@staix/agent-hub 0.44.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 (100) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +3 -8
  3. package/docs/agent-notes/adapters.md +2 -2
  4. package/docs/agent-notes/daemon.md +1 -1
  5. package/docs/agent-notes/local-worker.md +1 -1
  6. package/docs/agent-notes/security-review.md +1 -1
  7. package/docs/agent-notes/tasks.md +3 -1
  8. package/docs/agent-notes/tests.md +3 -2
  9. package/docs/design/adapters.md +4 -2
  10. package/docs/design/agent-hub.md +1 -1
  11. package/docs/design/roadmap.md +75 -2
  12. package/docs/design/supervision.md +21 -1
  13. package/docs/design/task-board.md +30 -2
  14. package/docs/dogfood.md +13 -4
  15. package/docs/events.md +5 -1
  16. package/docs/influences.md +7 -0
  17. package/docs/memory.md +4 -4
  18. package/docs/operations.md +51 -18
  19. package/docs/quickstart.md +8 -2
  20. package/docs/research.md +16 -0
  21. package/docs/roadmap.json +4 -0
  22. package/docs/roadmap.md +9 -0
  23. package/docs/sdlc.md +15 -3
  24. package/docs/security.md +3 -3
  25. package/docs/verification/2026-11-19-claude-implementer-2.1.328.md +49 -0
  26. package/docs/verification/2026-11-20-claude-implementer-2.1.329.md +49 -0
  27. package/docs/verification/2026-11-20-sdlc-metrics-diagnosis.md +7 -0
  28. package/docs/verification/2026-11-21-0.45.0.md +69 -0
  29. package/docs/verification/2026-11-22-codex-0171-reviewer-isolation.md +47 -0
  30. package/docs/verified.json +32 -26
  31. package/package.json +2 -2
  32. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  33. package/plugins/agent-hub/kimi-hook.js +472 -229
  34. package/plugins/agent-hub/kimi-review-policy-worker.js +5 -5
  35. package/plugins/agent-hub/server.js +513 -258
  36. package/scripts/check-docs.mjs +9 -1
  37. package/src/adapters/acp.ts +11 -1
  38. package/src/adapters/compat.ts +3 -3
  39. package/src/adapters/definitions/builtin-metadata.ts +2 -2
  40. package/src/adapters/definitions/native-context.ts +10 -0
  41. package/src/adapters/jcode.ts +10 -0
  42. package/src/adapters/local-worker.ts +3 -2
  43. package/src/adapters/pi.ts +15 -4
  44. package/src/cli/console-state.ts +3 -1
  45. package/src/cli/help.ts +3 -1
  46. package/src/cli/identity.ts +2 -1
  47. package/src/cli/main.ts +11 -5
  48. package/src/cli/recovery-package.ts +16 -3
  49. package/src/cli/roadmap-write.ts +59 -0
  50. package/src/cli/roadmap.ts +81 -4
  51. package/src/cli/sdlc-output.ts +4 -0
  52. package/src/cli/upgrade-runtime.ts +10 -6
  53. package/src/hub/agent-mem-range.ts +43 -0
  54. package/src/hub/board.ts +102 -1
  55. package/src/hub/check-runner.ts +25 -1
  56. package/src/hub/config-apply.ts +4 -2
  57. package/src/hub/config-trust.ts +1 -1
  58. package/src/hub/context-window.ts +1 -1
  59. package/src/hub/cost-governance.ts +11 -7
  60. package/src/hub/daemon.ts +253 -30
  61. package/src/hub/dogfood-read.ts +4 -2
  62. package/src/hub/edit-guard.ts +100 -0
  63. package/src/hub/events.ts +79 -8
  64. package/src/hub/facts.ts +57 -4
  65. package/src/hub/hub-tools.ts +2 -0
  66. package/src/hub/lifecycle.ts +6 -1
  67. package/src/hub/log-rotation.ts +130 -0
  68. package/src/hub/memory-profile.ts +137 -21
  69. package/src/hub/no-writes.ts +1 -0
  70. package/src/hub/operational-authority.ts +3 -2
  71. package/src/hub/operational-settings.ts +2 -2
  72. package/src/hub/recovery-store.ts +49 -21
  73. package/src/hub/research-experiments.ts +132 -0
  74. package/src/hub/research-quality.ts +8 -2
  75. package/src/hub/research-record.ts +35 -0
  76. package/src/hub/research.ts +128 -28
  77. package/src/hub/roadmap-check.ts +65 -0
  78. package/src/hub/roadmap-decompose.ts +80 -0
  79. package/src/hub/roadmap-export.ts +27 -0
  80. package/src/hub/roadmap-sync.ts +97 -0
  81. package/src/hub/roadmap.ts +40 -0
  82. package/src/hub/sdlc-branch-ci.ts +128 -0
  83. package/src/hub/sdlc-merge.ts +6 -3
  84. package/src/hub/sdlc-metrics.ts +19 -5
  85. package/src/hub/sdlc.ts +73 -5
  86. package/src/hub/settings.ts +1 -0
  87. package/src/hub/snapshots.ts +13 -1
  88. package/src/hub/startup-event-seeds.ts +21 -15
  89. package/src/hub/startup-timing.ts +3 -1
  90. package/src/hub/supervision-proposals.ts +10 -2
  91. package/src/hub/supervision-rules.ts +26 -3
  92. package/src/hub/supervision.ts +7 -0
  93. package/src/hub/task-pr.ts +47 -0
  94. package/src/hub/task-worktree.ts +18 -11
  95. package/src/hub/tasks.ts +502 -34
  96. package/src/hub/usage-rollup.ts +35 -20
  97. package/src/local/tools.ts +13 -1
  98. package/src/memory/client.ts +3 -2
  99. package/src/pi/extension.ts +15 -3
  100. 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";
@@ -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 { MERGE_READBACK_DEADLINE_MS, 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";
@@ -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. */
@@ -568,7 +577,9 @@ export interface ExperimentView { attempts: ExperimentAttemptView[]; counts: { a
568
577
  interface ExperimentContext { task: Task; campaign: ResearchCampaignRecord; private: boolean; key: string; fence: ExperimentWriteFence }
569
578
  interface CompletionRefresh { revision: number; commit: string; state: "in_review" | "approved" }
570
579
  interface RefileHeadGuard { recorded?: string }
571
- 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 } };
572
583
 
573
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. */
574
585
  export type DeliverableResult = "changed" | "missing" | "unknown" | "unchanged";
@@ -843,6 +854,8 @@ export class Tasks {
843
854
  private readonly planReviewRequests = new Map<number, string>();
844
855
  private readonly repositories: TaskRepositories;
845
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>>();
846
859
  private readonly plannerBacklog = new Map<PeerId, Set<number>>();
847
860
  private readonly plannerBlockedQueue = new Map<PeerId, string>();
848
861
  private readonly knownPlanners = new Set<PeerId>();
@@ -3556,6 +3569,227 @@ export class Tasks {
3556
3569
  return row;
3557
3570
  }
3558
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
+
3559
3793
  // ---- R3 (#1481): bottom-up placement. Reads are the roadmap read authority; every write below is the R1 writer, never a new one. ----
3560
3794
 
3561
3795
  /** The one repository the roadmap reads from GitHub: the caller's choice, else the project's. Never derived from model text. */
@@ -3635,6 +3869,134 @@ export class Tasks {
3635
3869
  return done(saved, parsed.dropped + parsed.suggestions.length - saved.length, null);
3636
3870
  }
3637
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
+
3638
4000
  /** Apply one suggestion through R1's own writers. A "new milestone" suggestion creates it first; a retry never creates a second. */
3639
4001
  async roadmapAccept(by: PeerId, rawId: unknown): Promise<{ suggestion: MilestoneSuggestion; milestone: MilestoneView }> {
3640
4002
  const current = this.roadmapWriteAuthority(by);
@@ -4209,7 +4571,7 @@ export class Tasks {
4209
4571
  return updated; // a failed readback may follow a durable release write
4210
4572
  }
4211
4573
 
4212
- async propose(by: PeerId, input: { title?: string; detail?: string; class?: string; role?: unknown; refs?: TaskRefs; plan?: TaskPlan; owner?: PeerId; after?: unknown; urgent?: unknown; needs_network?: unknown; needs_worktree?: unknown; backlog?: unknown; draft?: unknown; goal?: unknown }, external?: GitHubSource, created?: () => void, fence?: () => string | undefined, hostCreatedHook?: (task: Task) => void): Promise<Task> {
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> {
4213
4575
  const requestCheck = this.requestCheck(by, fence);
4214
4576
  const plan = cleanPlan(input.plan, this.d.profileData ?? this.d.profile ?? "dev", (this.d.sdlc?.config().mode ?? "off") !== "off");
4215
4577
  this.validatePlanSources(plan);
@@ -4218,7 +4580,13 @@ export class Tasks {
4218
4580
  if (external && (!this.personOrConductor(by) || input.backlog !== true)) throw new PreEffectToolRefusal("external intake requires person-owned backlog staging");
4219
4581
  if (input.backlog !== undefined && typeof input.backlog !== "boolean") throw new PreEffectToolRefusal("backlog must be a boolean");
4220
4582
  const backlog = input.backlog === true;
4221
- if (input.draft !== undefined && (input.draft !== true || !backlog || by !== USER)) throw new PreEffectToolRefusal("only the person's intake stages a backlog draft");
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");
4222
4590
  const claiming = !backlog && input.owner === by;
4223
4591
  if (claiming) {
4224
4592
  this.acceptanceCapacity({ id: -1, owner: by, state: "proposed" });
@@ -6682,13 +7050,14 @@ export class Tasks {
6682
7050
  * counts) and the staged PR only while the done's effective commit and branch are still the ones it was read for.
6683
7051
  */
6684
7052
  private withLink(task: Task, link: IdentityLink | undefined, refs?: TaskRefs): Task {
6685
- 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");
6686
7055
  const config = this.d.sdlc?.config() ?? sdlcConfig(undefined);
6687
7056
  let issue: { repo: string; issue: number } | undefined;
6688
- 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; } }
6689
7058
  const commit = refs?.commit ?? task.refs.commit, branch = refs?.branch ?? task.refs.branch;
6690
- const repository = task.sdlc?.repo ?? task.refs.repo ?? this.d.repository;
6691
- const pr = link && !task.sdlc?.pr && repository?.toLowerCase() === link.repo.toLowerCase() && link.basis.commit === commit && (commit !== undefined || link.basis.branch === branch) ? link : undefined;
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;
6692
7061
  let next = task.sdlc;
6693
7062
  if (issue) next = linkedReceipt(next, issue, config) ?? next;
6694
7063
  if (pr) next = linkedReceipt(next, { repo: pr.repo, pr: pr.pr }, config) ?? next;
@@ -6808,7 +7177,7 @@ export class Tasks {
6808
7177
  for (const stall of this.stalled()) if (visibleIds.has(stall.task)) byKind[stall.cause.kind] = (byKind[stall.cause.kind] ?? 0) + 1;
6809
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 };
6810
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.
6811
- 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> = {};
6812
7181
  for (const task of rows) {
6813
7182
  const guarded = task.sdlc?.merge;
6814
7183
  const merge = guarded?.state === "merged" ? guarded : task.sdlc?.mergeReadback;
@@ -6816,9 +7185,9 @@ export class Tasks {
6816
7185
  const cost = cleanMergeCost(merge.cost);
6817
7186
  const at = cost?.mergedAt ?? (merge === guarded && Number.isSafeInteger(merge.at) ? merge.at : null);
6818
7187
  if (at !== null) mergedAt[task.id] = at;
6819
- if (cost) { ciReruns[task.id] = cost.ciReruns; ciRuns[task.id] = cost.ciRuns; reviews[task.id] = cost.reviews; }
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; }
6820
7189
  }
6821
- return { ...sdlcMetrics(tasks, { ...(cutoff !== undefined ? { since: cutoff } : {}), ...(this.d.sdlc?.config().bands ? { bands: this.d.sdlc.config().bands } : {}), stalls, mergedAt, ciReruns, ciRuns, reviews, external: this.externalSeries(), ...(merged ?? {}) }), ...(this.securityScanCounts() ? { securityScan: this.securityScanCounts() } : {}) };
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() } : {}) };
6822
7191
  }
6823
7192
 
6824
7193
  /** Latest configured scan source counts; no repository or alert text is projected. */
@@ -7786,11 +8155,12 @@ export class Tasks {
7786
8155
  current();
7787
8156
  const gates = adoptMergeGates(evidence, head, requiredChecksFor(config, repo));
7788
8157
  if (gates.length) throw new PreEffectToolRefusal(gates.join("; "));
7789
- const costDeadline = performance.now() + MERGE_READBACK_DEADLINE_MS;
8158
+ const costDeadline = performance.now() + INLINE_MERGE_READBACK_DEADLINE_MS;
7790
8159
  const cost = evidence?.costSnapshot ? await readPrCostHistory(repo, pr as number, (args, timeout, cwd, cap) => {
7791
8160
  const remaining = costDeadline - performance.now();
7792
- return remaining > 0 ? run(args, Math.min(timeout ?? remaining, remaining), cwd, cap) : Promise.resolve({ code: 1, stdout: "" });
7793
- }, evidence.costSnapshot, head).then(pr => pr?.complete ? mergeCostFrom(pr) : undefined, () => undefined) : undefined;
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;
7794
8164
  const latest = current();
7795
8165
  const merge: ReadbackMergeRecord = { repo, pr: pr as number, head, at: Date.now(), state: "merged", ...(evidence?.mergeCommit ? { mergeCommit: evidence.mergeCommit } : {}), ...(cost ? { cost } : {}) };
7796
8166
  const capacity = this.capacityBefore(latest);
@@ -7840,7 +8210,7 @@ export class Tasks {
7840
8210
  this.mergesInFlight.add(task.id);
7841
8211
  try {
7842
8212
  const links = this.deliveryLinks(config), subject = links.find(link => link.id === task.id)!;
7843
- const outcome = await guardedMerge({ mode, subject, state: task.state, taskState: n => this.d.board.get(n)?.state, config, tasks: links, run: this.d.sdlc?.gh ?? sdlcGh, readableMetadata: this.publicMetadataText,
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,
7844
8214
  recordMerge: record=>this.recordMergeResult(task.id,by,record,artifactCurrent),
7845
8215
  beforeMerge: queue => {
7846
8216
  if (!this.mergeAuthority(by)) return "merge authority changed during the merge check: nothing was run";
@@ -7881,8 +8251,9 @@ export class Tasks {
7881
8251
  async captureExternalMerge(id: number): Promise<"merged" | "closed" | "retry" | "skip"> {
7882
8252
  const task = this.d.board.get(id), config = this.d.sdlc?.config(), receipt = task?.sdlc;
7883
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;
7884
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)
7885
- || this.repositories.scope(task.refs).key !== this.repositories.scope({ repo }).key || mergeModeFor(config, repo) !== "off" || (receipt?.merge?.state === "merged" || receipt?.mergeReadback?.state === "merged") || this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) return "skip";
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";
7886
8257
  const identity = JSON.stringify([task.history.length, task.updated, task.owner, receipt, config]);
7887
8258
  const current = () => {
7888
8259
  const now = this.d.board.get(id), policy = this.d.sdlc?.config();
@@ -7898,9 +8269,15 @@ export class Tasks {
7898
8269
  if (!current()) return "skip";
7899
8270
  if (evidence?.state === "CLOSED") return "closed";
7900
8271
  if (evidence?.state !== "MERGED" || evidence.head !== head) return "retry";
7901
- const cost = await readPrCostHistory(repo, pr, run, undefined, head).then(value => value?.complete ? mergeCostFrom(value) : undefined, () => undefined);
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);
7902
8273
  if (!current()) return "skip";
7903
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
+ }
7904
8281
  const merge: ReadbackMergeRecord = { repo, pr, head, at: Date.now(), state: "merged", ...(evidence.mergeCommit ? { mergeCommit: evidence.mergeCommit } : {}), ...(cost ? { cost } : {}) };
7905
8282
  this.d.board.update(id, HUB, "merge observed", { sdlc: { ...now.sdlc!, mergeReadback: merge } }, undefined, {}, now.history.length);
7906
8283
  return "merged";
@@ -7918,8 +8295,9 @@ export class Tasks {
7918
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);
7919
8296
  for (const task of candidates) {
7920
8297
  if (reads >= 3 || this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) break;
7921
- if (task.state !== "approved" || this.isPii(task) || !task.sdlc?.repo || !task.sdlc.pr || task.sdlc.merge || task.sdlc.mergeReadback) { this.mergeReadbackSchedule.delete(task.id); continue; }
7922
- const approval = task.history.findLastIndex(entry => entry.event === "approved" || entry.event === "done" && entry.by === task.owner);
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);
7923
8301
  const at = task.history[approval]?.at;
7924
8302
  if (approval < 0 || at === undefined || now < at || now - at >= 24 * 60 * 60_000) { this.mergeReadbackSchedule.delete(task.id); continue; }
7925
8303
  const previous = this.mergeReadbackSchedule.get(task.id);
@@ -8392,6 +8770,9 @@ export class Tasks {
8392
8770
  } else if (approvalHead && currentHead && currentHead !== approvalHead) throw this.reviewHeadMoveRefusal(task.id, approvalHead, currentHead);
8393
8771
  const integrity = publicTestIntegrity(receipt && evidence && !this.isPii(task) ? await readTestIntegrity(receipt, evidence, read) : this.unknownTestIntegrity(this.isPii(task)), this.publicMetadataText);
8394
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;
8395
8776
  const current = this.need(task.id, false, true);
8396
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`);
8397
8778
  // Advise may continue on the current task, but evidence from its previous link cannot admit that task's review.
@@ -8402,7 +8783,12 @@ export class Tasks {
8402
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.
8403
8784
  const evalNames = evalRequiredChecks(config, evidence).filter(name => !config.requiredChecks.includes(name));
8404
8785
  const evalBlocker = (blocker: string) => evalNames.some(name => blocker.startsWith(`required check ${name}:`)) || evalGapBlockers(status.evalGate).includes(blocker);
8405
- const blockers = transition === "review" ? [...new Set([...status.blockers.filter(blocker => ["lifecycle stage definition unknown", "issue identity missing", "PR identity missing", "current PR evidence unknown", "PR is not open", "local gate on current head missing or failed"].includes(blocker) || blocker.startsWith("test integrity:") || evalBlocker(blocker)), ...(status.entry ?? []), ...(status.exit ?? [])])] : status.blockers;
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
+ ));
8406
8792
  if (config.mode === "enforce" && blockers.length) throw new PreEffectToolRefusal(`task #${task.id}: SDLC ${transition} blocked: ${blockers.join("; ")}`);
8407
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.
8408
8794
  const gate = status.evalGate;
@@ -8733,10 +9119,63 @@ export class Tasks {
8733
9119
  const task = this.need(id, false, true);
8734
9120
  this.mine(task, by, "owner", true);
8735
9121
  if (this.isPii(task) || !port.describe(by, task.id)) return undefined;
8736
- const result = await port.commitAndPush({ peer: by, task: task.id, title: task.title });
8737
- if (!result.ok) throw new PreEffectToolRefusal(`hub_task_done for task #${task.id}: ${result.reason}`);
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();
8738
9139
  if (result.note) this.doneNotes.set(task.id, result.note);
8739
- 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);
8740
9179
  }
8741
9180
 
8742
9181
  /** Decline or cancel: clear the hub-made worktree and its empty branch. Uncommitted work is kept and reported, never force-removed. */
@@ -8945,6 +9384,14 @@ export class Tasks {
8945
9384
  }
8946
9385
 
8947
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> {
8948
9395
  const observerExcluded = this.observerExcluded(by);
8949
9396
  const requestCheck = this.requestCheck(by);
8950
9397
  const initial = this.need(id, false, true);
@@ -8989,12 +9436,32 @@ export class Tasks {
8989
9436
  task = valid();
8990
9437
  }
8991
9438
  // #694: stage the identities the hub can verify; the gates read them, and only the admitted done persists them.
8992
- const link = this.d.sdlc && this.d.sdlc.config().mode !== "off" ? await this.identityLink(task, refs) : undefined;
8993
- const current = () => this.stagedSpec(by, this.withLink(valid(), link, refs), specCarry);
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));
8994
9461
  task = current();
8995
9462
  let reviewEvidence: PrEvidence | undefined;
8996
9463
  if (this.d.sdlc && this.d.sdlc.config().mode !== "off") { reviewEvidence = await this.lifecycleGate(task, "review", undefined, undefined, refileHead); task = current(); }
8997
- const reviewAdmission = task.reviewer || this.d.prepareReviewBrief ? await this.reviewRequestAdmission(task, refs, true, by, reviewEvidence, undefined, staged => this.stagedSpec(by, this.withLink(this.completionDraft(staged, draft), link, refs), specCarry), !task.reviewer, refileHead) : undefined;
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;
8998
9465
  task = current();
8999
9466
  if (refileHead && (this.d.sdlc?.config().mode ?? "off") === "off") {
9000
9467
  const currentHead = await this.currentPrHeadForReview(task, current);
@@ -9025,8 +9492,8 @@ export class Tasks {
9025
9492
  if (r.action === "request") return write(task.id, HUB, "integration requested", {}, this.integrationRequest(task, r));
9026
9493
  if (r.action === "unresolved") {
9027
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`);
9028
- task = this.withLink(write(task.id, HUB, "integration unresolved", {}, r.why), link, refs);
9029
- } else if (r.integrated) task = this.withLink(write(task.id, HUB, "integrated", {}, `cohort #${cohort!.id}, revision ${cohort!.revision}`), link, refs);
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);
9030
9497
  } else if (cohort?.held.size && !this.isPii(task)) {
9031
9498
  // No integration step for this member (silence lifted, a PII task open): the notices the silence held stand in
9032
9499
  // for it (issue #107, AC4).
@@ -9034,7 +9501,7 @@ export class Tasks {
9034
9501
  if (evidence && by === USER) this.d.notify(`task ${this.publicTitle(task)} done by the console; overlapping work finished meanwhile:\n${evidence}`);
9035
9502
  else if (evidence) this.doneNotes.set(task.id, `Overlapping work finished while you worked (no turn-free integration step ran):\n${evidence}`);
9036
9503
  }
9037
- if (task.state === "proposed" || task.state === "changes_requested") task = this.withLink(write(task.id, by, "accepted", { state: "in_progress" }, WITH_DONE), link, refs); // done without a separate accept
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
9038
9505
  const command = this.d.runCheck ? this.d.check?.(task.class, task) : undefined;
9039
9506
  if (!command) return this.complete(task, by, summary, refs, "", withheld, "review", reviewAdmission, link, records, requestCheck, refresh, specInspection, false, resolvedReviewComments, reviewObserverTurn);
9040
9507
  // The tool call returns now; a check can outlast an agent's tool timeout. The result decides what comes next.
@@ -9471,6 +9938,7 @@ export class Tasks {
9471
9938
  const head = admission.head ?? this.reviewHead(task) ?? "unknown head";
9472
9939
  if (admission.ready) {
9473
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`;
9474
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`;
9475
9943
  }
9476
9944
  return `Hub-verified at ${head}: not ready: ${admission.blockers.join("; ")}.\n`;
@@ -9507,7 +9975,7 @@ export class Tasks {
9507
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.
9508
9976
  const codeScoped = this.d.reviewScope?.(reviewer) === "code";
9509
9977
  const verified = codeScoped ? "" : this.hubVerifiedBlock(task, admission);
9510
- const ciPassed = admission?.ready === true && !this.isPii(task);
9978
+ const ciPassed = admission?.ready === true && !admission.deferred?.length && !this.isPii(task);
9511
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.
9512
9980
  const checkResult = codeScoped ? CODE_SCOPE_LINE
9513
9981
  : check ? `Check result: ${(check.note ?? "").split("\n")[0]}`