@staix/agent-hub 0.43.0 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +3 -8
  3. package/docs/agent-notes/adapters.md +2 -2
  4. package/docs/agent-notes/daemon.md +4 -4
  5. package/docs/agent-notes/local-worker.md +2 -1
  6. package/docs/agent-notes/security-review.md +1 -1
  7. package/docs/agent-notes/tasks.md +5 -2
  8. package/docs/agent-notes/tests.md +4 -3
  9. package/docs/design/adapters.md +4 -2
  10. package/docs/design/agent-hub-architecture.md +2 -0
  11. package/docs/design/agent-hub.md +1 -1
  12. package/docs/design/roadmap.md +75 -2
  13. package/docs/design/supervision.md +34 -2
  14. package/docs/design/task-board.md +36 -2
  15. package/docs/dogfood.md +20 -5
  16. package/docs/events.md +9 -3
  17. package/docs/influences.md +7 -0
  18. package/docs/memory.md +4 -4
  19. package/docs/operations.md +84 -31
  20. package/docs/quickstart.md +14 -2
  21. package/docs/research.md +18 -0
  22. package/docs/roadmap.json +4 -0
  23. package/docs/roadmap.md +9 -0
  24. package/docs/sdlc.md +19 -4
  25. package/docs/security.md +4 -4
  26. package/docs/verification/2026-11-11-supervision-pilot-1221.md +864 -0
  27. package/docs/verification/2026-11-19-0.44.0.md +60 -0
  28. package/docs/verification/2026-11-19-claude-implementer-2.1.328.md +49 -0
  29. package/docs/verification/2026-11-20-claude-implementer-2.1.329.md +49 -0
  30. package/docs/verification/2026-11-20-sdlc-metrics-diagnosis.md +7 -0
  31. package/docs/verification/2026-11-21-0.45.0.md +69 -0
  32. package/docs/verification/2026-11-22-codex-0171-reviewer-isolation.md +47 -0
  33. package/docs/verified.json +32 -26
  34. package/package.json +2 -2
  35. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  36. package/plugins/agent-hub/kimi-hook.js +585 -264
  37. package/plugins/agent-hub/kimi-review-policy-worker.js +5 -5
  38. package/plugins/agent-hub/server.js +629 -293
  39. package/scripts/check-docs.mjs +9 -1
  40. package/src/adapters/acp.ts +11 -1
  41. package/src/adapters/compat.ts +3 -3
  42. package/src/adapters/definitions/builtin-metadata.ts +2 -2
  43. package/src/adapters/definitions/native-context.ts +10 -0
  44. package/src/adapters/jcode.ts +10 -0
  45. package/src/adapters/local-worker.ts +3 -2
  46. package/src/adapters/pi.ts +15 -4
  47. package/src/cli/console-state.ts +3 -1
  48. package/src/cli/help.ts +3 -1
  49. package/src/cli/identity.ts +2 -1
  50. package/src/cli/main.ts +12 -6
  51. package/src/cli/output.ts +2 -2
  52. package/src/cli/recovery-package.ts +16 -3
  53. package/src/cli/roadmap-write.ts +59 -0
  54. package/src/cli/roadmap.ts +81 -4
  55. package/src/cli/sdlc-output.ts +11 -1
  56. package/src/cli/upgrade-runtime.ts +10 -6
  57. package/src/cli/upgrade.ts +9 -3
  58. package/src/hub/agent-mem-range.ts +43 -0
  59. package/src/hub/board.ts +116 -2
  60. package/src/hub/bus.ts +4 -0
  61. package/src/hub/check-runner.ts +25 -1
  62. package/src/hub/claude-shell-wrapper.ts +2 -1
  63. package/src/hub/config-apply.ts +4 -2
  64. package/src/hub/config-trust.ts +1 -1
  65. package/src/hub/context-window.ts +1 -1
  66. package/src/hub/control-write-trace.ts +39 -2
  67. package/src/hub/cost-governance.ts +11 -7
  68. package/src/hub/daemon.ts +318 -53
  69. package/src/hub/dogfood-read.ts +4 -2
  70. package/src/hub/edit-guard.ts +100 -0
  71. package/src/hub/events.ts +79 -8
  72. package/src/hub/facts.ts +85 -2
  73. package/src/hub/hub-tools.ts +3 -1
  74. package/src/hub/lifecycle.ts +6 -1
  75. package/src/hub/log-rotation.ts +130 -0
  76. package/src/hub/memory-profile.ts +137 -21
  77. package/src/hub/no-writes.ts +1 -0
  78. package/src/hub/operational-authority.ts +3 -2
  79. package/src/hub/operational-settings.ts +2 -2
  80. package/src/hub/quota-events.ts +40 -0
  81. package/src/hub/recovery-store.ts +70 -24
  82. package/src/hub/report.ts +1 -1
  83. package/src/hub/research-experiments.ts +132 -0
  84. package/src/hub/research-quality.ts +13 -3
  85. package/src/hub/research-record.ts +38 -2
  86. package/src/hub/research.ts +128 -28
  87. package/src/hub/restart.ts +49 -2
  88. package/src/hub/roadmap-check.ts +65 -0
  89. package/src/hub/roadmap-decompose.ts +80 -0
  90. package/src/hub/roadmap-export.ts +27 -0
  91. package/src/hub/roadmap-sync.ts +97 -0
  92. package/src/hub/roadmap.ts +40 -0
  93. package/src/hub/runtime-capture-prune.ts +9 -1
  94. package/src/hub/runtime-prune-health.ts +5 -1
  95. package/src/hub/sdlc-branch-ci.ts +128 -0
  96. package/src/hub/sdlc-merge.ts +12 -5
  97. package/src/hub/sdlc-metrics.ts +33 -10
  98. package/src/hub/sdlc.ts +90 -10
  99. package/src/hub/settings.ts +1 -0
  100. package/src/hub/snapshots.ts +56 -1
  101. package/src/hub/startup-event-seeds.ts +21 -15
  102. package/src/hub/startup-timing.ts +3 -1
  103. package/src/hub/supervision-proposals.ts +10 -2
  104. package/src/hub/supervision-rules.ts +27 -4
  105. package/src/hub/supervision.ts +7 -0
  106. package/src/hub/task-pr.ts +47 -0
  107. package/src/hub/task-shell-command.ts +124 -0
  108. package/src/hub/task-worktree.ts +18 -11
  109. package/src/hub/tasks.ts +617 -45
  110. package/src/hub/usage-rollup.ts +35 -20
  111. package/src/hub/worktree-shelf.ts +2 -1
  112. package/src/local/sandbox.ts +2 -1
  113. package/src/local/shell-environment.ts +6 -0
  114. package/src/local/tools.ts +13 -1
  115. package/src/memory/brief.ts +10 -1
  116. package/src/memory/client.ts +3 -2
  117. package/src/pi/extension.ts +15 -3
  118. package/src/pi/tool-receipts.ts +26 -0
@@ -10,33 +10,60 @@ export const ROADMAP_FORMS = {
10
10
  order: "order <id> <n>", state: "state <id> <proposed|planned|active|done|dropped>",
11
11
  unplaced: "unplaced [--repo <owner/name>] [--json]",
12
12
  triage: "triage [--repo <owner/name>] [--list] [--json]",
13
+ decompose: "decompose <id> [--accept <part>] [--json]",
13
14
  accept: "accept <suggestion>", reject: "reject <suggestion>",
14
15
  importGithub: "import-github [--repo <owner/name>] [--apply] [--json]",
16
+ check: "check [--json]", sync: "sync [--apply --confirm <fingerprint>] [--json]",
17
+ export: "export [--write | --issue <n> [--apply --confirm <fingerprint>]] [--json]",
15
18
  } as const;
16
19
  export const ROADMAP_USAGE = `usage: ${Object.values(ROADMAP_FORMS).map(form => `ahub roadmap ${form}`).join(" | ")}`;
17
20
  export interface RoadmapArgs {
18
- op: "hub_roadmap_list" | "hub_roadmap_show" | "hub_roadmap_edit" | "hub_roadmap_unplaced" | "hub_roadmap_triage" | "roadmap_import_github";
21
+ op: "hub_roadmap_list" | "hub_roadmap_show" | "hub_roadmap_check" | "hub_roadmap_edit" | "hub_roadmap_unplaced" | "hub_roadmap_triage" | "hub_roadmap_decompose" | "roadmap_import_github" | "roadmap_sync" | "roadmap_sync_apply" | "roadmap_export" | "roadmap_export_apply";
19
22
  args: Record<string, unknown>;
20
23
  json: boolean;
24
+ write?: boolean;
21
25
  }
22
26
  /** R3 commands: their flags are not milestone fields, so they are parsed apart from new/edit. */
23
- const R3_COMMANDS = ["unplaced", "triage", "accept", "reject", "import-github"];
24
- const R3_JSON = ["unplaced", "triage", "import-github"];
27
+ const R3_COMMANDS = ["unplaced", "triage", "decompose", "accept", "reject", "import-github"];
28
+ const R3_JSON = ["unplaced", "triage", "decompose", "import-github"];
25
29
  const fieldFlags = ["title", "outcome", "horizon", "order", "target", "parent"];
26
30
  const usage = (message: string): never => { throw new Error(`${message}; ${ROADMAP_USAGE}`); };
31
+
32
+ function parseR4(command: string, rest: readonly string[], jsonSeen: boolean): RoadmapArgs {
33
+ let json = jsonSeen, apply = false, write = false, issue: number | undefined, confirm: string | undefined;
34
+ for (let i = 0; i < rest.length; i++) {
35
+ const word = rest[i]!;
36
+ if (word === "--json" && !json) json = true;
37
+ else if (word === "--apply" && !apply && command !== "check") apply = true;
38
+ else if (word === "--write" && !write && command === "export") write = true;
39
+ else if (word === "--issue" && issue === undefined && command === "export") issue = integer(rest[++i]);
40
+ else if (word === "--confirm" && confirm === undefined && command !== "check") { confirm = rest[++i]; if (!confirm || !/^[a-f0-9]{64}$/.test(confirm)) return usage("roadmap confirmation needs a full fingerprint"); }
41
+ else return usage("unknown or duplicate roadmap option");
42
+ }
43
+ if (confirm && !apply || apply && !confirm || write && (apply || issue !== undefined) || command === "export" && apply && issue === undefined) return usage("roadmap apply needs its preview fingerprint and export --write is separate from --issue");
44
+ if (command === "check") return { op: "hub_roadmap_check", args: {}, json };
45
+ if (command === "sync") return { op: apply ? "roadmap_sync_apply" : "roadmap_sync", args: apply ? { apply, confirm } : {}, json };
46
+ return { op: apply ? "roadmap_export_apply" : "roadmap_export", args: { ...(issue === undefined ? {} : { issue }), ...(apply ? { apply, confirm } : {}) }, json, ...(write ? { write } : {}) };
47
+ }
27
48
  function integer(value: string | undefined, zero = false): number {
28
49
  if (value === undefined || !/^(0|[1-9][0-9]*)$/.test(value)) return usage("roadmap needs a whole-number operand");
29
50
  return zero ? milestoneRevision(Number(value)) : milestoneId(Number(value));
30
51
  }
31
52
 
32
53
  function parseR3(command: string, rest: readonly string[], jsonSeen: boolean): RoadmapArgs {
33
- let json = jsonSeen, list = false, apply = false, repo: string | undefined;
54
+ let json = jsonSeen, list = false, apply = false, repo: string | undefined, accept: number | undefined;
34
55
  const operands: string[] = [];
35
56
  for (let at = 0; at < rest.length; at++) {
36
57
  const word = rest[at]!;
37
58
  if (word === "--json") { if (json) return usage("duplicate roadmap --json flag"); json = true; continue; }
38
59
  if (word === "--list" && command === "triage") { if (list) return usage("duplicate roadmap --list flag"); list = true; continue; }
39
60
  if (word === "--apply" && command === "import-github") { if (apply) return usage("duplicate roadmap --apply flag"); apply = true; continue; }
61
+ if ((word === "--accept" || word.startsWith("--accept=")) && command === "decompose") {
62
+ if (accept !== undefined) return usage("duplicate roadmap --accept option");
63
+ const value = word === "--accept" ? rest[++at] : word.slice("--accept=".length);
64
+ accept = integer(value);
65
+ continue;
66
+ }
40
67
  if ((word === "--repo" || word.startsWith("--repo=")) && ["unplaced", "triage", "import-github"].includes(command)) {
41
68
  if (repo !== undefined) return usage("duplicate roadmap --repo option");
42
69
  const value = word === "--repo" ? rest[++at] : word.slice("--repo=".length);
@@ -52,6 +79,10 @@ function parseR3(command: string, rest: readonly string[], jsonSeen: boolean): R
52
79
  if (operands.length !== 1) return usage(`roadmap ${command} needs one suggestion id`);
53
80
  return { op: "hub_roadmap_edit", args: { op: command, suggestion: integer(operands[0]) }, json };
54
81
  }
82
+ if (command === "decompose") {
83
+ if (operands.length !== 1) return usage("roadmap decompose needs one milestone id");
84
+ return { op: "hub_roadmap_decompose", args: { id: integer(operands[0]), ...(accept === undefined ? {} : { accept }) }, json };
85
+ }
55
86
  if (operands.length) return usage(`roadmap ${command} takes no operands`);
56
87
  const base = repo === undefined ? {} : { repo };
57
88
  if (command === "unplaced") return { op: "hub_roadmap_unplaced", args: base, json };
@@ -65,6 +96,7 @@ export function parseRoadmapArgs(argv: readonly string[]): RoadmapArgs {
65
96
  if (argv[index] === "--json") { json = true; index++; }
66
97
  const command = argv[index] ?? "list";
67
98
  if (argv[index] !== undefined) index++;
99
+ if (["check", "sync", "export"].includes(command)) return parseR4(command, argv.slice(index), json);
68
100
  if (!["list", "show", "new", "edit", "link", "unlink", "order", "state", ...R3_COMMANDS].includes(command)) return usage("unknown roadmap command");
69
101
  if (R3_COMMANDS.includes(command)) return parseR3(command, argv.slice(index), json);
70
102
  const operands: string[] = [], flags = new Map<string, string>();
@@ -165,6 +197,28 @@ export function renderRoadmap(input: unknown, width = 80): string {
165
197
  }
166
198
  };
167
199
  const names = (rows: unknown[], one: (value: Row) => string) => { for (const value of rows) add(one(row(value))); };
200
+ if (Array.isArray(view.findings) && Array.isArray(view.unknown)) {
201
+ add(`Roadmap drift (${view.findings.length} findings)`);
202
+ names(view.findings, finding => ` Rule ${count(finding.rule)}, milestone ${finding.milestone === null ? "none" : count(finding.milestone)}: ${text(finding.cause)}; ${list(finding.items).map(text).join(", ")}. Next: ${text(finding.remedy)}`);
203
+ if (view.unknown.length) add(`Unknown evidence for rules: ${view.unknown.map(count).join(", ")}`);
204
+ if (view.truncated === true) add("More findings exist; narrow the roadmap before relying on this list.");
205
+ return lines.join("\n");
206
+ }
207
+ if (Array.isArray(view.calls) && typeof view.fingerprint === "string") {
208
+ add(`GitHub mirror: ${view.applied ? "applied" : "dry run"}`);
209
+ for (const call of view.calls) if (Array.isArray(call)) add(` gh ${call.map(value => `'${String(value).replaceAll("'", "'\\''")}'`).join(" ")}`);
210
+ for (const binding of list(view.bindings)) { const b = row(binding); add(` Bind local milestone ${count(b.milestone)} to GitHub milestone ${count(b.number)}`); }
211
+ if (!view.applied) add(`Apply this exact preview: ahub roadmap sync --apply --confirm ${text(view.fingerprint)}`);
212
+ return lines.join("\n");
213
+ }
214
+ if (typeof view.markdown === "string" && typeof view.fingerprint === "string") {
215
+ add(view.markdown);
216
+ const endpoint = Array.isArray(view.call) ? view.call[1] : undefined;
217
+ const issue = typeof endpoint === "string" ? /\/issues\/([1-9][0-9]*)$/.exec(endpoint)?.[1] : undefined;
218
+ if (issue && !view.applied) add(`Apply this exact issue preview: ahub roadmap export --issue ${issue} --apply --confirm ${text(view.fingerprint)}`);
219
+ if (view.applied) add("GitHub issue update confirmed.");
220
+ return lines.join("\n");
221
+ }
168
222
  if (Array.isArray(view.issues) && Array.isArray(view.tasks) && Array.isArray(view.specs) && view.privateTasks !== undefined) {
169
223
  add(`Unplaced work${view.repo ? ` (${text(view.repo)})` : ""}`);
170
224
  if (view.partial === true) add("Partial: the GitHub read stopped early or a list was cut, so these lists are a lower bound.");
@@ -178,6 +232,29 @@ export function renderRoadmap(input: unknown, width = 80): string {
178
232
  add(`Private tasks counted, not listed: ${count(view.privateTasks)}`);
179
233
  return lines.join("\n");
180
234
  }
235
+ if (typeof view.part === "number" && typeof view.milestone === "number" && view.task !== undefined && view.task !== null) {
236
+ const task = row(view.task), draft = count(task.id);
237
+ add(`Milestone ${count(view.milestone)} part ${count(view.part)}: ${view.created === true ? "held as intake draft" : "already held as intake draft"} ${draft}`);
238
+ add(` ${text(task.title)} (${text(task.state)})`);
239
+ add(` ${view.intake === "spec" ? "It needs its own spec issue before implementation." : "It goes straight to a task."}`);
240
+ add(` Nothing offers it until the hold is released: ahub intake approve ${draft}`);
241
+ return lines.join("\n");
242
+ }
243
+ if (Array.isArray(view.parts) && typeof view.milestone === "number") {
244
+ add(`Milestone ${count(view.milestone)} decomposition`);
245
+ if (view.unavailable) add(`Decompose unavailable: ${text(view.unavailable)}`);
246
+ const saved = row(view.saved);
247
+ if (view.saved !== null && view.saved !== undefined) add(`${count(view.parts.length)} part${view.parts.length === 1 ? "" : "s"} saved as pending model answer ${count(saved.id)}; nothing is intaken, linked or published.`);
248
+ if (Number(view.dropped) > 0) add(`Dropped ${count(view.dropped)} model part${Number(view.dropped) === 1 ? "" : "s"} that cited nothing it was shown or did not fit the split schema.`);
249
+ for (const value of list(view.parts)) {
250
+ const part = row(value);
251
+ add(` ${text(part.title)} -> ${part.intake === "spec" ? "needs its own spec issue" : "goes straight to a task"} (${text(part.class)})`);
252
+ add(` cites: ${list(part.cites).map(text).join(", ")}`);
253
+ add(` ${text(part.detail)}`);
254
+ }
255
+ if (!list(view.parts).length && !view.unavailable) add("The model proposed no part that cited an id it was shown.");
256
+ return lines.join("\n");
257
+ }
181
258
  if (Array.isArray(view.suggestions)) {
182
259
  add(`Triage suggestions (${view.suggestions.length})`);
183
260
  if (view.unavailable) add(`Triage unavailable: ${text(view.unavailable)}`);
@@ -176,6 +176,9 @@ function taskBlock(row: any, columns: number | undefined, detail: boolean): Line
176
176
  function lifecycleView(reply: any, columns: number | undefined, detail: boolean): Line[] {
177
177
  const rows = list(reply?.rows);
178
178
  const out: Line[] = [...heading(`SDLC lifecycle, mode ${reply?.mode ?? "unknown"}`, columns)];
179
+ if (reply?.securityScan && typeof reply.securityScan === "object") {
180
+ out.push(...pair("security scan", Object.entries(reply.securityScan).map(([source, value]) => `${source}: ${value === null ? "unknown" : value}`).join(", "), columns, 14));
181
+ }
179
182
  if (!rows.length) return [...out, [s("no task has lifecycle state yet", "muted")]];
180
183
  if (!detail || rows.length > 1) {
181
184
  out.push(...grid(["ID", "STAGE", "READY", "ACTOR", "PR"], rows.map(row => [s(`#${row.id}`, "taskRef"), s(row.stage ?? "unknown"), s(yes(row.ready), readyTone(row.ready)), s(row.actor ?? "-"), s(row.receipt?.pr ? `#${row.receipt.pr}` : "-")]), columns));
@@ -263,9 +266,10 @@ export function renderSdlcRelease(reply: unknown, columns?: number, now = Date.n
263
266
  // ---- sdlc metrics / costs -----------------------------------------------------------------------------------------
264
267
 
265
268
  const SUMMARY_ROWS: [string, string, boolean][] = [
266
- ["acceptance_to_plan_ms", "acceptance to plan", true], ["acceptance_to_first_review_ms", "acceptance to first review", true], ["acceptance_to_merge_ms", "acceptance to merge", true],
269
+ ["acceptance_to_plan_ms", "acceptance to plan", true], ["accepted_to_plan_ms", "task acceptance to plan", true], ["acceptance_to_first_review_ms", "acceptance to first review", true], ["acceptance_to_merge_ms", "acceptance to merge", true],
267
270
  ["rework_rounds", "rework rounds", false], ["same_head_ci_reruns", "same-head CI reruns", false], ["stale_head_re_reviews", "stale-head re-reviews", false],
268
271
  ["review_rounds_at_merge", "review rounds at merge", false], ["ci_runs_at_merge", "CI runs at merge", false], ["github_reviews_at_merge", "GitHub reviews at merge", false],
272
+ ["full_gate_runs", "full gate runs", false], ["successful_gate_runs", "successful gate runs", false], ["failed_gate_runs", "failed gate runs", false], ["cancelled_gate_runs", "cancelled gate runs", false], ["other_gate_runs", "other gate runs", false], ["macos_shard_runs", "macOS shard runs", false],
269
273
  ];
270
274
  const BAND_TONE: Record<string, Tone> = { ok: "success", log: "muted", diagnose: "attention", propose: "failure" };
271
275
  /** `ahub sdlc metrics [--since ...]`: times and counts from board history, the two approval rates, stalls and band tiers. */
@@ -274,6 +278,9 @@ export function renderSdlcMetrics(result: unknown, columns?: number, now = Date.
274
278
  const out: Line[] = [...heading("SDLC metrics", columns)];
275
279
  out.push(...pair("window", m?.since === null || m?.since === undefined ? "all recorded history" : `since ${moment(m.since, now)}`, columns, 10),
276
280
  ...pair("tasks", `${m?.tasks ?? 0} counted${m?.withheldPrivate ? `, ${m.withheldPrivate} private withheld` : ""}`, columns, 10));
281
+ if (m?.securityScan && typeof m.securityScan === "object") {
282
+ out.push(...pair("security scan", Object.entries(m.securityScan).map(([source, value]) => `${source}: ${value === null ? "unknown" : value}`).join(", "), columns, 14));
283
+ }
277
284
  const metrics = m?.metrics ?? {};
278
285
  const value = (n: unknown, time: boolean) => time ? span(n) : count(n);
279
286
  out.push(blank, ...grid(["METRIC", "N", "UNKNOWN", "MEAN", "MEDIAN", "P90", "MAX"], SUMMARY_ROWS.map(([key, label, time]) => {
@@ -304,6 +311,9 @@ export function renderSdlcCosts(result: unknown, columns?: number, _now = Date.n
304
311
  out.push(...(out.length > 1 ? [blank] : []), ...wrap(repo, room(columns), 2).map((line): Line => [s(line, "info")]), ...grid(["PR", "ROUNDS", "CI", "RERUNS", "FULL", "DELTA", "REVIEW", "UNK", "OK"], rows.filter(row => String(row.repo) === repo).map(row => [
305
312
  s(`#${row.pr}`, "issueRef"), s(count(row.reviewRounds)), s(count(row.ciRuns)), s(count(row.ciReruns)), s(count(row.fullReReviews)), s(count(row.deltaReviews)), s(span(row.reviewMs)),
306
313
  s(count(row.unknownReviewScopes), row.unknownReviewScopes ? "attention" : "muted"), s(row.complete ? "yes" : "no", row.complete ? "success" : "attention")]), columns));
314
+ for (const row of rows.filter(row => String(row.repo) === repo && row.fullGateRuns !== undefined)) {
315
+ out.push(...para(`#${row.pr}: full gates ${count(row.fullGateRuns)} (success ${count(row.successfulGateRuns)}, failed ${count(row.failedGateRuns)}, cancelled ${count(row.cancelledGateRuns)}, other ${count(row.otherGateRuns)}); macOS shards ${count(row.macosShardRuns)}`, columns));
316
+ }
307
317
  }
308
318
  if (c?.truncated) out.push(blank, ...para("truncated: more PRs than one read covers, or a read was incomplete", columns, "attention"));
309
319
  if (c?.privateTasks === "withheld") out.push(...para("private tasks are withheld", columns, "muted"));
@@ -485,7 +485,8 @@ export function preserveSource(plan: UpgradePlan, home = hubHome()): string {
485
485
 
486
486
  const unboundRecoveryInspection = inspectRecovery;
487
487
 
488
- export function makeRecoveryDriver(run: RunCommand = runCommand, liveTestPeer?: string, clock?: Pick<RecoveryDriver, "now" | "sleep">, conductorPeer?: string): RecoveryDriver {
488
+ /** `clock.waitSliceMs` (#1578) is forwarded to the attachment wait as its poll slice, so a test can poll coarser; production passes nothing and keeps 1 s. */
489
+ export function makeRecoveryDriver(run: RunCommand = runCommand, liveTestPeer?: string, clock?: Pick<RecoveryDriver, "now" | "sleep"> & { waitSliceMs?: number }, conductorPeer?: string): RecoveryDriver {
489
490
  let authorizedOperation: RecoveryOperation | undefined;
490
491
  const recoveryCurrent = async () => { if (conductorPeer) { if (!authorizedOperation) throw new FinalRefusal("conductor recovery authority unavailable"); await authorizeConductorOperation(authorizedOperation, conductorPeer); } };
491
492
  const inspectRecovery = (project: Project, features?: readonly string[], purpose?: "cleanup") => unboundRecoveryInspection(project, features, purpose, conductorPeer);
@@ -640,8 +641,11 @@ export function makeRecoveryDriver(run: RunCommand = runCommand, liveTestPeer?:
640
641
  if (result.manualRequired) throw new Error(`${peer}: closing terminal ${retired.handle} of the stopped target's session was not verified; manual-required`);
641
642
  progress.terminals[key] = true; save();
642
643
  };
643
- /** #414: an idle terminal is not an authenticated peer. Keep its receipt while waiting, including on resume. */
644
- const awaitAttachment = async (planned: PlannedProject, progress: ProjectProgress, op: RecoveryOperation, waiting: Extract<RestoreReceipt, { state: "waiting" }>, save: () => void, expectedSession: string | null = waiting.binding.sessionId): Promise<string> => {
644
+ /** #414: an idle terminal is not an authenticated peer. Keep its receipt while waiting, including on resume.
645
+ * #1578: `waitSliceMs` is the poll slice, 1 s in production. It is a parameter with a default, not the enclosing `clock`, because
646
+ * `test/upgrade-timing-failure.test.ts` runs this closure's own source in a sandbox that provides only named ports. Only a test
647
+ * passes a larger slice, so a 600 s deadline costs fewer polls; the last slice is still clamped to the remaining time. */
648
+ const awaitAttachment = async (planned: PlannedProject, progress: ProjectProgress, op: RecoveryOperation, waiting: Extract<RestoreReceipt, { state: "waiting" }>, save: () => void, expectedSession: string | null = waiting.binding.sessionId, waitSliceMs = 1000): Promise<string> => {
645
649
  const saveTiming = () => {
646
650
  try { save(); }
647
651
  catch { console.warn("Recovery timing observation could not be saved; recovery continues"); }
@@ -686,7 +690,7 @@ export function makeRecoveryDriver(run: RunCommand = runCommand, liveTestPeer?:
686
690
  else { launchState = "older-instance"; olderHandle = evidence.handle; }
687
691
  } else if (evidence.state === "live" && evidence.session) {
688
692
  if (now() >= deadline) break;
689
- await sleep(Math.min(1000, deadline - now()));
693
+ await sleep(Math.min(waitSliceMs, deadline - now()));
690
694
  continue;
691
695
  }
692
696
  }
@@ -704,7 +708,7 @@ export function makeRecoveryDriver(run: RunCommand = runCommand, liveTestPeer?:
704
708
  throw nativeFailure(planned, binding.peer, "launcher_unverified", `${binding.peer}: the chosen restoration launcher's identity cannot be verified (${launchState}); saved terminal retained; no terminal was created`, { handle: binding.handle, launcherState: launchState });
705
709
  }
706
710
  if (now() >= deadline) break;
707
- await sleep(Math.min(1000, deadline - now()));
711
+ await sleep(Math.min(waitSliceMs, deadline - now()));
708
712
  }
709
713
  const terminal: NonNullable<ProjectProgress["attachmentTimeouts"]>[string]["terminal"] = { handle: binding.handle, incarnationId: binding.incarnationId, state: "unknown" };
710
714
  try {
@@ -973,7 +977,7 @@ export function makeRecoveryDriver(run: RunCommand = runCommand, liveTestPeer?:
973
977
  function awaitBound(waiting: Extract<RestoreReceipt, { state: "waiting" }> & { origin: "pending" }, expected: string | null): Promise<string>;
974
978
  function awaitBound(waiting: Extract<RestoreReceipt, { state: "waiting" }>, expected: string | null): Promise<string | undefined>;
975
979
  async function awaitBound(waiting: Extract<RestoreReceipt, { state: "waiting" }>, expected: string | null): Promise<string | undefined> {
976
- try { return await awaitAttachment(planned, progress, op, waiting, save, expected); }
980
+ try { return await awaitAttachment(planned, progress, op, waiting, save, expected, clock?.waitSliceMs); }
977
981
  catch (error) {
978
982
  if (!(error instanceof AttachmentLauncherGone)) throw error;
979
983
  progress.terminals[key] = error.transition.next; save();
@@ -1,3 +1,4 @@
1
+ import { scheduleRuntimeCapturePrune } from "../hub/runtime-capture-prune.ts";
1
2
  import { RecoveryLaunchError, type RecoveryLaunchFailure } from "./recovery-launch.ts";
2
3
  import { nativeRestoreGroup } from "../adapters/definitions/native-identity-defaults.ts";
3
4
  import { definitionOf } from "../adapters/registry.ts";
@@ -659,6 +660,11 @@ export function guardedRecoveryDriver(driver: RecoveryDriver, operation: () => R
659
660
  };
660
661
  }
661
662
 
663
+ /** #1546: a start that ran while this operation held its lock scheduled nothing; schedule runtime maintenance now that the lock is released. */
664
+ function pruneAfterRelease(home: string): void {
665
+ try { scheduleRuntimeCapturePrune(home); } catch { /* maintenance never changes a recovery outcome */ }
666
+ }
667
+
662
668
  /** Resumable state machine. Driver actions are preceded by receipts and followed by live readback. */
663
669
  export async function runRecovery(id: string, driver: RecoveryDriver, home = hubHome(), idleTimeoutMs = 600_000): Promise<RecoveryOperation> {
664
670
  // Read once to validate the selector, then claim the runner before trusting any
@@ -920,7 +926,7 @@ export async function runRecovery(id: string, driver: RecoveryDriver, home = hub
920
926
  if (scope === undefined && op.plan.kind === "upgrade" && !op.globalInstalled) {
921
927
  step("install-global"); await driver.installGlobal(op); op.globalInstalled = true; save();
922
928
  }
923
- releaseRecoveryLock(id, home, scope); op.phase = "completed"; step("completed");
929
+ releaseRecoveryLock(id, home, scope); pruneAfterRelease(home); op.phase = "completed"; step("completed");
924
930
  } catch (error) {
925
931
  // #215: every runner error ends with the choices status shows, read from every open source, never only this one.
926
932
  const presentationError = error instanceof RecoveryPresentationError ? error
@@ -1081,7 +1087,7 @@ export async function abortRecovery(id: string, driver: RecoveryDriver, home = h
1081
1087
  }
1082
1088
  delete op.error; delete op.failure; delete op.blockedReattachment; delete op.presentationCause;
1083
1089
  op.phase = "cancelled"; op.step = "cancelled"; op.updatedAt = driver.now();
1084
- writeOperation(id, op, home); releaseRecoveryLock(id, home, scope);
1090
+ writeOperation(id, op, home); releaseRecoveryLock(id, home, scope); pruneAfterRelease(home);
1085
1091
  } catch (error) {
1086
1092
  if (isDatabaseBusy(error)) throw new RecoveryDatabaseBusy();
1087
1093
  throw error;
@@ -1223,7 +1229,7 @@ export async function disposeRecovery(id: string, choice: { fresh: string } | {
1223
1229
  }
1224
1230
  delete op.error; delete op.failure;
1225
1231
  op.phase = "cancelled"; op.step = "disposed: stop-and-archive (abandoned, not completed)"; op.updatedAt = driver.now();
1226
- writeOperation(id, op, home); releaseRecoveryLock(id, home, scope);
1232
+ writeOperation(id, op, home); releaseRecoveryLock(id, home, scope); pruneAfterRelease(home);
1227
1233
  return op;
1228
1234
  } finally { releaseRunner(); }
1229
1235
  }
@@ -0,0 +1,43 @@
1
+ import packageJson from "../../package.json";
2
+
3
+ /**
4
+ * #1611: the first-party memory core is declared as `>=X.Y.Z <M.0.0` (X.Y.Z at or above 0.33.0, M the next major), so a new minor
5
+ * reaches users without a hub release; the host API range below, not the version number, decides whether it is compatible.
6
+ * Legacy `~X.Y.Z` (#1605) declarations still verify in an older recovery package.
7
+ */
8
+ export const AGENT_MEM_RANGE: string = packageJson.dependencies["@staix/agent-mem"];
9
+ /** The agent-mem host API versions this hub supports, inclusive: [min, max]. A new major host API is a reviewed hub change. */
10
+ export const AGENT_MEM_HOST_API_RANGE: readonly [number, number] = [1, 1];
11
+ /**
12
+ * #1611: the declared form `>=X.Y.Z <M.0.0` with X.Y.Z at or above 0.33.0 and M the next major.
13
+ * ponytail: a copy of scripts/lib/agent-mem-range.mjs, because a preserved source holds no scripts/ directory (the import failed in recovery); test/npm-pin.test.ts pins both to the same answers. Upgrade path: one shared file under src/ that the scripts import.
14
+ */
15
+ export function isAgentMemFloorRange(value: unknown): boolean {
16
+ const match = /^>=(\d+)\.(\d+)\.(\d+) <(\d+)\.0\.0$/.exec(typeof value === "string" ? value : "");
17
+ if (!match) return false;
18
+ const major = Number(match[1]), minor = Number(match[2]);
19
+ return Number(match[4]) === major + 1 && (major > 0 || minor >= 33);
20
+ }
21
+
22
+ /** The host API constants a staged package's src/memory/platform.ts exports, as numbers (undefined when absent). */
23
+ export function readHostApiConstants(source: string): { min: number | undefined; version: number | undefined } {
24
+ const read = (name: string): number | undefined => { const text = new RegExp(`export const ${name} = (\\d+)`).exec(source)?.[1]; return text === undefined ? undefined : Number(text); };
25
+ return { min: read("HOST_API_MIN"), version: read("HOST_API_VERSION") };
26
+ }
27
+ const PATCH_RANGE = /^~\d+\.\d+\.\d+$/;
28
+ const PLAIN_RELEASE = /^\d+\.\d+\.\d+$/;
29
+
30
+ /** Whether `version` is a plain release (no prerelease or build suffix) that satisfies the declared range (floor form, or legacy patch form). */
31
+ export function agentMemVersionInRange(version: unknown, range: string = AGENT_MEM_RANGE): boolean {
32
+ if (typeof version !== "string" || !PLAIN_RELEASE.test(version)) return false;
33
+ if (!PATCH_RANGE.test(range) && !isAgentMemFloorRange(range)) return false;
34
+ return Bun.semver.satisfies(version, range);
35
+ }
36
+
37
+ const positive = (value: unknown): value is number => typeof value === "number" && Number.isInteger(value) && value > 0;
38
+
39
+ /** Whether the package's host API constants are valid positive integers (MIN <= VERSION) and their range intersects the supported one. */
40
+ export function agentMemHostApiOk(min: unknown, version: unknown, supported: readonly [number, number] = AGENT_MEM_HOST_API_RANGE): boolean {
41
+ const [lowest, highest] = supported;
42
+ return positive(min) && positive(version) && min <= version && min <= highest && version >= lowest;
43
+ }
package/src/hub/board.ts CHANGED
@@ -20,7 +20,7 @@ import type { Database } from "./db-schema.ts";
20
20
  import { openHubDatabase, advanceHubDbSchema } from "./db-schema.ts";
21
21
  import { controlWriteSpan } from "./control-write-trace.ts";
22
22
  import { planningPatch, type PlanningFields, type Release, type ReleaseState } from "./planning.ts";
23
- import { MILESTONE_HISTORY_LIMIT, parseMilestoneInput, parseMilestonePatch, milestoneId, milestoneRevision, milestoneActor, milestoneHistory, milestoneLinkRef, type Milestone, type MilestoneInput, type MilestonePatch, type MilestoneLink, type MilestoneLinkKind, type MilestoneHistoryEntry, type MilestoneSuggestion, type SuggestionItemKind, type SuggestionState } from "./roadmap.ts";
23
+ import { MILESTONE_HISTORY_LIMIT, parseMilestoneInput, parseMilestonePatch, milestoneId, milestoneRevision, milestoneActor, milestoneHistory, milestoneLinkRef, githubRepo, type Milestone, type MilestoneInput, type MilestonePatch, type MilestoneLink, type MilestoneLinkKind, type MilestoneHistoryEntry, type MilestoneSuggestion, type SuggestionItemKind, type SuggestionState, type DecomposePart, type DecomposeIntake, type DecompositionState, type MilestoneDecomposition, type DecompositionAccept } from "./roadmap.ts";
24
24
  import { HUB, USER, type PeerId } from "./envelope.ts";
25
25
  import type { AuditFinding, AuditProfile, AuditUnit } from "./security-audit.ts";
26
26
  import type { ReviewFinding } from "./review-findings.ts";
@@ -72,6 +72,11 @@ const GUIDANCE_VARIANT_SELECT = `SELECT CASE WHEN typeof(id)='text' AND length(C
72
72
  export const HOST_MERGE_ADOPTION = Symbol("host merge adoption");
73
73
  /** Internal publication capability, independent of the person-only acceptance API. */
74
74
  export const HOST_SPEC_ACCEPTANCE_CARRY = Symbol("host spec acceptance carry");
75
+ /**
76
+ * Internal capability for R2 part 2 (#1480): the draft `roadmapDecomposePart` stages for an accepted part is held exactly like the
77
+ * person's intake draft. A Symbol cannot arrive in a tool argument, so no caller can stage a hidden draft through it.
78
+ */
79
+ export const HOST_ROADMAP_DRAFT = Symbol("host roadmap acceptance draft");
75
80
  export interface SpecAcceptanceCommit { source: number; cancellationRevision: number; acceptance: SpecAcceptance; }
76
81
 
77
82
  export interface ResearchCampaignRecord {
@@ -485,6 +490,7 @@ export interface Task extends PlanningFields {
485
490
 
486
491
  /** Structured execution evidence, including legacy rows whose owner was later cleared. */
487
492
  export function taskHasStarted(task: Pick<Task, "history">): boolean {
493
+ if (task.history.some(entry => entry.event === "check run passed" || entry.event === "check run failed")) return true;
488
494
  return task.history.some(entry => ["accepted", "done", "done (checking)", "check passed", "check failed", "changes_requested", "approved", "reopened", "integration requested", "integrated"].includes(entry.event));
489
495
  }
490
496
  /** S9 return eligibility never erases the historical acceptance used by cancellation and undo. */
@@ -592,6 +598,7 @@ export class Board {
592
598
  this.db.run("CREATE INDEX IF NOT EXISTS tasks_human_reviews ON tasks(id) WHERE state='in_review' AND reviewer='user'");
593
599
  // #481 S7: one row per log-tier band breach episode already announced, so a restart never repeats the notice.
594
600
  this.db.run("CREATE TABLE IF NOT EXISTS band_notices (marker TEXT PRIMARY KEY, at INTEGER NOT NULL)");
601
+ this.db.run("CREATE TABLE IF NOT EXISTS roadmap_notices (marker TEXT PRIMARY KEY, at INTEGER NOT NULL)");
595
602
  // #481 S7: one row per scheduled security scan. Counts only (no alert text); `total` is null when a named source could not be read completely.
596
603
  this.db.run("CREATE TABLE IF NOT EXISTS security_scans (id INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL, repo TEXT NOT NULL, sources TEXT NOT NULL, counts TEXT NOT NULL, total INTEGER)");
597
604
  // #843 AC3: one row per (agent id, installed version, planner) already queued, so a restart never repeats it.
@@ -646,6 +653,17 @@ export class Board {
646
653
  this.db.run("CREATE UNIQUE INDEX IF NOT EXISTS milestone_suggestions_pending ON milestone_suggestions(kind,ref) WHERE state='pending'");
647
654
  this.db.run(`CREATE TABLE IF NOT EXISTS milestone_imports (
648
655
  repo TEXT NOT NULL, number INTEGER NOT NULL, milestone INTEGER NOT NULL, at INTEGER NOT NULL, PRIMARY KEY(repo,number))`);
656
+ // R2 (#1480): model-written decompositions, additive and outside the roadmap integrity digest like a suggestion: a lost
657
+ // answer is asked for again, and one pending answer per milestone is the newest run.
658
+ this.db.run(`CREATE TABLE IF NOT EXISTS milestone_decompositions (
659
+ id INTEGER PRIMARY KEY AUTOINCREMENT, milestone INTEGER NOT NULL, parts TEXT NOT NULL,
660
+ state TEXT NOT NULL, by TEXT NOT NULL, created INTEGER NOT NULL, settled INTEGER, settled_by TEXT)`);
661
+ this.db.run("CREATE UNIQUE INDEX IF NOT EXISTS milestone_decompositions_pending ON milestone_decompositions(milestone) WHERE state='pending'");
662
+ // R2 part 2 (#1480): which parts of a pending answer are already held as intake drafts. Keyed by the answer and the part's
663
+ // 1-based position, so accepting the same part twice finds this row instead of making a second draft.
664
+ this.db.run(`CREATE TABLE IF NOT EXISTS milestone_decomposition_accepts (
665
+ decomposition INTEGER NOT NULL, milestone INTEGER NOT NULL, part INTEGER NOT NULL, task INTEGER NOT NULL,
666
+ intake TEXT NOT NULL, by TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY(decomposition,part))`);
649
667
 
650
668
  this.db.run(`CREATE TABLE IF NOT EXISTS research_campaigns (
651
669
  id TEXT NOT NULL, project TEXT NOT NULL, parent_task_id INTEGER NOT NULL, revision INTEGER NOT NULL,
@@ -2590,6 +2608,18 @@ export class Board {
2590
2608
  const rows = this.db.query(`SELECT id, at, total FROM security_scans WHERE repo=? AND sources=?${knownOnly ? " AND total IS NOT NULL" : ""} ORDER BY id DESC LIMIT ?`).all(repo.toLowerCase(), sources, Math.max(1, Math.min(1000, limit))) as { id: number; at: number; total: number | null }[];
2591
2609
  return rows.reverse();
2592
2610
  }
2611
+ /** The latest recorded per-source scan counts, with unreadable values kept unknown. */
2612
+ latestSecurityScanCounts(repo: string, sources: string): Record<string, number | null> | undefined {
2613
+ const row = this.db.query("SELECT counts FROM security_scans WHERE repo=? AND sources=? ORDER BY id DESC LIMIT 1").get(repo.toLowerCase(), sources) as { counts: string } | null;
2614
+ if (!row) return undefined;
2615
+ let counts: unknown;
2616
+ try { counts = JSON.parse(row.counts); } catch { counts = undefined; }
2617
+ const raw = counts && typeof counts === "object" && !Array.isArray(counts) ? counts as Record<string, unknown> : {};
2618
+ return Object.fromEntries(sources.split(",").filter(source => ["dependabot", "secret_scanning", "code_scanning"].includes(source)).map(source => {
2619
+ const value = raw[source];
2620
+ return [source, typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null];
2621
+ }));
2622
+ }
2593
2623
  recordSecurityScan(row: { repo: string; sources: string; counts: Record<string, number | null>; total: number | null }): number {
2594
2624
  if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(row.repo) || !/^[a-z_,]{1,80}$/.test(row.sources) || (row.total !== null && (!Number.isSafeInteger(row.total) || row.total < 0))) throw new Error("invalid security scan row");
2595
2625
  return Number(this.db.query("INSERT INTO security_scans(at, repo, sources, counts, total) VALUES(?,?,?,?,?)").run(Date.now(), row.repo.toLowerCase(), row.sources, JSON.stringify(row.counts), row.total).lastInsertRowid);
@@ -2599,6 +2629,15 @@ export class Board {
2599
2629
  if (!/^[a-z_]{1,64}:#[1-9][0-9]{0,9}:log$/.test(marker)) throw new Error("invalid band notice marker");
2600
2630
  return this.db.query("INSERT OR IGNORE INTO band_notices(marker, at) VALUES(?, ?)").run(marker, Date.now()).changes > 0;
2601
2631
  }
2632
+
2633
+ hasRoadmapNotice(marker: string): boolean {
2634
+ if (!/^[a-f0-9]{64}$/.test(marker)) throw new Error("invalid roadmap notice marker");
2635
+ return !!this.db.query("SELECT 1 FROM roadmap_notices WHERE marker=?").get(marker);
2636
+ }
2637
+ recordRoadmapNotice(marker: string): boolean {
2638
+ if (!/^[a-f0-9]{64}$/.test(marker)) throw new Error("invalid roadmap notice marker");
2639
+ return this.db.query("INSERT OR IGNORE INTO roadmap_notices(marker,at) VALUES(?,?)").run(marker, Date.now()).changes > 0;
2640
+ }
2602
2641
  /** True when the (id, version, planner) marker was new and is now recorded; false when it was announced before. */
2603
2642
  recordAgentDriftNotice(marker: string): boolean {
2604
2643
  if (!/^[a-z][a-z0-9-]{0,31}:[0-9A-Za-z][0-9A-Za-z.+_-]{0,63}@[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/.test(marker)) throw new Error("invalid agent drift marker");
@@ -2785,7 +2824,7 @@ export class Board {
2785
2824
  && priorHead !== undefined && /^[a-f0-9]{40}$/.test(priorHead);
2786
2825
  const previousHistory = backfill ? task.history.map((entry, index) => index === priorApproval && !entry.reviewedHead
2787
2826
  ? { ...entry, reviewedHead: entry.reviewFindings?.head ?? priorHead } : entry) : task.history;
2788
- const history = [...previousHistory, { at: Date.now(), by, event, ...(resolvedReviewComments?.length ? { resolvedReviewComments } : {}), ...(returnPlanning ? { planning: returnPlanning } : {}), ...(extra.invocation ? { invocation: extra.invocation } : {}), ...plannerHistory, ...authorHistory, ...(extra.selfReview === true ? { selfReview: true as const } : {}), ...(planRevision ? { planRevision } : {}), ...(extra.planObservation ? { planObservation: extra.planObservation } : {}), ...(extra.planDeparture ? { planDeparture: extra.planDeparture } : {}), ...(departureInvalidated ? { planDepartureInvalidated: true as const } : {}), ...reviewMetadata, ...specMetadata, ...(note ? { note } : {}), ...(patch.cancelled?.supersededBy ? { supersededBy: patch.cancelled.supersededBy } : {}), ...("owner" in patch ? { owner: next.owner } : {}), ...(extra.profile ? { profile: extra.profile } : {}), ...(extra.sweep ? { sweep: extra.sweep } : {}), ...(event === "wait recorded" && extra.wait && Number.isSafeInteger(extra.wait.until) && extra.wait.until > 0 ? { wait: { until: extra.wait.until, owner: extra.wait.owner } } : {}), ...(extra.reason && TASK_MOVE_REASONS.includes(extra.reason) ? { reason: extra.reason } : {}), ...(extra.from ? { from: extra.from } : {}), ...(extra.capacity === true ? { capacity: true as const } : {}), ...(extra.conductorManual === true ? { conductorManual: true as const } : {}), ...(extra.withheld && (note || reviewFindings) ? { withheld: true as const } : {}), ...(reviewFindings ? { reviewFindings } : {}), ...(extra.reviewedHead ? { reviewedHead: extra.reviewedHead } : {}), ...(unmetCriteria?.length ? { unmetCriteria } : {}), ...(securityPass ? { securityPass } : {}), ...(deliverables ? { deliverables } : {}), ...(extra.reviewContext === "fresh" || extra.reviewContext === "continuing" ? { reviewContext: extra.reviewContext } : {}), ...(extra.reviewScope === "code" ? { reviewScope: "code" as const } : {}), ...(extra.evidenceOnly === true && event === "changes_requested" ? { evidenceOnly: true as const } : {}), ...(extra.reviewCost ? { reviewCost: extra.reviewCost } : {}), ...(event === "done" && extra.requestHead && /^[a-f0-9]{40}$/.test(extra.requestHead) ? { requestHead: extra.requestHead } : {}), ...(event === "done" && extra.noWrites === true ? { noWrites: true as const } : {}), ...(["check passed", "check failed"].includes(event) && typeof extra.checkKey === "string" && /^[a-z][a-z0-9_]{0,47}$/.test(extra.checkKey) ? { checkKey: extra.checkKey } : {}), ...(["check passed", "check failed"].includes(event) && Number.isSafeInteger(extra.missingKeys) && extra.missingKeys! >= 0 && extra.missingKeys! <= 100_000 ? { missingKeys: extra.missingKeys } : {}), ...(event === "claim verdict" && extra.claim ? { claim: extra.claim } : {}) }];
2827
+ const history = [...previousHistory, { at: Date.now(), by, event, ...(resolvedReviewComments?.length ? { resolvedReviewComments } : {}), ...(returnPlanning ? { planning: returnPlanning } : {}), ...(extra.invocation ? { invocation: extra.invocation } : {}), ...plannerHistory, ...authorHistory, ...(extra.selfReview === true ? { selfReview: true as const } : {}), ...(planRevision ? { planRevision } : {}), ...(extra.planObservation ? { planObservation: extra.planObservation } : {}), ...(extra.planDeparture ? { planDeparture: extra.planDeparture } : {}), ...(departureInvalidated ? { planDepartureInvalidated: true as const } : {}), ...reviewMetadata, ...specMetadata, ...(note ? { note } : {}), ...(patch.cancelled?.supersededBy ? { supersededBy: patch.cancelled.supersededBy } : {}), ...("owner" in patch ? { owner: next.owner } : {}), ...(extra.profile ? { profile: extra.profile } : {}), ...(extra.sweep ? { sweep: extra.sweep } : {}), ...(event === "wait recorded" && extra.wait && Number.isSafeInteger(extra.wait.until) && extra.wait.until > 0 ? { wait: { until: extra.wait.until, owner: extra.wait.owner } } : {}), ...(extra.reason && TASK_MOVE_REASONS.includes(extra.reason) ? { reason: extra.reason } : {}), ...(extra.from ? { from: extra.from } : {}), ...(extra.capacity === true ? { capacity: true as const } : {}), ...(extra.conductorManual === true ? { conductorManual: true as const } : {}), ...(extra.withheld && (note || reviewFindings) ? { withheld: true as const } : {}), ...(reviewFindings ? { reviewFindings } : {}), ...(extra.reviewedHead ? { reviewedHead: extra.reviewedHead } : {}), ...(unmetCriteria?.length ? { unmetCriteria } : {}), ...(securityPass ? { securityPass } : {}), ...(deliverables ? { deliverables } : {}), ...(extra.reviewContext === "fresh" || extra.reviewContext === "continuing" ? { reviewContext: extra.reviewContext } : {}), ...(extra.reviewScope === "code" ? { reviewScope: "code" as const } : {}), ...(extra.evidenceOnly === true && event === "changes_requested" ? { evidenceOnly: true as const } : {}), ...(extra.reviewCost ? { reviewCost: extra.reviewCost } : {}), ...(["done", "check run passed", "check run failed"].includes(event) && extra.requestHead && /^[a-f0-9]{40}$/.test(extra.requestHead) ? { requestHead: extra.requestHead } : {}), ...(event === "done" && extra.noWrites === true ? { noWrites: true as const } : {}), ...(["check passed", "check failed", "check run passed", "check run failed"].includes(event) && typeof extra.checkKey === "string" && /^[a-z][a-z0-9_]{0,47}$/.test(extra.checkKey) ? { checkKey: extra.checkKey } : {}), ...(["check passed", "check failed"].includes(event) && Number.isSafeInteger(extra.missingKeys) && extra.missingKeys! >= 0 && extra.missingKeys! <= 100_000 ? { missingKeys: extra.missingKeys } : {}), ...(event === "claim verdict" && extra.claim ? { claim: extra.claim } : {}) }];
2789
2828
  this.taskWrite(() => {
2790
2829
  if (resolvedReviewComments?.length) for (const record of this.reviewComments(task.id, task.created)) {
2791
2830
  if (!resolvedReviewComments.includes(record.thread.id) || record.lifecycle !== "sent") continue;
@@ -3033,6 +3072,52 @@ export class Board {
3033
3072
  this.db.query("UPDATE milestone_suggestions SET created_milestone=? WHERE id=? AND state='pending' AND created_milestone IS NULL").run(milestoneId(milestone), milestoneId(id));
3034
3073
  }
3035
3074
 
3075
+ /** R2: one pending decomposition per milestone. A newer answer supersedes the older one in the same transaction, never doubles it. */
3076
+ addDecomposition(row: { milestone: number; parts: DecomposePart[] }, by: string, now = Date.now()): MilestoneDecomposition {
3077
+ const actor = milestoneActor(by), at = milestoneId(now), milestone = milestoneId(row.milestone);
3078
+ return this.db.transaction(() => {
3079
+ this.db.query("UPDATE milestone_decompositions SET state='superseded', settled=?, settled_by=? WHERE milestone=? AND state='pending'").run(at, actor, milestone);
3080
+ const inserted = this.db.query("INSERT INTO milestone_decompositions(milestone,parts,state,by,created) VALUES(?,?,'pending',?,?)").run(milestone, JSON.stringify(row.parts), actor, at);
3081
+ // Settled rows are history, not storage: keep the newest 200.
3082
+ this.db.query("DELETE FROM milestone_decompositions WHERE state<>'pending' AND id NOT IN (SELECT id FROM milestone_decompositions WHERE state<>'pending' ORDER BY id DESC LIMIT 200)").run();
3083
+ return this.decomposition(Number(inserted.lastInsertRowid))!;
3084
+ })();
3085
+ }
3086
+
3087
+ decomposition(id: number): MilestoneDecomposition | undefined {
3088
+ milestoneId(id);
3089
+ const row = this.db.query("SELECT * FROM milestone_decompositions WHERE id=?").get(id) as Record<string, unknown> | null;
3090
+ return row ? parseDecomposition(row) : undefined;
3091
+ }
3092
+
3093
+ decompositions(state?: DecompositionState): MilestoneDecomposition[] {
3094
+ const rows = (state === undefined ? this.db.query("SELECT * FROM milestone_decompositions ORDER BY id").all() : this.db.query("SELECT * FROM milestone_decompositions WHERE state=? ORDER BY id").all(state)) as Record<string, unknown>[];
3095
+ return rows.map(parseDecomposition);
3096
+ }
3097
+
3098
+ /** R2 part 2: the answer an accept reads its parts from. A superseded one is not pending, so an accept cannot land on it. */
3099
+ pendingDecomposition(milestone: number): MilestoneDecomposition | undefined {
3100
+ const row = this.db.query("SELECT * FROM milestone_decompositions WHERE milestone=? AND state='pending'").get(milestoneId(milestone)) as Record<string, unknown> | null;
3101
+ return row ? parseDecomposition(row) : undefined;
3102
+ }
3103
+
3104
+ /** R2 part 2: the draft one part already made, if it was accepted before. */
3105
+ decompositionAccept(decomposition: number, part: number): DecompositionAccept | undefined {
3106
+ const row = this.db.query("SELECT * FROM milestone_decomposition_accepts WHERE decomposition=? AND part=?").get(milestoneId(decomposition), milestoneId(part)) as Record<string, unknown> | null;
3107
+ return row ? parseDecompositionAccept(row) : undefined;
3108
+ }
3109
+
3110
+ /**
3111
+ * R2 part 2: record that a part is held as a draft. The insert is ignored on a repeated accept, so the row that already names
3112
+ * the first draft is the one a retry reads, and no second draft is ever keyed here.
3113
+ */
3114
+ acceptDecompositionPart(row: { decomposition: number; milestone: number; part: number; task: number; intake: DecomposeIntake }, by: string, now = Date.now()): DecompositionAccept {
3115
+ const actor = milestoneActor(by), at = milestoneId(now);
3116
+ this.db.query("INSERT OR IGNORE INTO milestone_decomposition_accepts(decomposition,milestone,part,task,intake,by,at) VALUES(?,?,?,?,?,?,?)")
3117
+ .run(milestoneId(row.decomposition), milestoneId(row.milestone), milestoneId(row.part), milestoneId(row.task), row.intake, actor, at);
3118
+ return this.decompositionAccept(row.decomposition, row.part)!;
3119
+ }
3120
+
3036
3121
  /** Compare-and-set from pending: a second settle of the same suggestion changes nothing. */
3037
3122
  settleSuggestion(id: number, state: "accepted" | "rejected" | "superseded", by: string, now = Date.now()): MilestoneSuggestion {
3038
3123
  const actor = milestoneActor(by), at = milestoneId(now);
@@ -3050,6 +3135,24 @@ export class Board {
3050
3135
  return row?.milestone;
3051
3136
  }
3052
3137
 
3138
+ /** R4 uses the same durable marks as R3 imports; conflicting legacy marks are never guessed. */
3139
+ mirrorMilestone(repo: string, id: number): number | undefined {
3140
+ const rows = this.db.query("SELECT number FROM milestone_imports WHERE repo=? AND milestone=? ORDER BY number LIMIT 2").all(githubRepo(repo), milestoneId(id)) as { number: number }[];
3141
+ if (rows.length > 1) throw new PreEffectToolRefusal("roadmap milestone has conflicting GitHub bindings; inspect imports before syncing");
3142
+ return rows[0]?.number;
3143
+ }
3144
+
3145
+ bindMirrorMilestone(repo: string, id: number, number: number, now = Date.now()): void {
3146
+ const key = githubRepo(repo), local = milestoneId(id), remote = milestoneId(number), at = milestoneId(now);
3147
+ this.db.transaction(() => {
3148
+ if (!this.milestone(local)) throw new PreEffectToolRefusal("roadmap milestone no longer exists; inspect ahub roadmap list");
3149
+ const prior = this.mirrorMilestone(key, local), owner = this.importedMilestone(key, remote);
3150
+ if (prior !== undefined && prior !== remote || owner !== undefined && owner !== local) throw new PreEffectToolRefusal("roadmap GitHub binding conflicts with an existing milestone; inspect imports before syncing");
3151
+ if (prior === remote && owner === local) return;
3152
+ this.db.query("INSERT INTO milestone_imports(repo,number,milestone,at) VALUES(?,?,?,?)").run(key, remote, local, at);
3153
+ })();
3154
+ }
3155
+
3053
3156
  /** One transaction: the milestone and its import mark exist together or not at all, so a repeat finds the mark. */
3054
3157
  importMilestone(repo: string, number: number, input: MilestoneInput, by: string, now = Date.now()): { milestone: Milestone; created: boolean } {
3055
3158
  const key = repo.toLowerCase();
@@ -3233,6 +3336,17 @@ function parseSuggestion(row: Record<string, unknown>): MilestoneSuggestion {
3233
3336
  settled: row.settled == null ? null : milestoneId(row.settled), settledBy: row.settled_by == null ? null : milestoneActor(row.settled_by) };
3234
3337
  }
3235
3338
 
3339
+ function parseDecomposition(row: Record<string, unknown>): MilestoneDecomposition {
3340
+ return { id: milestoneId(row.id), milestone: milestoneId(row.milestone), parts: JSON.parse(String(row.parts)) as DecomposePart[],
3341
+ state: row.state as DecompositionState, by: milestoneActor(row.by), created: milestoneId(row.created),
3342
+ settled: row.settled == null ? null : milestoneId(row.settled), settledBy: row.settled_by == null ? null : milestoneActor(row.settled_by) };
3343
+ }
3344
+
3345
+ function parseDecompositionAccept(row: Record<string, unknown>): DecompositionAccept {
3346
+ return { decomposition: milestoneId(row.decomposition), milestone: milestoneId(row.milestone), part: milestoneId(row.part), task: milestoneId(row.task),
3347
+ intake: row.intake as DecomposeIntake, by: milestoneActor(row.by), at: milestoneId(row.at) };
3348
+ }
3349
+
3236
3350
  function parseRelease(row: Record<string, unknown>): Release {
3237
3351
  return { ...(row.train == null ? {} : { train: JSON.parse(String(row.train)) }), planner: row.planner == null ? null : String(row.planner), id: Number(row.id), name: String(row.name), goal: String(row.goal), order: Number(row.release_order), state: row.state as ReleaseState,
3238
3352
  plannedStart: row.planned_start as number | null, cut: row.cut as number | null, ship: row.ship as number | null,
package/src/hub/bus.ts CHANGED
@@ -209,6 +209,8 @@ export class Bus {
209
209
  * and is never corrected once the queue empties (measured: status.json kept `queued 4` on an empty queue).
210
210
  */
211
211
  onQueues?: () => void;
212
+ /** Host-only registration observation; never changes delivery or peer state. */
213
+ onPeerAdded?: (peer: PeerId) => void;
212
214
  /**
213
215
  * #445 C2: a peer's answer to a delivery, offered BEFORE anything is built from it. The host returns true when the answer belongs to an invocation it
214
216
  * took over: the bus then publishes nothing, stores nothing, emits no event and lets no tap, queue, digest or memory path see it. `answers` is what the
@@ -303,6 +305,7 @@ export class Bus {
303
305
  }
304
306
 
305
307
  add(peer: PeerAdapter): void {
308
+ const newAttachment = this.peers.get(peer.id) !== peer;
306
309
  if (peer.remoteRoom !== undefined && (!parseRemotePeerId(peer.id) || typeof peer.remoteRoom !== "string" || !peer.remoteRoom || peer.remoteRoom.length > 256 || !remoteFingerprint(peer.remoteMember))) throw new Error("invalid remote peer binding");
307
310
  const pendingRemote = peer.remoteRoom !== undefined && this.hasRemoteWork(peer.id);
308
311
  if (peer.remoteRoom !== undefined && pendingRemote) {
@@ -458,6 +461,7 @@ export class Bus {
458
461
  this.emit({ t: "state", peer: peer.id, state: this.stateOf(peer.id) });
459
462
  void this.drain(peer.id);
460
463
  };
464
+ if (newAttachment) try { this.onPeerAdded?.(peer.id); } catch { /* observers cannot undo a registered peer */ }
461
465
  }
462
466
 
463
467
  private persist(): void {
@@ -40,6 +40,8 @@ export interface RunnerOptions {
40
40
  projectDir: string; stateDir: string; storageDir: string; projectKey: string;
41
41
  enabled: boolean | (() => boolean); isDenied: (path: string) => boolean;
42
42
  onResult?: (receipt: RunReceipt) => void | Promise<void>;
43
+ /** #1555 AC6: whether the task is approved or cancelled, so a run that settles after its task closed is compacted when it leaves the queue. */
44
+ taskClosed?: (task: number) => boolean;
43
45
  /** Daemon authority fence, re-evaluated across every asynchronous stage. */
44
46
  isCurrent?: (request: CheckRequest) => boolean;
45
47
  /** Test seams; never supplied from a tool request or config. */
@@ -262,7 +264,10 @@ export class ContainerRunner {
262
264
  const entry = this.queue.shift(); if (!entry) return;
263
265
  this.active = entry;
264
266
  try { await this.execute(entry); }
265
- finally { this.active = undefined; this.entries.delete(entry.receipt.run); entry.resolve({ ...entry.receipt }); void this.drain(); }
267
+ finally { this.active = undefined; this.entries.delete(entry.receipt.run); entry.resolve({ ...entry.receipt }); void this.compactIfClosed(entry.receipt.task); void this.drain(); }
268
+ }
269
+ private async compactIfClosed(task: number): Promise<void> {
270
+ try { if (this.options.taskClosed?.(task)) await this.compactTask(task); } catch { /* retention only: the files stay */ }
266
271
  }
267
272
  private async heavy(entry: Entry): Promise<() => Promise<void>> {
268
273
  const lock = join(this.common, "ahub-heavy.lock");
@@ -497,6 +502,25 @@ export class ContainerRunner {
497
502
  }
498
503
  }
499
504
  async consumeOutput(run: string): Promise<void> { if (/^[a-f0-9-]{36}$/.test(run)) await rm(join(this.root, run, "output.log"), { force: true }); }
505
+ /**
506
+ * #1555 AC6: a task reached approved or cancelled. Its finished receipts keep every field the verdict and the metrics read, but lose the output tail, and the staged output
507
+ * file goes with it (nobody reads either once the task is closed). A run still queued or running is left alone, and each rewrite goes through the receipt's own save turn.
508
+ */
509
+ async compactTask(task: number): Promise<number> {
510
+ const names = await readdir(this.records).catch(error => { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; });
511
+ let compacted = 0;
512
+ for (const name of names) {
513
+ const run = name.endsWith(".json") ? name.slice(0, -5) : "";
514
+ if (!/^[a-f0-9-]{36}$/.test(run) || this.entries.has(run)) continue;
515
+ let receipt: RunReceipt | undefined;
516
+ try { receipt = await this.result(run); } catch { continue; }
517
+ if (!receipt || receipt.task !== task || (receipt.status !== "finished" && receipt.status !== "stale")) continue;
518
+ if (receipt.tail !== "") { receipt.tail = ""; await this.save(receipt); }
519
+ await this.consumeOutput(run);
520
+ compacted++;
521
+ }
522
+ return compacted;
523
+ }
500
524
  async cancel(run: string): Promise<void> {
501
525
  const entry = this.entries.get(run); if (!entry) return;
502
526
  entry.receipt.cancelled = true; entry.abort.abort();