@staix/agent-hub 0.39.0 → 0.40.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 (110) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +12 -6
  3. package/docs/adding-an-ai-tool.md +1 -1
  4. package/docs/agent-notes/README.md +7 -0
  5. package/docs/agent-notes/adapters.md +5 -3
  6. package/docs/agent-notes/benchmarks.md +2 -0
  7. package/docs/agent-notes/budget.md +1 -0
  8. package/docs/agent-notes/bus.md +1 -0
  9. package/docs/agent-notes/daemon.md +8 -3
  10. package/docs/agent-notes/local-worker.md +3 -1
  11. package/docs/agent-notes/security-review.md +1 -0
  12. package/docs/agent-notes/tasks.md +7 -2
  13. package/docs/agent-notes/tests.md +7 -7
  14. package/docs/contracts/companion-cli-v1.json +4 -0
  15. package/docs/design/adapters.md +91 -0
  16. package/docs/design/agent-hub-architecture.md +17 -0
  17. package/docs/design/agent-hub.md +10 -0
  18. package/docs/design/bus.md +7 -0
  19. package/docs/design/cli-output.md +183 -0
  20. package/docs/design/execution-reference.md +6 -1
  21. package/docs/design/roadmap.md +191 -0
  22. package/docs/design/task-board.md +34 -0
  23. package/docs/dogfood.md +11 -4
  24. package/docs/events.md +4 -4
  25. package/docs/memory.md +3 -3
  26. package/docs/operations.md +153 -41
  27. package/docs/profiles.md +1 -0
  28. package/docs/quickstart.md +17 -4
  29. package/docs/sdlc.md +3 -1
  30. package/docs/security.md +40 -4
  31. package/docs/verification/2026-11-14-codex-0169-reviewer-isolation.md +70 -0
  32. package/docs/verification/2026-11-14-codex-0169-reviewer-tool-call.md +48 -0
  33. package/docs/verification/2026-11-14-pi-152-compat.md +45 -0
  34. package/docs/verification/2026-11-15-0.40.0.md +39 -0
  35. package/docs/verification/2026-11-16-pi-loopback-1447.md +39 -0
  36. package/docs/verification/pi-152-model-free.ts +57 -0
  37. package/docs/verification/pi-152-native.mjs +21 -0
  38. package/docs/verified.json +22 -22
  39. package/package.json +3 -3
  40. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  41. package/plugins/agent-hub/kimi-hook.js +332 -89
  42. package/plugins/agent-hub/kimi-review-policy-worker.js +16 -11
  43. package/plugins/agent-hub/server.js +417 -160
  44. package/src/adapters/agy/definition.ts +1 -1
  45. package/src/adapters/claude-channel.ts +1 -1
  46. package/src/adapters/codex-review-isolation.ts +61 -17
  47. package/src/adapters/compat.ts +7 -7
  48. package/src/adapters/definitions/builtin-metadata.ts +6 -6
  49. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  50. package/src/adapters/definitions/native-config-policy.ts +1 -1
  51. package/src/adapters/definitions/qwen.ts +1 -1
  52. package/src/adapters/local-worker.ts +5 -3
  53. package/src/adapters/pi.ts +54 -11
  54. package/src/adapters/registry-types.ts +2 -1
  55. package/src/adapters/reviewer-print.ts +2 -1
  56. package/src/cli/answer-args.ts +11 -3
  57. package/src/cli/console-question.ts +1 -1
  58. package/src/cli/console-state.ts +95 -10
  59. package/src/cli/console.ts +6 -2
  60. package/src/cli/error-format.ts +19 -0
  61. package/src/cli/help.ts +290 -25
  62. package/src/cli/identity-audit.ts +8 -7
  63. package/src/cli/identity.ts +17 -0
  64. package/src/cli/init.ts +102 -9
  65. package/src/cli/main.js +2 -2
  66. package/src/cli/main.ts +57 -21
  67. package/src/cli/output-standard.ts +56 -0
  68. package/src/cli/output.ts +143 -8
  69. package/src/cli/roadmap.ts +215 -0
  70. package/src/cli/smoke-pty-bridge.ts +7 -24
  71. package/src/cli/task-output.ts +3 -1
  72. package/src/cli/upgrade-presentation-flags.ts +2 -2
  73. package/src/hub/board.ts +200 -3
  74. package/src/hub/bus.ts +9 -0
  75. package/src/hub/check-runner.ts +3 -4
  76. package/src/hub/ci-watch.ts +19 -4
  77. package/src/hub/control-client.ts +1 -1
  78. package/src/hub/daemon.ts +245 -43
  79. package/src/hub/events.ts +2 -2
  80. package/src/hub/execution-reference.ts +1 -1
  81. package/src/hub/github-import.ts +81 -0
  82. package/src/hub/hub-tools.ts +34 -9
  83. package/src/hub/install-policy.ts +23 -0
  84. package/src/hub/lifecycle-schema.ts +2 -2
  85. package/src/hub/no-writes.ts +3 -0
  86. package/src/hub/operational-authority.ts +3 -1
  87. package/src/hub/operational-view.ts +1 -1
  88. package/src/hub/pi-failure.ts +7 -0
  89. package/src/hub/question-desk.ts +26 -7
  90. package/src/hub/questions.ts +33 -5
  91. package/src/hub/restart.ts +7 -0
  92. package/src/hub/roadmap-triage.ts +86 -0
  93. package/src/hub/roadmap-unplaced.ts +169 -0
  94. package/src/hub/roadmap-view.ts +83 -0
  95. package/src/hub/roadmap.ts +127 -0
  96. package/src/hub/sdlc-merge.ts +5 -4
  97. package/src/hub/sdlc-queue.ts +3 -3
  98. package/src/hub/sdlc.ts +37 -2
  99. package/src/hub/specs-task.ts +7 -0
  100. package/src/hub/task-sweep.ts +29 -2
  101. package/src/hub/task-worktree.ts +37 -0
  102. package/src/hub/tasks.ts +381 -7
  103. package/src/pi/dependency-publish.ts +50 -0
  104. package/src/pi/extension.ts +1 -1
  105. package/src/pi/launch.ts +1 -1
  106. package/src/pi/task-dependencies.ts +249 -0
  107. package/src/ui/index.html +53 -13
  108. package/src/ui/plugin-questions.ts +5 -0
  109. package/src/ui/plugin.ts +6 -1
  110. package/templates/config.json +1 -1
@@ -60,7 +60,15 @@ export function nextSweep(task: Task, config: TaskSweepConfig, now: number, read
60
60
  if (!kind) return undefined;
61
61
  let activity = task.history.length - 1;
62
62
  while (activity >= 0 && (task.history[activity]?.sweep || task.history[activity]?.event === "memory reference started")) activity--;
63
- const at = task.history[activity]?.at ?? task.created;
63
+ let at = task.history[activity]?.at ?? task.created;
64
+ if (kind === "idle-owner") {
65
+ // #1454: a pending wait suspends the ladder; once it passes, the ladder restarts from `until`, not from the activity before it.
66
+ const wait = taskWait(task);
67
+ if (wait) {
68
+ if (now < wait.until) return undefined;
69
+ at = Math.max(at, wait.until);
70
+ }
71
+ }
64
72
  const threshold = kind === "ready-unassigned" ? config.ready_min ?? 60 : kind === "unaccepted-assignment" ? config.unaccepted_min : kind === "idle-owner" ? config.idle_min : config.review_min;
65
73
  if (now - at < threshold * 60_000) return undefined;
66
74
  const previous = task.history.flatMap((h) => h.sweep?.kind === kind && h.sweep.activity === activity ? [h.sweep] : []).at(-1);
@@ -68,13 +76,30 @@ export function nextSweep(task: Task, config: TaskSweepConfig, now: number, read
68
76
  return { kind, activity, step: previous ? (previous.step + 1) as 2 | 3 : 1, at: now };
69
77
  }
70
78
 
79
+ /** #1454: the longest a bounded wait may reach ahead of the moment it is recorded. */
80
+ export const TASK_WAIT_MAX_MS = 14 * 24 * 3_600_000;
81
+ /** #1454: the reason a wait carries is public text; longer text is refused, never cut. */
82
+ export const TASK_WAIT_REASON_MAX = 200;
83
+ /** History events that leave a recorded wait in force: bookkeeping that neither moves the task nor is owner activity on it. Anything else (done, decline, return, reassignment, cancel) ends it. */
84
+ const WAIT_KEEPING_EVENTS = new Set(["wait recorded", "idle sweep", "answer", "reviewer changed", "memory reference started", "ready held", "plan observed", "planner changed", "claim verdict", "invocation", "shell branch bound"]);
85
+ export interface TaskWait { until: number; at: number; by: string; owner: string }
86
+ /** The wait that is still in force on an in_progress task: the latest `wait recorded` entry, for the current owner, with no state-changing entry after it. A passed `until` still counts (the planner groom view lists it); `nextSweep` is what lets the ladder restart. */
87
+ export function taskWait(task: Pick<Task, "state" | "owner" | "history">): TaskWait | undefined {
88
+ if (task.state !== "in_progress" || !task.owner) return undefined;
89
+ const index = task.history.findLastIndex(entry => entry.wait !== undefined);
90
+ const entry = task.history[index];
91
+ if (!entry?.wait || entry.event !== "wait recorded" || entry.wait.owner !== task.owner) return undefined;
92
+ if (task.history.slice(index + 1).some(later => !WAIT_KEEPING_EVENTS.has(later.event))) return undefined;
93
+ return { until: entry.wait.until, at: entry.at, by: entry.by, owner: entry.wait.owner };
94
+ }
95
+
71
96
  /** A planned start is the earliest automatic start time; the card is eligible at that boundary. */
72
97
  export function plannedStartPending(task: Pick<Task, "plannedStart">, now: number): boolean {
73
98
  return task.plannedStart != null && (!Number.isFinite(now) || task.plannedStart > now);
74
99
  }
75
100
 
76
101
  export interface GroomingItem {
77
- kind: "text-dependency" | "overlap" | "duplicate" | "over-wip" | "stale" | "superseded" | "blocked" | "closed-issue" | "scheduled";
102
+ kind: "text-dependency" | "overlap" | "duplicate" | "over-wip" | "stale" | "superseded" | "blocked" | "closed-issue" | "scheduled" | "wait-passed";
78
103
  task: number;
79
104
  related?: number[];
80
105
  code?: string;
@@ -173,6 +198,8 @@ export function plannerGrooming(tasks: readonly Task[], options: PlannerGrooming
173
198
  if (task.state === "cancelled") continue; // Closed rows contribute supersession evidence only.
174
199
  if ((task.state === "backlog" || task.state === "proposed" && !task.owner) && options.now !== undefined && plannedStartPending(task, options.now))
175
200
  add({ kind: "scheduled", task: task.id });
201
+ // #1454: a wait that has passed is shown here, so a stale one is seen rather than silently restarting the idle ladder.
202
+ if (options.now !== undefined && taskWait(task) && taskWait(task)!.until <= options.now) add({ kind: "wait-passed", task: task.id });
176
203
  const issues = new Set<number>();
177
204
  for (const issue of [task.external?.issue, task.sdlc?.issue]) {
178
205
  if (issue === undefined) continue;
@@ -8,6 +8,7 @@ import type { PeerId } from "./envelope.ts";
8
8
  import { hubGitArgv, hubGitEnv, hubGitSync } from "./git.ts";
9
9
  import { grantablePath } from "./permission-mode.ts";
10
10
  import { realPath } from "./project.ts";
11
+ import type { DependencyPreparation } from "../pi/task-dependencies.ts";
11
12
 
12
13
  /**
13
14
  * #1115: a hub-sandboxed peer (Pi, the local worker) cannot run `git worktree add` or commit, because its profile refuses `.git` writes that
@@ -39,6 +40,9 @@ export interface TaskWorktreePort {
39
40
  available(): TaskWorktreeAvailability;
40
41
  create(input: { peer: PeerId; task: number }): TaskWorktreeResult;
41
42
  describe(peer: PeerId, task: number): Pick<TaskWorktreeEntry, "path" | "branch" | "base"> | undefined;
43
+ prepareDependencies?(input: { peer: PeerId; task: number; current: () => boolean }): Promise<void>;
44
+ preparesDependencies?(peer: PeerId): boolean;
45
+ dependencyState?(peer: PeerId, task: number): DependencyPreparation | undefined;
42
46
  commitAndPush(input: { peer: PeerId; task: number; title: string }): Promise<TaskWorktreeCommit>;
43
47
  remove(input: { peer: PeerId; task: number }): TaskWorktreeRemoval;
44
48
  }
@@ -77,10 +81,42 @@ export class TaskWorktrees implements TaskWorktreePort {
77
81
  private readonly root: string;
78
82
  private chain: Promise<unknown> = Promise.resolve();
79
83
  private cached?: { at: number; value: TaskWorktreeAvailability };
84
+ private dependencyPreparers = new Map<PeerId, (cwd: string, current: () => boolean, base: string) => Promise<DependencyPreparation>>();
85
+ private dependencyRuns = new Map<string, Promise<void>>();
86
+ private dependencyStates = new Map<string, { path: string; state: DependencyPreparation }>();
80
87
  constructor(private readonly o: TaskWorktreeOptions) { this.root = realPath(o.root); }
81
88
 
82
89
  applies = (peer: PeerId): boolean => this.o.applies(peer);
83
90
 
91
+ /** Host adapter registration only; a peer/tool cannot choose an installer or environment. */
92
+ registerDependencyPreparation(peer: PeerId, prepare: (cwd: string, current: () => boolean, base: string) => Promise<DependencyPreparation>): void {
93
+ this.dependencyPreparers.set(peer, prepare);
94
+ }
95
+ preparesDependencies = (peer: PeerId): boolean => this.dependencyPreparers.has(peer);
96
+
97
+ prepareDependencies(input: { peer: PeerId; task: number; current: () => boolean }): Promise<void> {
98
+ const { peer, task, current } = input, prepare = this.dependencyPreparers.get(peer), entry = this.describe(peer, task);
99
+ if (!prepare || !entry || !current()) return Promise.resolve();
100
+ const key = this.key(peer, task), running = this.dependencyRuns.get(key);
101
+ // A repeated accept may supersede the running request's authority. Serialize
102
+ // installs, then prepare under this caller instead of adopting its stale run.
103
+ if (running) return running.then(() => current() ? this.prepareDependencies(input) : undefined);
104
+ this.dependencyStates.delete(key);
105
+ const run = (async () => {
106
+ let state: DependencyPreparation;
107
+ try { state = await prepare(entry.path, current, entry.base); }
108
+ catch { state = { ready: false, reason: "install failed" }; }
109
+ if (current() && this.describe(peer, task)?.path === entry.path) this.dependencyStates.set(key, { path: entry.path, state });
110
+ })().finally(() => { if (this.dependencyRuns.get(key) === run) this.dependencyRuns.delete(key); });
111
+ this.dependencyRuns.set(key, run);
112
+ return run;
113
+ }
114
+
115
+ dependencyState(peer: PeerId, task: number): DependencyPreparation | undefined {
116
+ const saved = this.dependencyStates.get(this.key(peer, task));
117
+ return saved && this.describe(peer, task)?.path === saved.path ? saved.state : undefined;
118
+ }
119
+
84
120
  /** `extra` is merged after the isolation, which strips GIT_INDEX_FILE: only the hub's own private index passes through it. */
85
121
  private git(args: string[], cwd = this.root, timeout = GIT_TIMEOUT_MS, extra: Record<string, string> = {}): Run {
86
122
  const run = hubGitSync(["-C", cwd, "-c", "gc.auto=0", "-c", "maintenance.auto=false", ...args], { encoding: "utf8", timeout, maxBuffer: 8 * 1024 * 1024, env: { ...hubGitEnv(childEnv(), { repositoryIsolation: true }), ...extra } });
@@ -304,6 +340,7 @@ export class TaskWorktrees implements TaskWorktreePort {
304
340
  */
305
341
  remove(input: { peer: PeerId; task: number }): TaskWorktreeRemoval {
306
342
  const { peer, task } = input;
343
+ this.dependencyStates.delete(this.key(peer, task));
307
344
  let records: Record<string, TaskWorktreeEntry>;
308
345
  try { records = this.readRecords(); } catch (error) { return { removed: false, branchDeleted: false, kept: (error as Error).message }; }
309
346
  const entry = records[this.key(peer, task)];
package/src/hub/tasks.ts CHANGED
@@ -1,4 +1,8 @@
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";
3
+ import { milestoneViews, type MilestoneView, type RoadmapSnapshot } from "./roadmap-view.ts";
4
+ import { computeUnplaced, withTree, type ReadyToClose, type TreeRollup, type UnplacedResult } from "./roadmap-unplaced.ts";
5
+ import { buildTriagePrompt, parseTriage, TRIAGE_BATCH, type TriageItem } from "./roadmap-triage.ts";
2
6
  import { pathCandidates } from "@staix/agent-mem";
3
7
  import { renderGuidanceVariantV1 } from "./guidance-variants.ts";
4
8
  import { GuidanceProbeFixtureHost, type GuidanceProbeStore } from "./guidance-probe-store.ts";
@@ -69,7 +73,7 @@ import type { InstancesConfig } from "./instances.ts";
69
73
  import { composeRememberText } from "./memory-fail.ts";
70
74
  import { VERSION } from "../version.ts";
71
75
  import { NoWriteTurns } from "./no-writes.ts";
72
- import { readGitHubImport, type GitHubSource, type GitHubImportSelection } from "./github-import.ts";
76
+ import { readGitHubImport, readGitHubIssuePages, readGitHubMilestonePages, type GitHubSource, type GitHubImportSelection } from "./github-import.ts";
73
77
  import { BACKLOG_SPLIT_SCREEN_TIMEOUT_MS, actualTaskDates, planningPatch, type PlanningFields, type Release, type ReleaseState } from "./planning.ts";
74
78
  import { readMergeQueue, type DeliveryTask, type MergeQueue } from "./sdlc-queue.ts";
75
79
  import { adoptMergeGates, guardedMerge, mergeModeFor, mergeView, readAdoptMergeEvidence, requiredChecksFor, type MergeView } from "./sdlc-merge.ts";
@@ -120,7 +124,7 @@ import { DEFAULT_SPECS_CONFIG, type SpecsConfig } from "./specs-config.ts";
120
124
  import type { SpecsCheckReport, SpecsCoverReport } from "./specs.ts";
121
125
  import { definitionOf as builtinDefinitionOf } from "../adapters/registry.ts";
122
126
  import { ADAPTERS, DEFAULT_REVIEW_POOL, definitionOf, familyOf, type ProjectAdapterCatalog } from "../adapters/registry.ts";
123
- import { plannerGrooming, nextSweep, plannedStartPending, taskSweepConfig, type TaskSweepConfig, type SweepRecord } from "./task-sweep.ts";
127
+ import { plannerGrooming, nextSweep, plannedStartPending, taskSweepConfig, taskWait, TASK_WAIT_MAX_MS, TASK_WAIT_REASON_MAX, type TaskSweepConfig, type SweepRecord } from "./task-sweep.ts";
124
128
  import { CiWatchers, pollCi, type CiOutcome, type CiWatch } from "./ci-watch.ts";
125
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";
126
130
 
@@ -225,6 +229,12 @@ export interface TasksDeps {
225
229
  specsConfig?: () => SpecsConfig;
226
230
  /** Explicit, read-only inspection remains available when task notices are disabled. */
227
231
  specsRead?: (action: "check" | "covers", paths: readonly string[]) => SpecsCheckReport | SpecsCoverReport;
232
+ /** R3 (#1481): spec ids with their status, for the unplaced list. Absent or throwing is "unavailable", never "no specs". */
233
+ specsList?: () => { specs: { id: string; title: string; status: string | null }[]; errors: number; truncated: boolean };
234
+ /** R3 (#1481): the model for triage. Absent, off or failing is no suggestion; it carries no authority and links nothing. */
235
+ roadmapModel?: (system: string, user: string, allowed: () => boolean) => Promise<string | undefined>;
236
+ /** R3 (#1481): host-only `gh` runner for the roadmap's read-only issue and milestone reads (tests); production uses `sdlc.gh`. */
237
+ roadmapGh?: SdlcGh;
228
238
  /** Host-verified existing symbols at this task's admitted completion head; never plan guesses. */
229
239
  memorySymbolNodes?: (task: Task) => MemorySymbolNodes | undefined;
230
240
  /** Host-only release report selector; derives its answer from committed policy and the in-memory authorization ledger. */
@@ -397,6 +407,7 @@ QUIET_EVENTS.add("plan observed"); // Host observation does not move the task or
397
407
  QUIET_EVENTS.add("planner changed"); // Planning authority does not move the execution owner or revoke its handoff.
398
408
  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".
399
409
  QUIET_EVENTS.add("invocation");
410
+ 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".
400
411
  QUIET_EVENTS.add("shell branch bound"); // #880: the hub's host-observed branch binding (#845) is bookkeeping; it neither moves nor settles the task.
401
412
  /** The records of the `done (checking)` entry a passed check now completes: what the owner delivered then (#509a). */
402
413
  const latestPendingDeliverables = (task: Task): DeliverableRecord[] | undefined => {
@@ -1020,6 +1031,44 @@ export class Tasks {
1020
1031
  return recorded;
1021
1032
  }
1022
1033
 
1034
+ /**
1035
+ * #1454: record a bounded wait on an in_progress task, so the idle-owner ladder is suspended until `until` and restarts from it.
1036
+ * Owner, its planner or the person only. The reason is public text: one the privacy screen would withhold is refused on an
1037
+ * ordinary task (the wait is shown in every board view), and kept withheld on a PII task. Every refusal is pre-effect and
1038
+ * names its cause and the next step. Done, decline, return and reassignment end a wait by moving the task (`taskWait`).
1039
+ */
1040
+ async wait(by: PeerId, input: { id: unknown; until: unknown; reason: unknown }): Promise<Task> {
1041
+ requireLocalTaskPeer(by);
1042
+ const refuse = (text: string): never => { throw new PreEffectToolRefusal(text); };
1043
+ if (!this.sweepConfig.enabled) refuse("a wait suspends the idle sweep and task_sweep is off, so there is nothing to suspend; just keep working, or ask the person to turn on task_sweep.enabled");
1044
+ const now = this.d.now?.() ?? Date.now();
1045
+ const until = typeof input.until === "number" ? input.until
1046
+ : typeof input.until === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/.test(input.until.trim()) ? Date.parse(input.until.trim()) : NaN;
1047
+ if (!Number.isSafeInteger(until)) refuse("until must be an absolute time with a zone, for example 2026-11-18T09:00:00+09:00 (or milliseconds since the epoch); resend with that");
1048
+ if (until <= now) refuse(`until ${new Date(until).toISOString()} is not in the future (now ${new Date(now).toISOString()}); name a later time, or drop the wait and keep working`);
1049
+ if (until > now + TASK_WAIT_MAX_MS) refuse(`until ${new Date(until).toISOString()} is more than 14 days ahead (latest ${new Date(now + TASK_WAIT_MAX_MS).toISOString()}); name an earlier time and record the wait again when it passes`);
1050
+ const reason = typeof input.reason === "string" ? input.reason.trim() : "";
1051
+ if (!reason) refuse("reason must be a short public sentence naming what the task waits for; resend with it");
1052
+ if ([...reason].length > TASK_WAIT_REASON_MAX || /[\u0000-\u001f\u007f]/.test(reason)) refuse(`reason must be one line of at most ${TASK_WAIT_REASON_MAX} characters; shorten it and resend`);
1053
+ const validate = (): Task => {
1054
+ const task = this.need(input.id, false, true);
1055
+ if (task.state !== "in_progress") refuse(`task #${task.id} is ${task.state}: a wait applies only to in_progress work; ${task.state === "proposed" ? "accept the task first with hub_task_accept" : "it needs no wait"}`);
1056
+ if (by !== USER && task.owner !== by && !(this.d.roles?.[by]?.includes("planner") && this.taskPlanner(task).includes(by)))
1057
+ refuse(`task #${task.id}: only its owner (${task.owner ?? "none"}), its planner or the console user can record a wait; ask the owner, or hub_send the planner`);
1058
+ if (by !== USER && this.d.privateTurn?.(by) && !this.isPii(task)) refuse("a wait on ordinary work is unavailable during a private turn; record it from a public turn");
1059
+ return task;
1060
+ };
1061
+ const before = validate(), revision = before.history.length;
1062
+ const pii = this.isPii(before);
1063
+ const withheld = looksSecret(reason) || this.aboutPrivatePath("", reason, before) || await this.withholds("note", reason, before);
1064
+ if (withheld && !pii) refuse("the reason would be withheld by the privacy screen and a wait is shown in every board view; restate it without names, paths or personal details");
1065
+ const task = validate();
1066
+ if (task.history.length !== revision) refuse(`task #${task.id}: it changed while the reason was screened; read it with hub_task_show and record the wait again`);
1067
+ const next = this.d.board.update(task.id, by, "wait recorded", {}, reason, { wait: { until, owner: task.owner! }, ...(pii || withheld ? { withheld: true as const } : {}) }, revision);
1068
+ this.d.notify(`task ${this.publicTitle(next)}: wait recorded by ${by} until ${new Date(until).toISOString()}`);
1069
+ return next;
1070
+ }
1071
+
1023
1072
  /** A validated snapshot takes effect on the next sweep, never halfway through one. */
1024
1073
  configureSweep(config: TaskSweepConfig): void {
1025
1074
  this.sweepConfig = taskSweepConfig(config);
@@ -1029,7 +1078,8 @@ export class Tasks {
1029
1078
  }
1030
1079
  }
1031
1080
 
1032
- private ownerAcceptance(task: Task, first = false): { index: number; at: number } | undefined {
1081
+ /** Host-only acceptance binding, shared by owner-turn evidence and bounded native continuations. */
1082
+ ownerAcceptance(task: Task, first = false): { index: number; at: number } | undefined {
1033
1083
  if (!task.owner) return undefined;
1034
1084
  const boundary = task.history.findLastIndex(entry => OWNERSHIP_EVENTS.has(entry.event) || entry.owner !== undefined && entry.owner !== task.owner);
1035
1085
  const accepted = (entry: Task["history"][number], index: number) => index > boundary && entry.event === "accepted" && (entry.by === task.owner || entry.by === USER);
@@ -1379,13 +1429,15 @@ export class Tasks {
1379
1429
  ...(h.planning ? { planning: { revision: h.planning.revision, fields: h.planning.fields, ...(h.planning.split ? { children: h.planning.split.children.map(child => child.id) } : {}) } } : {}),
1380
1430
  ...(h.reason && TASK_MOVE_REASONS.includes(h.reason) ? { reason: h.reason } : {}),
1381
1431
  ...(h.sweep ? { sweep: { kind: h.sweep.kind, activity: h.sweep.activity, step: h.sweep.step, at: h.sweep.at } } : {}),
1432
+ ...(h.wait ? { wait: { until: h.wait.until, owner: h.wait.owner } } : {}),
1382
1433
  ...(h === currentSpecEntry && currentSpecReport ? { specReport: currentSpecReport } : {}),
1383
1434
  }));
1384
1435
  const sets = this.reviewFindingSets(task), current = findingsForHead(sets, this.findingHead(task));
1385
1436
  const symbolRepository = codeSymbols && this.codeSymbolsRepository(task);
1386
1437
  const publicSymbols = codeSymbols && symbolRepository ? publicTaskCodeSymbols(codeSymbols, this.reviewHead(task), symbolRepository.key, this.publicMetadataText) : undefined;
1387
1438
  const handedOff = this.d.board.handoffOrigin(task.id); // #604: where another project's handoff came from; two ids, never text
1388
- return { ...rest, ...(claimBindings ? { claims: claimBindings } : {}), ...(currentSpecReport ? { specReport: currentSpecReport } : {}), ...(approvalBinding(task) ? { approval: approvalBinding(task) } : {}), ...(handedOff ? { handoffOrigin: { projectId: handedOff.projectId, peer: handedOff.peer, ...(handedOff.originTask === null ? {} : { task: handedOff.originTask }) } } : {}), ...(publicSymbols ? { codeSymbols: publicSymbols } : {}), ...(current.length ? { findings: findingTally(current) } : {}), ...(cancelled ? { cancelled: { ...cancelled, reason: screenHistoryText(cancelled.reason, "cancellation", cancelled.withheld), ...(cancelled.supersededBy ? { supersededBy: screenHistoryText(cancelled.supersededBy, "supersession", cancelled.withheld) } : {}) } } : {}), ...(external && this.nameable(external.url) ? { external } : {}), actualDates: actualTaskDates(task), ...(((this.d.sdlc?.config().mode ?? "off") !== "off" || this.d.sdlc?.config().workflow === "gsd-lite") ? { lifecycle: sdlcStatus(this.d.sdlc?.config() ?? sdlcConfig(undefined), task.sdlc, undefined, this.workflowView(task), undefined, sets, task.refs.commit) } : {}), title, detail, history: publicHistory };
1439
+ const wait = taskWait(task), waitEntry = wait ? history.findLast(h => h.wait) : undefined;
1440
+ return { ...rest, ...(wait && waitEntry ? { wait: { until: wait.until, by: wait.by, at: wait.at, passed: wait.until <= (this.d.now?.() ?? Date.now()), ...(waitEntry.note ? { reason: screenHistoryText(waitEntry.note, "wait reason", waitEntry.withheld) } : {}) } } : {}), ...(claimBindings ? { claims: claimBindings } : {}), ...(currentSpecReport ? { specReport: currentSpecReport } : {}), ...(approvalBinding(task) ? { approval: approvalBinding(task) } : {}), ...(handedOff ? { handoffOrigin: { projectId: handedOff.projectId, peer: handedOff.peer, ...(handedOff.originTask === null ? {} : { task: handedOff.originTask }) } } : {}), ...(publicSymbols ? { codeSymbols: publicSymbols } : {}), ...(current.length ? { findings: findingTally(current) } : {}), ...(cancelled ? { cancelled: { ...cancelled, reason: screenHistoryText(cancelled.reason, "cancellation", cancelled.withheld), ...(cancelled.supersededBy ? { supersededBy: screenHistoryText(cancelled.supersededBy, "supersession", cancelled.withheld) } : {}) } } : {}), ...(external && this.nameable(external.url) ? { external } : {}), actualDates: actualTaskDates(task), ...(((this.d.sdlc?.config().mode ?? "off") !== "off" || this.d.sdlc?.config().workflow === "gsd-lite") ? { lifecycle: sdlcStatus(this.d.sdlc?.config() ?? sdlcConfig(undefined), task.sdlc, undefined, this.workflowView(task), undefined, sets, task.refs.commit) } : {}), title, detail, history: publicHistory };
1389
1441
  }
1390
1442
 
1391
1443
  /** Console results expose direct approval and delivery holds, not just the chosen peer ids. */
@@ -3349,6 +3401,297 @@ export class Tasks {
3349
3401
  }
3350
3402
  return notified.size;
3351
3403
  }
3404
+ private roadmapReadAuthority(by: PeerId): void {
3405
+ requireLocalTaskPeer(by);
3406
+ if (this.d.privateTurn?.(by) || this.observerExcluded(by) || this.reviewObserverTurn(by)) throw new PreEffectToolRefusal("roadmap is unavailable during private or review-observer input; use ahub roadmap list after that turn");
3407
+ }
3408
+
3409
+ private roadmapWriteAuthority(by: PeerId): () => void {
3410
+ const check = this.requestCheck(by, () => this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError ? "roadmap writes are held by recovery, shutdown or storage; retry ahub roadmap list after recovery" : undefined);
3411
+ const current = () => {
3412
+ check(); this.roadmapReadAuthority(by);
3413
+ if (by !== USER && (!this.d.bus.isRostered(by) || !this.isConfiguredPlanner(by) && !this.configuredManualConductor(by)))
3414
+ throw new PreEffectToolRefusal("roadmap writes require a configured planner or the unique conductor; ask the person to run ahub roadmap");
3415
+ };
3416
+ current(); return current;
3417
+ }
3418
+
3419
+ private roadmapParsed<T>(read: () => T): T {
3420
+ try { return read(); }
3421
+ catch (error) { throw new PreEffectToolRefusal(`${error instanceof Error ? error.message : "invalid roadmap input"}; check ahub roadmap show and correct the fields`); }
3422
+ }
3423
+
3424
+ private roadmapCurrent(id: unknown, state?: MilestoneState): Milestone {
3425
+ const row = this.d.board.milestone(this.roadmapParsed(() => milestoneId(id)));
3426
+ if (!row) throw new PreEffectToolRefusal("roadmap milestone does not exist; use ahub roadmap list");
3427
+ if (["done", "dropped"].includes(row.state) && state !== row.state) throw new PreEffectToolRefusal("a settled milestone is final; create new work with ahub roadmap new");
3428
+ return row;
3429
+ }
3430
+
3431
+ private roadmapStateAuthority(by: PeerId, state: MilestoneState | undefined): void {
3432
+ if (state !== undefined && !(MILESTONE_STATES as readonly string[]).includes(state)) throw new PreEffectToolRefusal("invalid milestone state; use proposed, planned, active, done or dropped with ahub roadmap state");
3433
+ if (by !== USER && (state === "done" || state === "dropped")) throw new PreEffectToolRefusal("done and dropped require the person; ask them to run ahub roadmap state");
3434
+ }
3435
+
3436
+ private roadmapTextCurrent(fields: MilestonePatch): string {
3437
+ const text = [fields.title, fields.outcome].filter((value): value is string => value !== undefined).join("\n");
3438
+ if (text && !this.publicMetadataText(text))
3439
+ throw new PreEffectToolRefusal("milestone text was not cleared for public planning; remove private content before ahub roadmap new or edit");
3440
+ return text;
3441
+ }
3442
+
3443
+ private async roadmapScreen(fields: MilestonePatch): Promise<void> {
3444
+ const text = this.roadmapTextCurrent(fields);
3445
+ if (text && this.screenOn() && (await this.screenCall(text)).label !== "clear")
3446
+ throw new PreEffectToolRefusal("milestone text was not cleared for public planning; remove private content before ahub roadmap new or edit");
3447
+ this.roadmapTextCurrent(fields);
3448
+ }
3449
+
3450
+ private roadmapResult(by: PeerId, id: number): MilestoneView {
3451
+ try { return this.milestoneShow(by, id); }
3452
+ catch { throw new Error("roadmap operation finished but public readback is unavailable; inspect ahub roadmap show before retrying"); }
3453
+ }
3454
+
3455
+ async milestoneNew(by: PeerId, raw: unknown): Promise<MilestoneView> {
3456
+ const current = this.roadmapWriteAuthority(by), fields = this.roadmapParsed(() => parseMilestoneInput(raw));
3457
+ this.roadmapStateAuthority(by, fields.state);
3458
+ await this.roadmapScreen(fields); current(); this.roadmapStateAuthority(by, fields.state); this.roadmapTextCurrent(fields);
3459
+ const row = this.d.board.newMilestone(fields, by, this.d.now?.() ?? Date.now());
3460
+ return this.roadmapResult(by, row.id);
3461
+ }
3462
+
3463
+ async milestoneEdit(by: PeerId, id: number, revision: number, raw: unknown): Promise<MilestoneView> {
3464
+ const current = this.roadmapWriteAuthority(by), fields = this.roadmapParsed(() => parseMilestonePatch(raw));
3465
+ this.roadmapParsed(() => milestoneRevision(revision)); this.roadmapStateAuthority(by, fields.state);
3466
+ const validate = () => {
3467
+ current(); this.roadmapStateAuthority(by, fields.state);
3468
+ const row = this.roadmapCurrent(id);
3469
+ if (row.revision !== revision) throw new PreEffectToolRefusal("roadmap revision changed; reload ahub roadmap show before editing");
3470
+ return row;
3471
+ };
3472
+ validate(); await this.roadmapScreen(fields); const row = validate(); this.roadmapTextCurrent(fields);
3473
+ if (Object.entries(fields).every(([key, value]) => row[key as keyof Milestone] === value)) return this.milestoneShow(by, id);
3474
+ this.d.board.updateMilestone(id, fields, revision, { by, at: this.d.now?.() ?? Date.now(), event: "edited", fields: Object.keys(fields) });
3475
+ return this.roadmapResult(by, id);
3476
+ }
3477
+
3478
+ milestoneLink(by: PeerId, id: number, kind: MilestoneLinkKind, raw: string): MilestoneView {
3479
+ this.roadmapWriteAuthority(by);
3480
+ const row = this.roadmapCurrent(id), ref = this.roadmapParsed(() => milestoneLinkRef(kind, raw));
3481
+ if (!this.publicMetadataText(ref)) throw new PreEffectToolRefusal("roadmap reference is private; use a public reference with ahub roadmap link");
3482
+ if (kind === "task" && !this.d.board.get(Number(ref)) || kind === "release" && !this.d.board.release(Number(ref)))
3483
+ throw new PreEffectToolRefusal("roadmap target does not exist; inspect ahub board or ahub release list before linking");
3484
+ this.d.board.linkMilestone(id, kind, ref, by, row.revision, this.d.now?.() ?? Date.now());
3485
+ return this.roadmapResult(by, id);
3486
+ }
3487
+
3488
+ milestoneUnlink(by: PeerId, id: number, kind: MilestoneLinkKind, raw: string): MilestoneView {
3489
+ this.roadmapWriteAuthority(by);
3490
+ const row = this.roadmapCurrent(id), ref = this.roadmapParsed(() => milestoneLinkRef(kind, raw));
3491
+ this.d.board.unlinkMilestone(id, kind, ref, by, row.revision, this.d.now?.() ?? Date.now());
3492
+ return this.roadmapResult(by, id);
3493
+ }
3494
+
3495
+ milestoneOrder(by: PeerId, id: number, order: number): MilestoneView {
3496
+ this.roadmapWriteAuthority(by);
3497
+ const row = this.roadmapCurrent(id), fields = this.roadmapParsed(() => parseMilestonePatch({ order }));
3498
+ if (row.order !== order) this.d.board.updateMilestone(id, fields, row.revision, { by, at: this.d.now?.() ?? Date.now(), event: "ordered", fields: ["order"] });
3499
+ return this.roadmapResult(by, id);
3500
+ }
3501
+
3502
+ milestoneState(by: PeerId, id: number, state: MilestoneState): MilestoneView {
3503
+ this.roadmapWriteAuthority(by); this.roadmapStateAuthority(by, state);
3504
+ this.roadmapParsed(() => parseMilestonePatch({ state }));
3505
+ const row = this.roadmapCurrent(id, state);
3506
+ if (row.state !== state) this.d.board.updateMilestone(id, { state }, row.revision, { by, at: this.d.now?.() ?? Date.now(), event: "state", fields: ["state"] });
3507
+ return this.roadmapResult(by, id);
3508
+ }
3509
+
3510
+ private roadmapSnapshot(by: PeerId): RoadmapSnapshot {
3511
+ let freshness: SpecsCheckReport["freshness"] | undefined;
3512
+ try { const report = this.d.specsRead?.("check", []); if (report && "freshness" in report && !report.truncated && report.errors === 0)
3513
+ freshness = report.freshness.filter(row => this.publicMetadataText(row.path) && (row.id === undefined || this.publicMetadataText(row.id))); } catch { /* unavailable evidence stays unknown */ }
3514
+ return { milestones: this.d.board.milestones(), links: this.d.board.milestoneLinks(), tasks: this.d.board.list(), releases: this.d.board.releases(), freshness,
3515
+ issueOf: task => { try { const source = this.planIssueIdentity(task); return source ? `${source.repo.toLowerCase()}#${source.issue}` : undefined; } catch { return undefined; } },
3516
+ privateTask: task => this.isPii(task) || task.signals.includes("pii") || task.state === "backlog" && by !== USER && !this.isConfiguredPlanner(by),
3517
+ publicText: text => this.publicMetadataText(text),
3518
+ };
3519
+ }
3520
+
3521
+ milestoneList(by: PeerId): (MilestoneView & { tree: TreeRollup; readyToClose: ReadyToClose })[] {
3522
+ this.roadmapReadAuthority(by);
3523
+ const views = withTree(milestoneViews(this.roadmapSnapshot(by)));
3524
+ this.roadmapReadAuthority(by); return views;
3525
+ }
3526
+
3527
+ milestoneShow(by: PeerId, id: number): MilestoneView {
3528
+ this.roadmapParsed(() => milestoneId(id));
3529
+ const row = this.milestoneList(by).find(row => row.id === id);
3530
+ if (!row) throw new PreEffectToolRefusal("roadmap milestone does not exist; use ahub roadmap list");
3531
+ return row;
3532
+ }
3533
+
3534
+ // ---- R3 (#1481): bottom-up placement. Reads are the roadmap read authority; every write below is the R1 writer, never a new one. ----
3535
+
3536
+ /** The one repository the roadmap reads from GitHub: the caller's choice, else the project's. Never derived from model text. */
3537
+ private roadmapRepo(raw: unknown): string | undefined {
3538
+ if (raw === undefined) return undefined;
3539
+ return this.roadmapParsed(() => githubRepo(raw));
3540
+ }
3541
+
3542
+ private roadmapGh(run?: SdlcGh): SdlcGh {
3543
+ return run ?? this.d.roadmapGh ?? this.d.sdlc?.gh ?? ((args, timeout, _cwd, bound) => sdlcGh(args, timeout, this.d.cwd, bound));
3544
+ }
3545
+
3546
+ /** Issues, tasks and specs that no live milestone places, each with its reason. Private tasks are counted and never named. */
3547
+ async roadmapUnplaced(by: PeerId, input: { repo?: unknown } = {}, run?: SdlcGh): Promise<UnplacedResult & { repo: string | null }> {
3548
+ this.roadmapReadAuthority(by);
3549
+ const repo = this.roadmapRepo(input.repo);
3550
+ let issues: Awaited<ReturnType<typeof readGitHubIssuePages>> | undefined;
3551
+ try { issues = await readGitHubIssuePages({ ...(repo === undefined ? {} : { repo }) }, this.roadmapGh(run)); } catch { issues = undefined; }
3552
+ this.roadmapReadAuthority(by);
3553
+ let specs: { id: string; title: string; status: string | null }[] | undefined;
3554
+ try { const list = this.d.specsList?.(); if (list && !list.truncated && list.errors === 0) specs = list.specs; } catch { specs = undefined; }
3555
+ const snapshot = this.roadmapSnapshot(by);
3556
+ const result = computeUnplaced({ milestones: snapshot.milestones, links: snapshot.links, tasks: snapshot.tasks, issues, specs, issueOf: snapshot.issueOf, privateTask: snapshot.privateTask, publicText: snapshot.publicText });
3557
+ return { ...result, repo: issues?.repo ?? repo ?? null };
3558
+ }
3559
+
3560
+ /** Pending and settled suggestions as a caller may read them: public text only. */
3561
+ milestoneSuggestions(by: PeerId, state?: MilestoneSuggestion["state"]): MilestoneSuggestion[] {
3562
+ this.roadmapReadAuthority(by);
3563
+ return this.d.board.suggestions(state).filter(row => this.suggestionPublic(row));
3564
+ }
3565
+
3566
+ private suggestionPublic(row: MilestoneSuggestion): boolean {
3567
+ const text = [row.ref, row.citeItem, row.citeMilestone ?? "", row.proposal?.title ?? "", row.proposal?.outcome ?? ""].join("\n");
3568
+ if (!this.publicMetadataText(text)) return false;
3569
+ if (row.kind !== "task") return true;
3570
+ const task = this.d.board.get(Number(row.ref));
3571
+ return task !== undefined && !this.isPii(task) && !task.signals.includes("pii");
3572
+ }
3573
+
3574
+ /**
3575
+ * Ask the hub's model where unplaced items belong. The model sees only public text, answers are checked against what it was shown
3576
+ * (ids offered, cited words present), saved as pending suggestions, and nothing is linked: that is `roadmapAccept`.
3577
+ */
3578
+ async roadmapTriage(by: PeerId, input: { repo?: unknown } = {}, run?: SdlcGh): Promise<{ suggestions: MilestoneSuggestion[]; asked: number; dropped: number; partial: boolean; unavailable: string | null }> {
3579
+ const current = this.roadmapWriteAuthority(by);
3580
+ const unplaced = await this.roadmapUnplaced(by, input, run);
3581
+ current();
3582
+ const snapshot = this.roadmapSnapshot(by), views = milestoneViews(snapshot);
3583
+ const pending = new Set(this.d.board.suggestions("pending").map(row => `${row.kind}:${row.ref}`));
3584
+ const items: TriageItem[] = [
3585
+ ...unplaced.tasks.map(row => ({ kind: "task" as const, ref: String(row.id), text: row.title })),
3586
+ ...unplaced.issues.map(row => ({ kind: "issue" as const, ref: row.ref, text: row.title })),
3587
+ ...unplaced.specs.map(row => ({ kind: "spec" as const, ref: row.id, text: row.title })),
3588
+ ].filter(item => !pending.has(`${item.kind}:${item.ref}`));
3589
+ const live = views.filter(view => view.state !== "done" && view.state !== "dropped" && view.title !== "[withheld]");
3590
+ const batch = items.slice(0, TRIAGE_BATCH);
3591
+ const done = (suggestions: MilestoneSuggestion[], dropped: number, unavailable: string | null) => ({ suggestions, asked: batch.length, dropped, partial: unplaced.partial || items.length > batch.length, unavailable });
3592
+ if (!batch.length) return done([], 0, null);
3593
+ if (!this.d.roadmapModel) return done([], 0, "no hub model is configured for roadmap triage");
3594
+ const prompt = buildTriagePrompt(batch, live.map(view => ({ id: view.id, title: view.title, outcome: view.outcome })));
3595
+ const answer = await this.d.roadmapModel(prompt.system, prompt.user, () => { try { current(); return true; } catch { return false; } });
3596
+ current();
3597
+ if (!answer) return done([], 0, "the hub model gave no answer; retry ahub roadmap triage later");
3598
+ const parsed = parseTriage(answer, prompt), saved: MilestoneSuggestion[] = [], at = this.d.now?.() ?? Date.now();
3599
+ for (const row of parsed.suggestions) {
3600
+ // Re-screen at the write: what is stored is public planning text only, and a milestone that has since settled is not a target.
3601
+ if (row.milestone !== null) { const target = this.d.board.milestone(row.milestone); if (!target || ["done", "dropped"].includes(target.state)) continue; }
3602
+ const text = [row.ref, row.citeItem, row.citeMilestone ?? "", row.proposal?.title ?? "", row.proposal?.outcome ?? ""].join("\n");
3603
+ if (!this.publicMetadataText(text)) continue;
3604
+ if (this.screenOn() && (await this.screenCall(text)).label !== "clear") continue;
3605
+ current();
3606
+ // A model's answer, attributed to the hub (never to the asker), is advisory data: no ask or memory path reads this table.
3607
+ const made = this.d.board.addSuggestion(row, "hub", at);
3608
+ if (made) saved.push(made);
3609
+ }
3610
+ return done(saved, parsed.dropped + parsed.suggestions.length - saved.length, null);
3611
+ }
3612
+
3613
+ /** Apply one suggestion through R1's own writers. A "new milestone" suggestion creates it first; a retry never creates a second. */
3614
+ async roadmapAccept(by: PeerId, rawId: unknown): Promise<{ suggestion: MilestoneSuggestion; milestone: MilestoneView }> {
3615
+ const current = this.roadmapWriteAuthority(by);
3616
+ const id = this.roadmapParsed(() => milestoneId(rawId)), row = this.d.board.suggestion(id);
3617
+ if (!row) throw new PreEffectToolRefusal("roadmap suggestion does not exist; use ahub roadmap triage");
3618
+ if (row.state !== "pending") throw new PreEffectToolRefusal(`roadmap suggestion was already ${row.state}; run ahub roadmap triage for current suggestions`);
3619
+ if (!this.suggestionPublic(row)) throw new PreEffectToolRefusal("roadmap suggestion text is no longer public; reject it with ahub roadmap reject");
3620
+ let target = row.milestone ?? this.d.board.suggestionCreated(id);
3621
+ if (target === undefined) {
3622
+ const proposal = row.proposal;
3623
+ if (!proposal) throw new PreEffectToolRefusal("roadmap suggestion has no target; reject it with ahub roadmap reject");
3624
+ const fields = this.roadmapParsed(() => parseMilestoneInput({ title: proposal.title, outcome: proposal.outcome }));
3625
+ await this.roadmapScreen(fields); current();
3626
+ const made = this.d.board.newMilestone(fields, by, this.d.now?.() ?? Date.now());
3627
+ this.d.board.setSuggestionCreated(id, made.id); target = made.id;
3628
+ }
3629
+ const milestone = this.roadmapCurrent(target);
3630
+ const ref = this.roadmapParsed(() => milestoneLinkRef(row.kind, row.ref));
3631
+ if (row.kind === "task" && !this.d.board.get(Number(ref))) throw new PreEffectToolRefusal("roadmap target does not exist; reject the suggestion with ahub roadmap reject");
3632
+ current();
3633
+ this.d.board.linkMilestone(target, row.kind, ref, by, milestone.revision, this.d.now?.() ?? Date.now());
3634
+ const settled = this.d.board.settleSuggestion(id, "accepted", by, this.d.now?.() ?? Date.now());
3635
+ return { suggestion: settled, milestone: this.roadmapResult(by, target) };
3636
+ }
3637
+
3638
+ roadmapReject(by: PeerId, rawId: unknown): MilestoneSuggestion {
3639
+ this.roadmapWriteAuthority(by);
3640
+ const id = this.roadmapParsed(() => milestoneId(rawId));
3641
+ return this.d.board.settleSuggestion(id, "rejected", by, this.d.now?.() ?? Date.now());
3642
+ }
3643
+
3644
+ /**
3645
+ * One-time import of open GitHub milestones as `proposed` milestones, linking their open issues. A dry run unless `apply`.
3646
+ * A repeat finds each milestone's import mark and each link, so a second `apply` changes nothing. Nothing is ever written to GitHub.
3647
+ */
3648
+ async roadmapImportGitHub(by: PeerId, input: { repo?: unknown; apply?: unknown } = {}, run?: SdlcGh): Promise<{
3649
+ repo: string; apply: boolean; partial: boolean; milestones: { number: number; title: string; milestone: number | null; action: "create" | "exists"; issues: string[]; newLinks: number }[]; created: number; linked: number; withheld: number;
3650
+ }> {
3651
+ const current = this.roadmapWriteAuthority(by);
3652
+ if (!this.personOrConductor(by)) throw new PreEffectToolRefusal("GitHub milestone import is a console command; ask the person to run ahub roadmap import-github");
3653
+ if (input.apply !== undefined && typeof input.apply !== "boolean") throw new PreEffectToolRefusal("roadmap import apply must be true or false; omit it for a dry run");
3654
+ const apply = input.apply === true, gh = this.roadmapGh(run), repoInput = this.roadmapRepo(input.repo);
3655
+ const milestonePages = await readGitHubMilestonePages({ ...(repoInput === undefined ? {} : { repo: repoInput }) }, gh);
3656
+ const issuePages = await readGitHubIssuePages({ repo: milestonePages.repo }, gh);
3657
+ current();
3658
+ const issuesOf = new Map<number, string[]>();
3659
+ for (const row of issuePages.rows) if (row.milestone !== null) issuesOf.set(row.milestone, [...(issuesOf.get(row.milestone) ?? []), `${issuePages.repo}#${row.number}`]);
3660
+ const out: { number: number; title: string; milestone: number | null; action: "create" | "exists"; issues: string[]; newLinks: number }[] = [];
3661
+ let created = 0, linked = 0, withheld = 0;
3662
+ for (const source of milestonePages.rows) {
3663
+ const description = source.description || `Imported from GitHub milestone ${milestonePages.repo}#milestone/${source.number}`;
3664
+ let fields: ReturnType<typeof parseMilestoneInput>;
3665
+ try { fields = parseMilestoneInput({ title: source.title, outcome: description.slice(0, 4000), ...(source.due ? { target: source.due } : {}) }); }
3666
+ catch { withheld++; continue; }
3667
+ const prior = this.d.board.importedMilestone(milestonePages.repo, source.number), existing = prior === undefined ? undefined : this.d.board.milestone(prior);
3668
+ const refs = (issuesOf.get(source.number) ?? []).filter(ref => this.publicMetadataText(ref));
3669
+ const have = new Set(existing ? this.d.board.milestoneLinks(existing.id).filter(link => link.kind === "issue").map(link => link.ref) : []);
3670
+ const newRefs = refs.filter(ref => !have.has(ref));
3671
+ const text = `${fields.title}\n${fields.outcome}`;
3672
+ if (!this.publicMetadataText(text)) { withheld++; continue; }
3673
+ const row = { number: source.number, title: sanitize(fields.title), milestone: existing?.id ?? null, action: existing ? "exists" as const : "create" as const, issues: refs, newLinks: newRefs.length };
3674
+ if (apply) {
3675
+ // The model screen runs on apply only, for a milestone about to be created; a dry run lists what passes the pattern screen.
3676
+ if (!existing && this.screenOn() && (await this.screenCall(text)).label !== "clear") { withheld++; continue; }
3677
+ current();
3678
+ const made = this.d.board.importMilestone(milestonePages.repo, source.number, fields, by, this.d.now?.() ?? Date.now());
3679
+ if (made.created) created++;
3680
+ row.milestone = made.milestone.id;
3681
+ for (const ref of newRefs) {
3682
+ const live = this.d.board.milestone(made.milestone.id)!;
3683
+ // A settled milestone is final: an import never reopens or relinks it.
3684
+ if (["done", "dropped"].includes(live.state)) break;
3685
+ const before = this.d.board.milestoneLinks(made.milestone.id).length;
3686
+ this.d.board.linkMilestone(made.milestone.id, "issue", ref, by, live.revision, this.d.now?.() ?? Date.now());
3687
+ if (this.d.board.milestoneLinks(made.milestone.id).length > before) linked++;
3688
+ }
3689
+ }
3690
+ out.push(row);
3691
+ }
3692
+ return { repo: milestonePages.repo, apply, partial: milestonePages.partial || issuePages.partial, milestones: out, created, linked, withheld };
3693
+ }
3694
+
3352
3695
  releaseList(by: PeerId): Record<string, unknown>[] {
3353
3696
  this.planningAuthority(by);
3354
3697
  const scopes = new Map<number, { id: number; state: Task["state"]; deps: number[] }[]>();
@@ -4634,6 +4977,7 @@ export class Tasks {
4634
4977
  try { claimed = this.d.board.update(next.id, by, "accepted", { state: "in_progress" }); }
4635
4978
  catch (error) { undoWorktree?.(); throw error; }
4636
4979
  this.captureOwnerAcceptance(claimed);
4980
+ claimed = await this.prepareAcceptedWorktree(claimed, by, opts.current ?? this.requestCheck(by));
4637
4981
  this.releaseNotice(`task ${this.publicTitle(claimed)} claimed by ${by}`);
4638
4982
  return claimed;
4639
4983
  }
@@ -8004,7 +8348,7 @@ export class Tasks {
8004
8348
  if (metadata && !this.isPii(task) && (!this.nameable(metadata.repo!) || looksSecret(metadata.repo!) || this.aboutPrivatePath("", metadata.repo!, task))) throw new PreEffectToolRefusal("this repository metadata is private or sensitive and is not kept");
8005
8349
  let draft = metadata ? { ...task, refs: { ...task.refs, ...metadata } } : task;
8006
8350
  this.warmRepository(draft);
8007
- if ((this.d.sdlc?.config() ?? sdlcConfig(undefined)).mode === "off" || !this.isBuildTask(task)) return this.accept(by, id, plan, metadata);
8351
+ if ((this.d.sdlc?.config() ?? sdlcConfig(undefined)).mode === "off" || !this.isBuildTask(task)) return this.prepareAcceptedWorktree(this.accept(by, id, plan, metadata), by, requestCheck);
8008
8352
  const spec = await this.specGate(by, id, draft.refs);
8009
8353
  if (spec?.carry) draft = metadata ? { ...spec.task, refs: { ...spec.task.refs, ...metadata } } : spec.task;
8010
8354
  await this.planEntryGate(by, draft, spec?.carry);
@@ -8013,7 +8357,7 @@ export class Tasks {
8013
8357
  this.mine(current, by, "owner", true);
8014
8358
  if (current.history.length !== task.history.length || current.owner !== task.owner) throw new PreEffectToolRefusal("task changed during build admission");
8015
8359
  this.reviewedAdmissions.set(current.id, { flow: current.history.length, owner: current.owner });
8016
- try { return this.accept(by, id, plan, metadata, spec?.carry); }
8360
+ try { return await this.prepareAcceptedWorktree(this.accept(by, id, plan, metadata, spec?.carry), by, requestCheck); }
8017
8361
  finally { this.reviewedAdmissions.delete(current.id); }
8018
8362
  }
8019
8363
 
@@ -8249,7 +8593,37 @@ export class Tasks {
8249
8593
  /** The hub-made worktree of the task's owner, for the accept answer: where to edit, and what the hub does at `hub_task_done`. */
8250
8594
  worktreeNote(task: Task, peer: PeerId): string | undefined {
8251
8595
  const found = this.d.taskWorktree?.describe(peer, task.id);
8252
- return found ? `Worktree: the hub made ${found.path} on branch ${found.branch} for this task. Edit files there only; do not run git. At hub_task_done the hub stages, commits and pushes it for you.` : undefined;
8596
+ return found ? [`Worktree: the hub made ${found.path} on branch ${found.branch} for this task. Edit files there only; do not run git. At hub_task_done the hub stages, commits and pushes it for you.`, this.dependencyNote(task, peer)].filter(Boolean).join("\n") : undefined;
8597
+ }
8598
+
8599
+ private dependencyNote(task: Task, peer: PeerId): string | undefined {
8600
+ const state = this.d.taskWorktree?.dependencyState?.(peer, task.id);
8601
+ return state ? `Task #${task.id} dependencies ${state.ready ? "prepared" : `not prepared: ${state.reason}`}. Full checks stay with CI and the remote runner.` : undefined;
8602
+ }
8603
+
8604
+ /** Only fixed readiness/cause text for this peer's current public work reaches its next prompt. */
8605
+ dependencyNotes(peer: PeerId): string | undefined {
8606
+ return this.d.board.list().filter(task => task.owner === peer && task.state === "in_progress" && !this.isPii(task))
8607
+ .map(task => this.dependencyNote(task, peer)).filter(Boolean).join("\n") || undefined;
8608
+ }
8609
+
8610
+ private async prepareAcceptedWorktree(task: Task, actor: PeerId, requestCheck: () => void): Promise<Task> {
8611
+ const port = this.d.taskWorktree;
8612
+ const peer = task.owner ?? actor;
8613
+ if (!port?.prepareDependencies || !port.preparesDependencies?.(peer) || !port.describe(peer, task.id)) return task;
8614
+ const acceptance = this.ownerAcceptance(task)?.index;
8615
+ const current = () => {
8616
+ try {
8617
+ requestCheck();
8618
+ const row = this.d.board.get(task.id);
8619
+ return !!row && row.created === task.created && row.owner === peer && row.state === "in_progress"
8620
+ && !this.isPii(row) && this.ownerAcceptance(row)?.index === acceptance;
8621
+ } catch { return false; }
8622
+ };
8623
+ await port.prepareDependencies({ peer, task: task.id, current });
8624
+ // Acceptance is already a board effect. Do not describe a lost request as pre-effect.
8625
+ if (!current()) throw new Error(`task #${task.id} changed owner, session or privacy during dependency preparation; read pending notices and call hub_task_list before continuing`);
8626
+ return this.d.board.get(task.id)!;
8253
8627
  }
8254
8628
 
8255
8629
  /**