@staix/agent-hub 0.35.0 → 0.37.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 (165) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +25 -4
  3. package/THIRD_PARTY_NOTICES.md +0 -18
  4. package/docs/agent-notes/README.md +71 -1
  5. package/docs/agent-notes/adapters.md +5 -2
  6. package/docs/agent-notes/bus.md +1 -0
  7. package/docs/agent-notes/daemon.md +7 -6
  8. package/docs/agent-notes/local-worker.md +1 -0
  9. package/docs/agent-notes/models.md +5 -3
  10. package/docs/agent-notes/tasks.md +9 -2
  11. package/docs/agent-notes/tests.md +1 -1
  12. package/docs/contracts/companion-cli-v1.json +70 -0
  13. package/docs/design/adapters.md +115 -2
  14. package/docs/design/agent-hub-architecture.md +10 -2
  15. package/docs/design/bus.md +8 -0
  16. package/docs/design/execution-reference.md +171 -11
  17. package/docs/design/guidance-experiments.md +438 -0
  18. package/docs/design/guidance-probes.md +802 -0
  19. package/docs/design/model-routes.md +1053 -0
  20. package/docs/design/supervision.md +121 -0
  21. package/docs/design/task-board.md +111 -0
  22. package/docs/dogfood.md +24 -15
  23. package/docs/events.md +20 -1
  24. package/docs/memory.md +3 -3
  25. package/docs/operations.md +366 -133
  26. package/docs/profiles.md +2 -2
  27. package/docs/quickstart.md +114 -3
  28. package/docs/research.md +5 -3
  29. package/docs/sdlc.md +113 -7
  30. package/docs/security.md +88 -6
  31. package/docs/specs/2026-09-19-agent-hub-design.md +14 -11
  32. package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
  33. package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
  34. package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
  35. package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
  36. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +61 -0
  37. package/docs/verification/2026-11-10-0.36.0.md +59 -0
  38. package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
  39. package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
  40. package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
  41. package/docs/verification/2026-11-11-0.37.0.md +40 -0
  42. package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
  43. package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
  44. package/docs/verification/claude-shell-wrapper-native.py +1 -1
  45. package/docs/verified.json +27 -27
  46. package/package.json +3 -4
  47. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  48. package/plugins/agent-hub/kimi-hook.js +3570 -1800
  49. package/plugins/agent-hub/server.js +4112 -1913
  50. package/src/adapters/channel-peer.ts +7 -1
  51. package/src/adapters/claude-channel.ts +7 -4
  52. package/src/adapters/compat.ts +10 -10
  53. package/src/adapters/local-probe.ts +174 -0
  54. package/src/adapters/local-worker.ts +233 -22
  55. package/src/adapters/qwen-dual.ts +324 -44
  56. package/src/cli/console-state.ts +25 -6
  57. package/src/cli/console-versions.ts +99 -0
  58. package/src/cli/console.ts +13 -1
  59. package/src/cli/guidance.ts +67 -0
  60. package/src/cli/help.ts +12 -4
  61. package/src/cli/identity.ts +10 -3
  62. package/src/cli/init-prompt.ts +15 -2
  63. package/src/cli/init-required-checks.ts +122 -0
  64. package/src/cli/init-settings.ts +10 -4
  65. package/src/cli/init.ts +39 -3
  66. package/src/cli/install-paths.ts +7 -2
  67. package/src/cli/lineage.ts +78 -0
  68. package/src/cli/main.ts +171 -14
  69. package/src/cli/runtime-version-warning.ts +2 -2
  70. package/src/cli/sdlc-output.ts +9 -5
  71. package/src/cli/setup-research.ts +10 -0
  72. package/src/hub/autonomy-defaults.ts +20 -9
  73. package/src/hub/board.ts +346 -4
  74. package/src/hub/build-entry.ts +11 -0
  75. package/src/hub/bus.ts +12 -0
  76. package/src/hub/ci-watch.ts +4 -4
  77. package/src/hub/config-apply.ts +6 -3
  78. package/src/hub/config-trust.ts +7 -1
  79. package/src/hub/control-client.ts +5 -2
  80. package/src/hub/daemon.ts +508 -26
  81. package/src/hub/delivery-hints.ts +4 -2
  82. package/src/hub/delivery-journal.ts +50 -2
  83. package/src/hub/delivery-public.ts +51 -0
  84. package/src/hub/dogfood-profile.ts +8 -4
  85. package/src/hub/events.ts +3 -2
  86. package/src/hub/execution-lineage-owner.ts +272 -0
  87. package/src/hub/execution-lineage.ts +52 -8
  88. package/src/hub/execution-links.ts +85 -0
  89. package/src/hub/guidance-probe-store.ts +713 -0
  90. package/src/hub/guidance-probes.ts +358 -0
  91. package/src/hub/guidance-variants.ts +398 -0
  92. package/src/hub/handoff.ts +1 -0
  93. package/src/hub/hub-tools.ts +43 -2
  94. package/src/hub/inference.ts +18 -5
  95. package/src/hub/manager.ts +44 -2
  96. package/src/hub/memory-policy.ts +2 -2
  97. package/src/hub/operational-authority.ts +13 -1
  98. package/src/hub/peers.ts +6 -1
  99. package/src/hub/planning.ts +1 -1
  100. package/src/hub/ports.ts +1 -1
  101. package/src/hub/progress.ts +47 -23
  102. package/src/hub/report.ts +2 -0
  103. package/src/hub/research.ts +1 -0
  104. package/src/hub/restart.ts +20 -0
  105. package/src/hub/roles.ts +26 -0
  106. package/src/hub/routing.ts +4 -1
  107. package/src/hub/sdlc-merge.ts +39 -1
  108. package/src/hub/sdlc-release-authorization.ts +139 -17
  109. package/src/hub/sdlc-release-policy.ts +100 -0
  110. package/src/hub/sdlc-release.ts +60 -8
  111. package/src/hub/sdlc.ts +62 -11
  112. package/src/hub/settings.ts +2 -0
  113. package/src/hub/supervision-proposals.ts +405 -0
  114. package/src/hub/supervision-rules.ts +388 -0
  115. package/src/hub/supervision.ts +2 -0
  116. package/src/hub/task-approval.ts +2 -2
  117. package/src/hub/task-repository.ts +5 -0
  118. package/src/hub/tasks.ts +917 -53
  119. package/src/local/probe-errors.ts +28 -0
  120. package/src/local/probe-sandbox.ts +224 -0
  121. package/src/local/probe-types.ts +108 -0
  122. package/src/local/probe-workspace.ts +237 -0
  123. package/src/local/sandbox.ts +71 -2
  124. package/src/local/tools.ts +135 -9
  125. package/src/memory/capture.ts +2 -2
  126. package/src/models/relay.ts +9 -2
  127. package/src/models/route/advisor-trigger.ts +88 -0
  128. package/src/models/route/config.ts +39 -8
  129. package/src/models/route/conversation-view.ts +179 -0
  130. package/src/models/route/decision-evidence.ts +1 -1
  131. package/src/models/route/decision.ts +193 -26
  132. package/src/models/route/escalation-control.ts +30 -0
  133. package/src/models/route/hub-prompts.ts +97 -0
  134. package/src/models/route/judge-choice.ts +155 -0
  135. package/src/models/route/judge-replies.ts +102 -0
  136. package/src/models/route/labels.ts +14 -70
  137. package/src/models/route/observation-signals.ts +250 -0
  138. package/src/models/route/plan-execute-choice.ts +27 -0
  139. package/src/models/route/relay-selector.ts +10 -9
  140. package/src/models/route/runtime.ts +129 -60
  141. package/src/models/route/stage-diagnostics.ts +22 -0
  142. package/src/models/route/stage-evidence.ts +55 -0
  143. package/src/models/route/stage-fallback.ts +58 -0
  144. package/src/models/route/stage-input.ts +155 -0
  145. package/src/models/route/stage.ts +5 -147
  146. package/src/models/route/turn-state.ts +77 -0
  147. package/src/omniroute/client.ts +3 -0
  148. package/src/ui/guidance-panel.ts +156 -0
  149. package/src/ui/guidance-view.ts +43 -0
  150. package/src/ui/lineage-view.ts +34 -0
  151. package/src/ui/plugin.ts +141 -27
  152. package/src/version.ts +4 -0
  153. package/templates/adec/README.md +32 -0
  154. package/templates/adec/ahub.plan-execute.json +23 -0
  155. package/templates/adec/ahub.stage.json +23 -0
  156. package/LICENSES/Apache-2.0.txt +0 -204
  157. package/src/models/route/advisor.ts +0 -102
  158. package/src/models/route/escalation.ts +0 -82
  159. package/src/models/route/judge.ts +0 -23
  160. package/src/models/route/normalize.ts +0 -103
  161. package/src/models/route/plan-execute.ts +0 -52
  162. package/src/models/route/prompts.ts +0 -8
  163. package/src/models/route/signals.ts +0 -247
  164. package/src/models/route/state.ts +0 -54
  165. package/src/models/route/text.ts +0 -61
@@ -16,6 +16,7 @@ import { windowKind } from "../hub/window-kind.ts";
16
16
  import { ownerIsolationText, taskHolderText } from "./role-holders.ts";
17
17
  import { USAGE_DROP, USAGE_HEAD, usageCells, usageDetail, usagePeers, usageTaskLines, type UsageState } from "./console-usage.ts";
18
18
  import type { RoomStatusView } from "../rooms/status.ts";
19
+ import { peerHubVersion, type ConsoleVersions } from "./console-versions.ts";
19
20
 
20
21
  export interface Approval {
21
22
  id: string; peer: string; title: string; expiresAt: number;
@@ -39,6 +40,8 @@ export interface ConsoleState {
39
40
  pendingRestart?: { key: string; reason: string }[];
40
41
  retainedConfig?: { key: string; reason: string }[];
41
42
  features?: readonly string[];
43
+ /** #1385: the agent-hub versions in play, and the native agent CLIs the hub has not verified (status `agentDrift`). */
44
+ versions?: ConsoleVersions; agentDrift?: readonly { id: string; version: string; state: string; receipt: string }[];
42
45
  /** #1053 T4: the open questions the hub reported (the person's text, shown here only) and the answer being built; `A` starts it. */
43
46
  questions?: QuestionView[]; questionFlow?: QuestionFlow; questionsSeen?: string[];
44
47
  /** Older embedding callers omit choices and retain the original STAI/off toggle. */
@@ -364,14 +367,28 @@ export function budgetFields(budget: any, now: number): [string, unknown][] {
364
367
  return [["quota", lines.length ? lines : typeof budget.note === "string" ? budget.note : "no reading"], ...(lines.length && typeof budget.note === "string" ? [["quota note", budget.note] as [string, unknown]] : [])];
365
368
  }
366
369
  /** #784 AC3: the Peers detail carries the planner WIP split as one line (`1 of 2: active 1, review-wait 0, reserved 0`); a hub that sends none adds nothing. */
370
+ /** #1385: one line above the peer table: the running daemon, this console, the global CLI and the plugin, older ones in attention, then the peers that load another version. */
371
+ function versionsLine(s: ConsoleState): Span[] {
372
+ const v = s.versions!;
373
+ const parts: Span[] = [span("agent-hub", "info")];
374
+ for (const [label, value, key] of [["daemon", v.daemon, undefined], ["console", v.cli, "cli"], ["global", v.global, "global"], ["plugin", v.plugin, "plugin"]] as const) {
375
+ const older = !!key && v.older.includes(key);
376
+ parts.push(span(` ${label} ${value ?? "unknown"}${older ? " (older)" : ""}`, older ? "attention" : value ? undefined : "muted"));
377
+ }
378
+ const differing = Object.entries(s.peers).filter(([id, peer]) => peerHubVersion({ id, ...peer }, v.daemon).differs).map(([id]) => id);
379
+ if (differing.length) parts.push(span(` ${plural(differing.length, "peer")} on another version: ${differing.join(", ")}`, "attention"));
380
+ return parts;
381
+ }
367
382
  function peerDetailRow(s: ConsoleState, row: any, now: number): Record<string, unknown> {
368
383
  const wip = s.taskWip?.[row.id];
369
384
  const split = wip && [wip.active, wip.reviewWait, wip.reserved].every(n => Number.isSafeInteger(n)) ? `${wip.wip} of ${wip.wipLimit}: active ${wip.active}, review-wait ${wip.reviewWait}, reserved ${wip.reserved}` : undefined;
370
385
  const isolation = ownerIsolationText(row.ownerIsolation, row.ownerIsolationNote);
371
- const { standbySessions, ...fields } = row;
386
+ const { standbySessions, ahub: _ahub, ahubTools: _tools, ...fields } = row;
387
+ const hub = peerHubVersion(row, s.versions?.daemon).detail;
388
+ const drift = s.agentDrift?.find(agent => agent.id === row.id);
372
389
  const standby = Array.isArray(standbySessions) ? standbySessions.filter((session: any) => session && typeof session.id === "string").map((session: any) =>
373
390
  `${typeof session.pid === "number" ? `pid ${session.pid}` : "pid unknown"}; session ${session.id}${typeof session.since === "number" ? `; waiting since ${relative(session.since, now)}` : ""}`) : [];
374
- return { ...fields, ...(standby.length ? { "standing by": standby } : {}), ...(isolation ? { ownerIsolation: isolation } : {}), ...(split ? { "planner WIP": split } : {}) };
391
+ return { ...fields, ...(hub ? { "agent-hub": hub } : {}), ...(drift ? { "agent CLI": `${drift.version} ${drift.state}; last receipt ${drift.receipt}` } : {}), ...(standby.length ? { "standing by": standby } : {}), ...(isolation ? { ownerIsolation: isolation } : {}), ...(split ? { "planner WIP": split } : {}) };
375
392
  }
376
393
  const detailLines = (detail: Detail, columns: number, now: number, task = false): Span[][] => {
377
394
  if (typeof detail === "string") return wrap(detail, columns).map(text => [span(text)]);
@@ -962,7 +979,7 @@ export function activeNotice(s: Pick<ConsoleState, "notice" | "noticeAt" | "noti
962
979
  return !!s.notice && now - (s.noticeAt ?? now) < (s.noticeMs ?? NOTICE_MS);
963
980
  }
964
981
  export const TABLES: Record<number, string[]> = {
965
- 1: ["PEER", "STATE", "LINK", "Q", "!", "WIP", "REVIEW", "PAUSE", "QUOTA", "MODEL", "DOING"],
982
+ 1: ["PEER", "STATE", "LINK", "AHUB", "Q", "!", "WIP", "REVIEW", "PAUSE", "QUOTA", "MODEL", "DOING"],
966
983
  2: ["ID", "PEER", "LEFT", "TITLE"],
967
984
  3: ["ID", "STATE", "OWNER", "REVIEWER", "CLASS", "AGE", "TITLE", "STAGE"],
968
985
  4: ["ID", "PEER", "STATE", "REV", "AGE"],
@@ -989,6 +1006,7 @@ export function cells(s: ConsoleState, row: any, selected: boolean, now: number,
989
1006
  return [id(row.planner ? `${row.id} (planner)` : row.id, row.state === "offline" ? undefined : "info"), span(`${row.rostered === false ? `${row.state} off roster` : row.state}${Array.isArray(row.standbySessions) && row.standbySessions.length ? ` +standby:${row.standbySessions.length}` : ""}`, stateTone(row.state)),
990
1007
  ...(showPermissionModes(s) ? [span(row.permissionMode && row.permissionMode !== "ask" ? row.permissionMode : "-", row.permissionMode === "never-ask" ? "attention" : undefined)] : []),
991
1008
  span(row.pullOnly && definitionOf(row.id)?.attach?.pullOnlyForms?.includes("tui") ? "pull-only" : row.toolsOnly ? "tools-only" : row.attached === false ? "detached" : "attached", row.toolsOnly ? "attention" : undefined),
1009
+ ((hub) => span(hub.cell, hub.differs ? "attention" : hub.cell === "-" || hub.unknown ? "muted" : undefined))(peerHubVersion(row, s.versions?.daemon)),
992
1010
  span(count(row.queued)), span(count(row.queuedImportant), row.queuedImportant ? "attention" : undefined),
993
1011
  span(wip ? `${wip.wip}/${wip.wipLimit}` : "-", wip && wip.wip >= wip.wipLimit ? "attention" : undefined),
994
1012
  span(count(row.needsReview), row.needsReview ? "failure" : undefined), span(paused, paused === "-" ? undefined : "attention"),
@@ -1065,10 +1083,10 @@ export function table(head: string[], rows: Span[][], columns: number, explicitW
1065
1083
  }));
1066
1084
  }
1067
1085
  /** Keep the status/quota columns visible instead of clipping them behind optional peer metadata. */
1068
- function optionalTable(head: string[], rows: Span[][], columns: number, drop = ["DOING", "MODEL", "WIP", "PAUSE", "REVIEW", "LINK", "Q", "!", "MODE"]): Span[][] {
1086
+ function optionalTable(head: string[], rows: Span[][], columns: number, drop = ["DOING", "MODEL", "WIP", "PAUSE", "REVIEW", "AHUB", "LINK", "Q", "!", "MODE"]): Span[][] {
1069
1087
  const cap = Math.max(24, Math.floor(columns / 3));
1070
1088
  const widths = head.map((name, i) => Math.min(cap, rows.reduce((max, row) => Math.max(max, Bun.stringWidth(flat(row[i]?.text ?? ""))), name.length)));
1071
- const keep = head.map((_, i) => i).filter(i => head[i] !== "DOING" || rows.some(row => row[i]?.text !== "-")); // #878: shown once a peer has one
1089
+ const keep = head.map((_, i) => i).filter(i => !["DOING", "AHUB"].includes(head[i]!) || rows.some(row => row[i]?.text !== "-")); // #878, #1385: shown once a peer has one
1072
1090
  const total = () => keep.reduce((sum, i) => sum + widths[i]!, 0) + 2 * (keep.length - 1);
1073
1091
  for (const name of drop) {
1074
1092
  if (total() <= columns - 2) break;
@@ -1285,7 +1303,7 @@ export function renderConsoleLines(s: ConsoleState, columns: number, rows = 24,
1285
1303
  const selectedTask = s.panel === 3 ? data[at] : undefined;
1286
1304
  const holders = selectedTask && (selectedTask.planner !== undefined || selectedTask.plannerReason !== undefined)
1287
1305
  ? fieldLines((["planner", "owner", "reviewer"] as const).map((role): [string, unknown] => [role, taskHolderText(selectedTask, role)]), columns, now).flat() : [];
1288
- const capacity = Math.max(1, s.panel === 2 ? Math.min(Math.floor(height / 2) - 1, height - 3 - tail.length) : s.panel === 7 ? height - 2 - taskLines.length : height - (s.panel === 3 ? 2 + holders.length : 1)); const start = Math.max(0, at - capacity + 1);
1306
+ const capacity = Math.max(1, s.panel === 2 ? Math.min(Math.floor(height / 2) - 1, height - 3 - tail.length) : s.panel === 7 ? height - 2 - taskLines.length : height - (s.panel === 3 ? 2 + holders.length : s.panel === 1 && s.versions ? 2 : 1)); const start = Math.max(0, at - capacity + 1);
1289
1307
  const stages = new Map(progress.stages.map(stage => [stage.id, stage]));
1290
1308
  const cellRows = head ? data.map((row, i) => cells(s, row, i === at, now, stages)) : [];
1291
1309
  const rowsOf = head ? s.panel === 7 ? optionalTable(head, cellRows, columns, USAGE_DROP) : s.panel === 1 ? optionalTable(head, cellRows, columns) : s.panel === 3 && s.backlogView ? optionalTable(head, cellRows, columns, ["AGE", "CLASS", "DEPS", "PRI"]) : table(head, cellRows, columns) : undefined;
@@ -1304,6 +1322,7 @@ export function renderConsoleLines(s: ConsoleState, columns: number, rows = 24,
1304
1322
  : `usage through ${s.usage.at ? relative(s.usage.at, now) : "now"}: today is the UTC day, 7d the last seven UTC days`;
1305
1323
  lines.push(fitLine([span(note, s.usage?.problem ? "failure" : !s.usage?.life || s.usage.behind ? "attention" : "info")], columns));
1306
1324
  }
1325
+ if (s.panel === 1 && s.versions) lines.push(fitLine(versionsLine(s), columns));
1307
1326
  if (s.panel === 8 && s.rooms === null) lines.push(fitLine([span("Room status unavailable", "attention")], columns));
1308
1327
  if (s.panel === 3 && s.backlogView) {
1309
1328
  lines.push(fitLine([span(s.tasksKnown === false ? "backlog loading..." : `backlog ${data.length}`, s.tasksKnown === false ? "attention" : "info")], columns));
@@ -0,0 +1,99 @@
1
+ import { closeSync, fstatSync, openSync, readSync, constants } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { DOCTOR_PLUGIN_PROBE } from "../adapters/registry.ts";
4
+ import { childEnv } from "../hub/child-process.ts";
5
+ import { withoutOrcaEnv } from "../hub/orca-env.ts";
6
+ import { displayVersion } from "../version.ts";
7
+ import { globalCliRoot } from "./install-paths.ts";
8
+ import { runtimeVersionWarnings } from "./runtime-version-warning.ts";
9
+ import { parseList, pluginState, type InstalledPlugin } from "./setup.ts";
10
+
11
+ /** #1385: the agent-hub versions the console shows. Every value is display only; a missing one is unknown, never matching. */
12
+ export interface ConsoleVersions {
13
+ daemon?: string;
14
+ cli: string;
15
+ global?: string;
16
+ plugin?: string;
17
+ /** The ones older than the running daemon, by the comparison `ahub doctor` prints (`runtimeVersionWarnings`), plus a global install older than it. */
18
+ older: ("cli" | "global" | "plugin")[];
19
+ }
20
+
21
+ // Contract: a package.json is a few KiB; a larger file is not an agent-hub manifest.
22
+ const MANIFEST_BYTES = 64 * 1024;
23
+ // Contract: the same bound `ahub doctor` and `ahub upgrade` give the plugin listing.
24
+ const PLUGIN_PROBE_MS = 10_000;
25
+ // Contract: a Claude plugin listing is a few KiB; more is not one.
26
+ const PLUGIN_PROBE_BYTES = 256 * 1024;
27
+
28
+ /** The version in the `package.json` of the `ahub` on PATH, read without running it. Unknown when no `ahub` resolves to a package root or its manifest is unreadable. */
29
+ export function globalCliVersion(env: NodeJS.ProcessEnv = process.env): string | undefined {
30
+ const root = globalCliRoot(env);
31
+ if (!root) return;
32
+ let fd: number | undefined;
33
+ try {
34
+ fd = openSync(join(root, "package.json"), constants.O_RDONLY | constants.O_NOFOLLOW);
35
+ const size = fstatSync(fd).size;
36
+ if (size > MANIFEST_BYTES) return;
37
+ const buffer = Buffer.alloc(size);
38
+ readSync(fd, buffer, 0, size, 0);
39
+ const manifest = JSON.parse(buffer.toString("utf8")) as { name?: unknown; version?: unknown };
40
+ return manifest.name === "@staix/agent-hub" ? displayVersion(manifest.version) : undefined;
41
+ } catch { return; } finally { if (fd !== undefined) closeSync(fd); }
42
+ }
43
+
44
+ /** The installed Claude plugin's version from the `claude plugin list --json` listing `ahub doctor` reads, once, bounded. A missing `claude`, a failure or an unreadable list is unknown. */
45
+ export async function installedPluginVersion(packageRoot: string): Promise<string | undefined> {
46
+ try {
47
+ const child = Bun.spawn([DOCTOR_PLUGIN_PROBE.command, ...DOCTOR_PLUGIN_PROBE.argv], { env: withoutOrcaEnv(childEnv()), stdin: "ignore", stdout: "pipe", stderr: "ignore" });
48
+ const timer = setTimeout(() => child.kill(), PLUGIN_PROBE_MS);
49
+ try {
50
+ const reader = child.stdout.getReader();
51
+ const chunks: Uint8Array[] = [];
52
+ let bytes = 0;
53
+ for (;;) {
54
+ const { done, value } = await reader.read();
55
+ if (done) break;
56
+ bytes += value.byteLength;
57
+ if (bytes > PLUGIN_PROBE_BYTES) { child.kill(); await reader.cancel(); return; }
58
+ chunks.push(value);
59
+ }
60
+ if (await child.exited !== 0) return;
61
+ const state = pluginState(parseList<InstalledPlugin>(Buffer.concat(chunks).toString("utf8")), packageRoot);
62
+ return state.state === "missing" ? undefined : displayVersion(state.version);
63
+ } finally { clearTimeout(timer); }
64
+ } catch { return; }
65
+ }
66
+
67
+ /** Both readings for `ahub console`, started once at launch so no draw waits on them. */
68
+ export async function installedVersions(packageRoot: string): Promise<{ global?: string; plugin?: string }> {
69
+ const global = globalCliVersion(), plugin = await installedPluginVersion(packageRoot);
70
+ return { ...(global ? { global } : {}), ...(plugin ? { plugin } : {}) };
71
+ }
72
+
73
+ export function consoleVersions(daemon: unknown, cli: string, global: string | undefined, plugin: string | undefined): ConsoleVersions {
74
+ const running = displayVersion(daemon);
75
+ const older: ConsoleVersions["older"] = [];
76
+ if (running) {
77
+ const warned = new Set(runtimeVersionWarnings(running, cli, plugin).filter(row => row.level === "warn").map(row => row.name));
78
+ if (warned.has("CLI versus daemon")) older.push("cli");
79
+ try { if (global && Bun.semver.order(global, running) < 0) older.push("global"); } catch { /* not comparable: shown, never flagged */ }
80
+ if (warned.has("plugin versus daemon")) older.push("plugin");
81
+ }
82
+ return { ...(running ? { daemon: running } : {}), cli, ...(global ? { global } : {}), ...(plugin ? { plugin } : {}), older };
83
+ }
84
+
85
+ /** What a peer's AHUB cell and detail say, from its status `ahub`/`ahubTools`; `differs` when any loaded version is not the daemon's. Older hubs send neither: `-`. */
86
+ export function peerHubVersion(row: { ahub?: { runs?: unknown; version?: unknown }; ahubTools?: unknown }, daemon: string | undefined): { cell: string; differs: boolean; unknown?: boolean; detail?: string } {
87
+ const runs = row.ahub?.runs, own = displayVersion(row.ahub?.version);
88
+ const tools = Array.isArray(row.ahubTools) ? row.ahubTools.filter((v): v is string => typeof v === "string" && (v === "unreported" || !!displayVersion(v))) : [];
89
+ const parts = [runs === "daemon" ? "daemon" : runs === "client" ? own ?? "unreported" : undefined, ...(tools.length ? [`tools ${tools.join(",")}`] : [])].filter((p): p is string => !!p);
90
+ if (!parts.length) return { cell: "-", differs: false };
91
+ // An unreported version is unknown, never a difference: only a version someone reported can differ from the daemon's.
92
+ const loaded = [...(runs === "client" && own ? [own] : []), ...tools.filter(v => v !== "unreported")];
93
+ const unknown = runs === "client" && !own || tools.includes("unreported");
94
+ const differs = !!daemon && loaded.some(v => v !== daemon);
95
+ const detail = `${runs === "daemon" ? `runs inside the daemon (${daemon ?? "unknown"})` : runs === "client" ? `client ${own ?? "unreported"}` : "no client attached"}${tools.length ? `; tools connections ${tools.join(", ")}` : ""}`
96
+ + (differs ? `; differs from the daemon ${daemon}: update the global CLI and run ahub setup, then restart that agent's session to load it` : "")
97
+ + (unknown ? "; an unreported version is unknown (a client older than #1385 sends none)" : "");
98
+ return { cell: parts.join(" "), differs, unknown, detail };
99
+ }
@@ -17,6 +17,8 @@ import { pasteFlow, questionRows } from "./console-question.ts";
17
17
  import { characterAttentionLine } from "./attention.ts";
18
18
  import { projectRoomStatus } from "../rooms/status.ts";
19
19
  import { LIVE_TEST_PERSON_REFUSAL } from "./identity.ts";
20
+ import { consoleVersions } from "./console-versions.ts";
21
+ import { VERSION } from "../version.ts";
20
22
 
21
23
  export interface ConsoleTerminal {
22
24
  columns: number; rows: number; isTTY: boolean; isRaw?: boolean;
@@ -40,6 +42,8 @@ export interface ConsoleOptions {
40
42
  /** Injected command runner must use argv, closed stdin, and return a cancellation handle. */
41
43
  runCommand?: (args: string[], output: (text: string) => void, done: (code?: number) => void, columns?: number) => (() => void);
42
44
  pollMs?: number;
45
+ /** #1385: the global CLI and installed plugin versions, read once off the render loop; absent reads as unknown. */
46
+ installed?: Promise<{ global?: string; plugin?: string }>;
43
47
  }
44
48
  /** Exact navigation sequences only (#309, #441); anything else in a multi-character read is a paste. */
45
49
  const NAVIGATION = ["\x1b[A", "\x1b[B", "\x1b[C", "\x1b[D", ...FIRST_KEYS, ...LAST_KEYS].filter(key => key.startsWith("\x1b"));
@@ -107,6 +111,8 @@ export async function runConsole(options: ConsoleOptions): Promise<void> {
107
111
  let resolveDone: () => void = () => {}; const done = new Promise<void>(resolve => { resolveDone = resolve; });
108
112
  let pendingStream: ConsoleEvent[] = []; let droppedStream = 0;
109
113
  let presentation = consoleOperationalSnapshot(undefined);
114
+ let installed: { global?: string; plugin?: string } = {};
115
+ options.installed?.then(value => { installed = value; if (state.versions) state.versions = consoleVersions(state.versions.daemon, VERSION, installed.global, installed.plugin); }, () => {});
110
116
  let priorStreamFooterStart: number | undefined;
111
117
  let lastExpandedNotice = "";
112
118
  const notice = (text: string, tone: Tone = "failure") => notify(state, text, Date.now(), tone);
@@ -238,6 +244,10 @@ export async function runConsole(options: ConsoleOptions): Promise<void> {
238
244
  if (status.status && status.ok !== false) state.pendingRestart = Array.isArray(status.status.pendingRestart) ? status.status.pendingRestart : [];
239
245
  if (status.status && status.ok !== false) state.retainedConfig = Array.isArray(status.status.retainedConfig) ? status.status.retainedConfig : [];
240
246
  if (status.status) state.features = Array.isArray(status.status.features) ? status.status.features : [];
247
+ if (status.status && status.ok !== false) {
248
+ state.versions = consoleVersions(status.status.version, VERSION, installed.global, installed.plugin);
249
+ state.agentDrift = Array.isArray(status.status.agentDrift) ? status.status.agentDrift : [];
250
+ }
241
251
  if (status.status && status.ok !== false) {
242
252
  const rooms = status.status.rooms;
243
253
  state.rooms = rooms === undefined ? undefined : rooms === null ? null : Array.isArray(rooms) ? projectRoomStatus(rooms).sort((a, b) => a.name.localeCompare(b.name)) : null;
@@ -252,7 +262,9 @@ export async function runConsole(options: ConsoleOptions): Promise<void> {
252
262
  }
253
263
  if (status.status?.peers) state.peers = Object.fromEntries(Object.entries(status.status.peers).map(([peer, value]) => [peer, { ...(value as object), ...status.status.roleInfo?.[peer],
254
264
  ...(typeof status.status.ownerIsolation?.[peer] === "boolean" ? { ownerIsolation: status.status.ownerIsolation[peer] } : {}),
255
- ...(typeof status.status.ownerIsolationNotes?.[peer] === "string" ? { ownerIsolationNote: status.status.ownerIsolationNotes[peer] } : {}) }]));
265
+ ...(typeof status.status.ownerIsolationNotes?.[peer] === "string" ? { ownerIsolationNote: status.status.ownerIsolationNotes[peer] } : {}),
266
+ ...(status.status.peerVersions?.[peer]?.ahub ? { ahub: status.status.peerVersions[peer].ahub } : {}),
267
+ ...(status.status.peerVersions?.[peer]?.ahubTools ? { ahubTools: status.status.peerVersions[peer].ahubTools } : {}) }]));
256
268
  if (status.status && status.ok !== false) {
257
269
  state.taskWip = status.status.taskWip ?? {};
258
270
  state.attentionFacts = attentionFacts(status.status.attentionItems);
@@ -0,0 +1,67 @@
1
+ import { executionText } from "../hub/execution-reference.ts";
2
+ import { GUIDANCE_HASH_HEX_LENGTH, GUIDANCE_CURSOR_MAX_BYTES, parseGuidanceWriteReceipt, type GuidanceDiffResult, type GuidancePageResult, type GuidanceWriteReceipt } from "../hub/guidance-variants.ts";
3
+ import { guidanceLines, guidanceReceiptLines } from "../ui/guidance-view.ts";
4
+ import { terminalText } from "./console-state.ts";
5
+
6
+ export const GUIDANCE_USAGE = "usage: ahub guidance create --file FILE [--json] | list --task N --task-created MS [--cursor TOKEN] [--json] | show --task N --task-created MS --id HASH [--json] | withdraw --task N --task-created MS --revision R --id HASH [--json]";
7
+ type Create = { op: "create"; json: boolean; file: string };
8
+ type List = { op: "list"; json: boolean; taskId: number; taskCreated: number; cursor?: string };
9
+ type Show = { op: "show"; json: boolean; taskId: number; taskCreated: number; id: string };
10
+ type Withdraw = { op: "withdraw"; json: boolean; taskId: number; taskCreated: number; flowRevision: number; id: string };
11
+ export type GuidanceCommand = Create | List | Show | Withdraw;
12
+ const invalid = (): never => { throw new Error(`invalid guidance arguments; ${GUIDANCE_USAGE}`); };
13
+ const integer = (raw: string | undefined, minimum: number): number => {
14
+ if (raw === undefined || !/^(0|[1-9][0-9]*)$/.test(raw)) return invalid();
15
+ const value = Number(raw);
16
+ return Number.isSafeInteger(value) && value >= minimum ? value : invalid();
17
+ };
18
+ const contentId = (raw: string | undefined): string =>
19
+ typeof raw === "string" && raw.length === GUIDANCE_HASH_HEX_LENGTH && /^[a-f0-9]+$/.test(raw) ? raw : invalid();
20
+ /** The explicit filename remains a selector; main owns its bounded read and the complete V1 parse. */
21
+ export function parseGuidanceCommand(args: readonly string[]): GuidanceCommand {
22
+ const [op, ...rest] = args;
23
+ if (op !== "create" && op !== "list" && op !== "show" && op !== "withdraw") return invalid();
24
+ const allowed = op === "create" ? ["--file"] : op === "list" ? ["--task", "--task-created", "--cursor"]
25
+ : op === "show" ? ["--task", "--task-created", "--id"] : ["--task", "--task-created", "--revision", "--id"];
26
+ const values = new Map<string, string>(); let json = false;
27
+ for (let index = 0; index < rest.length; index++) {
28
+ const flag = rest[index]!;
29
+ if (flag === "--json") { if (json) return invalid(); json = true; continue; }
30
+ if (!allowed.includes(flag) || values.has(flag)) return invalid();
31
+ const value = rest[++index];
32
+ if (typeof value !== "string" || value.length === 0 || value.startsWith("--") || /[\p{Cc}\p{Cf}\p{Cs}]/u.test(value)) return invalid();
33
+ values.set(flag, value);
34
+ }
35
+ if (op === "create") {
36
+ const file = values.get("--file");
37
+ if (!file) return invalid();
38
+ return { op, json, file };
39
+ }
40
+ const taskId = integer(values.get("--task"), 1), taskCreated = integer(values.get("--task-created"), 0);
41
+ if (op === "list") {
42
+ if (!values.has("--cursor")) return { op, json, taskId, taskCreated };
43
+ const cursor = values.get("--cursor")!;
44
+ // V1 wire bound: authentication and task/actor binding belong to the source host.
45
+ if (!executionText(cursor, GUIDANCE_CURSOR_MAX_BYTES) || !/^[A-Za-z0-9_-]+$/.test(cursor)) return invalid();
46
+ return { op, json, taskId, taskCreated, cursor };
47
+ }
48
+ const id = contentId(values.get("--id"));
49
+ return op === "show" ? { op, json, taskId, taskCreated, id }
50
+ : { op, json, taskId, taskCreated, flowRevision: integer(values.get("--revision"), 0), id };
51
+ }
52
+
53
+ export { parseGuidancePageResult as validateGuidancePageReply, parseGuidanceDiffResult as validateGuidanceDiffReply } from "../hub/guidance-variants.ts";
54
+ /** An unconfirmed write never authorizes an automatic retry or reinterprets a displayed experiment label as a selector. */
55
+ export function validateGuidanceReceipt(value: unknown, expected: { id?: string; taskId?: number; status?: "withdrawn" }): GuidanceWriteReceipt {
56
+ const unconfirmed = (): never => { throw new Error("guidance write reply is unconfirmed; inspect ahub guidance list for the task before retrying the write"); };
57
+ try {
58
+ const receipt = parseGuidanceWriteReceipt(value);
59
+ if (expected.id !== undefined && receipt.id !== expected.id || expected.taskId !== undefined && receipt.taskId !== expected.taskId
60
+ || expected.status !== undefined && receipt.status !== expected.status) return unconfirmed();
61
+ return receipt;
62
+ } catch { return unconfirmed(); }
63
+ }
64
+ /** The shared view contains public data only; terminal controls are stripped at this surface. */
65
+ const terminalLines = (lines: readonly string[]): string[] => lines.map(line => terminalText(line).replace(/[\r\n]+/g, " "));
66
+ export const renderGuidance = (result: GuidancePageResult | GuidanceDiffResult): string[] => terminalLines(guidanceLines(result));
67
+ export const renderGuidanceReceipt = (receipt: GuidanceWriteReceipt): string[] => terminalLines(guidanceReceiptLines(receipt));
package/src/cli/help.ts CHANGED
@@ -12,8 +12,8 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
12
12
  ["ahub --project <path|id> <command>", "select a repository or worktree explicitly"],
13
13
  ["ahub projects [--json] [--full] [--color=auto|always|never]", "list registered projects and live status"],
14
14
  ["ahub projects remove <id>", "forget a stopped registration (keeps project files)"],
15
- ["ahub setup [--yes] [--agents <a,b>]", "install or update the channel plugin and project-neutral hook in Claude configuration homes in use, preserving unrelated profile settings, ask once which agents ahub up starts (--agents answers it, --yes keeps the current choice or claude,codex, no terminal keeps the default), register the acon console plugin (console/plugins/ahub.json in the hub home, read at acon's next start), then run doctor"],
16
- ["ahub init [--profile dev|research|writing|general|<pack>] [--agents <a,b,...|none>] [--sdlc off|advise|enforce] [--coordination advisory|turn-free] [--memory|--no-memory] [--snapshots|--no-snapshots] [--pi|--no-pi] [--specs|--no-specs] [--spec-review off|report|require] [--autonomy inherit|off] [--shadow] [--release-guard] [--yes] [--dry-run --json]", "preview or write .agenthub/config.json and the AGENTS.md marker block (drops a legacy CLAUDE.md block); a pack is a shipped one (writing-pack, analysis, ops) or a project file .agenthub/roles/<name>.pack.json; a new project inherits a trusted machine autonomy default and the agent set chosen at ahub setup (start.agents) into config.local.json. Settings flags (#1065): --agents sets start.agents (none starts no agent) and --autonomy off skips the autonomy inheritance, both in config.local.json; --sdlc sets sdlc.toml mode (off writes no file on a new project); --coordination, --memory, --snapshots and --pi set their keys in config.json. On an existing project only a flag you give changes anything, and --dry-run shows each change as old -> new (--dry-run --json adds a settings array); a value equal to the current one is a no-op, an invalid value is refused with the allowed ones and nothing is written. --specs/--no-specs and --spec-review set the design-specs keys (and the AGENTS.md specs block). A person at a terminal who runs ahub init on a new project with no flag that sets anything and no --yes is asked each setting in turn with its default in brackets (Enter keeps it, a wrong answer asks again, and a third wrong answer ends init with nothing written), sees the plan and answers y/N; N, Ctrl-C and Ctrl-D write nothing. A peer, a live test, a pipe and --dry-run are never asked, and --yes takes the defaults. Executables, secrets, models and permissions stay file edits"],
15
+ ["ahub setup [--yes] [--agents <a,b>] [--research|--no-research]", "install or update the channel plugin and project-neutral hook in Claude configuration homes in use, preserving unrelated profile settings, ask once which agents ahub up starts (--agents answers it, --yes keeps the current choice or claude,codex, no terminal keeps the default), save the research default only with explicit --research/--no-research (ordinary setup leaves it unchanged), register the acon console plugin (console/plugins/ahub.json in the hub home, read at acon's next start), then run doctor"],
16
+ ["ahub init [--profile dev|research|writing|general|<pack>] [--agents <a,b,...|none>] [--sdlc off|advise|enforce] [--required-checks <a,b,...>] [--coordination advisory|turn-free] [--memory|--no-memory] [--research|--no-research] [--snapshots|--no-snapshots] [--pi|--no-pi] [--specs|--no-specs] [--spec-review off|report|require] [--autonomy inherit|off] [--shadow] [--release-guard] [--yes] [--dry-run --json]", "preview or write .agenthub/config.json and the AGENTS.md marker block (drops a legacy CLAUDE.md block); a pack is a shipped one (writing-pack, analysis, ops) or a project file .agenthub/roles/<name>.pack.json; a new project inherits a trusted machine autonomy default and the agent set chosen at ahub setup (start.agents) into config.local.json. Settings flags (#1065): --agents sets start.agents (none starts no agent), --research/--no-research sets research.enabled (new project default: the trusted setup choice, else off) and --autonomy off skips the autonomy inheritance, all in config.local.json; --sdlc sets sdlc.toml mode (off writes no file on a new project); advise/enforce discovers required checks from CI or literal workflow job names; --required-checks overrides discovery, and enforce without names refuses before writes; --coordination, --memory, --snapshots and --pi set their keys in config.json. On an existing project only a flag you give changes anything, and --dry-run shows each change as old -> new (--dry-run --json adds a settings array); a value equal to the current one is a no-op, an invalid value is refused with the allowed ones and nothing is written. --specs/--no-specs and --spec-review set the design-specs keys (and the AGENTS.md specs block). A person at a terminal who runs ahub init on a new project with no flag that sets anything and no --yes is asked each setting in turn with its default in brackets (Enter keeps it, a wrong answer asks again, and a third wrong answer ends init with nothing written), sees the plan and answers y/N; N, Ctrl-C and Ctrl-D write nothing. A peer, a live test, a pipe and --dry-run are never asked, and --yes takes the defaults. Success prints next steps to commit shared init changes, start with ahub up or ahub claude and, for advise/enforce, accept specs/departures and use guarded merge. Executables, secrets, models and permissions stay file edits"],
17
17
  ["ahub --live-test [--project <path|id>] <command> [args...]", "user-authorized operational console delegation; ordinary calls retain peer identity; person-authored content refuses"],
18
18
  ["ahub help [command]", "this help, or one command's entries; also --help and -h"],
19
19
  ["ahub version | --version", "print the installed version"],
@@ -27,8 +27,9 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
27
27
  ["ahub pet --palette <blue|teal|violet|ochre>", "retired floating-window option: run acon ui and open Mini"],
28
28
  ["ahub sdlc status [task] | explain <task> [--json] [--color=auto|always|never] | export <task> | record <task> <receipt-json>", "read head-bound lifecycle gates and the next actor/action; status and explain are open to any agent as a public view (private tasks stay stubs), export and record are person only; export stays JSON"],
29
29
  ["ahub sdlc queue <owner/repo> | release <owner/repo> [live-issue...] [--json] [--color=auto|always|never]", "read-only merge and release evidence; open to any agent as public readback of the checkout's repositories, never an authorization"],
30
+ ["ahub sdlc adopt-merge <task> --pr <n>", "record an already merged PR at the task's recorded head with green required checks and no open Important finding; approve and release dependents (person or current conductor)"],
30
31
  ["ahub sdlc merge <task> [--dry-run] [--json] [--color=auto|always|never]", "guarded squash merge of an approved task at its approved head after every gate is re-read; follows sdlc.toml auto_merge (off, dry-run, on); --dry-run only reports (person or conductor)"],
31
- ["ahub sdlc authorize-release <version> [--json] [--color=auto|always|never]", "approve this daemon checkout commit, version and fresh docs (person or unique configured conductor on the person's explicit release instruction naming the release in its own session; hub/task/review/file/peer relays never qualify; restart revokes)"],
32
+ ["ahub sdlc authorize-release <version> [--json] [--color=auto|always|never]", "approve this daemon checkout commit, configured version source and docs policy (person or unique configured conductor on the person's explicit release instruction naming the release in its own session; hub/task/review/file/peer relays never qualify; restart revokes)"],
32
33
  ["ahub sdlc release-guard -- <literal git push|gh release create|npm publish argv>", "read-only authorization preflight; init --release-guard installs the tag pre-push hook"],
33
34
  ["ahub sdlc release-guard-hook <remote-name> <remote-url>", "internal pre-push readback; validates version tags and forwards exact stdin on success"],
34
35
  ["ahub sdlc accept <task> --issue <n> [--repo owner/repo]", "accept the task's spec issue at its current body; build entry needs it in enforce (person only)"],
@@ -80,7 +81,7 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
80
81
  ["ahub roster add <peer> | remove <peer> [--yes] [--now]", "person or configured conductor: change live participation through settings; removal previews retained messages and task handoff; remove also deletes the roster key of an instance no longer declared"],
81
82
  ["ahub autonomy on [--all-projects] [--yes] | off [--all-projects] | status [--json]", "person only: apply the autonomy preset and machine default with one confirmation, optionally to every registered project; off removes fixed preset keys (manual edits included); status reports modes, floor enforcement and Claude homes; settings undo restores a live-hub project write"],
82
83
  ["ahub model set <peer> <model> | clear <peer> | list [--json]", "person only: select a runtime model at the next turn, clear its override, or inspect effective models and pending changes; unsupported peers need a restart"],
83
- ["ahub settings [list] [--json] | get <key> [--json]", "the settings the dashboard can change, each with its value, the file it comes from and when it applies"],
84
+ ["ahub settings [list] [--json] | get <key> [--json]", "the settings the dashboard can change, each with its value, the file it comes from and when it applies; get sdlc.mode or sdlc.required_checks reads running and file values without adding writable keys"],
84
85
  ["ahub settings set <key> <value|inherit> [--yes] [--preview] [--now] | undo | reload", "validated settings: conductor set is limited to exact live operational keys; undo/reload and other keys are person only; --preview saves nothing; conductor writes keep the person undo record"],
85
86
  ["ahub settings edit <config.local.json|sdlc.toml> (set <path> <json> | remove <path>)... [--reason <text>] [--preview] [--yes] | backups [--json]", "human only: structural config (instances, review, snapshots, approvals, context.gate, research.runners, sdlc.toml mode and required_checks) validated by the hub's own loaders, previewed as a diff and written with a backup; a key that runs code or locates secrets needs its name typed, never --yes"],
86
87
  ["ahub pause|resume <peer>", "hold a peer's deliveries in its queue / release them"],
@@ -138,6 +139,13 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
138
139
  ["ahub budget execution configure <config.json> | disable <id> [--json] [--color=auto|always|never]", "opt-in limits on model calls, tool calls, time and tokens for pi and local"],
139
140
  ]],
140
141
  ["History and reports", [
142
+ ["ahub guidance probe register --file JSON [--json] | start --id HASH --revision N [--variant G1-HASH] [--json] | show --id HASH [--json] | cancel --id HASH --revision N [--json]", "person or configured conductor only: bounded T1 declaration and fake-only probe lifecycle; production execution is unavailable"],
143
+ ["ahub guidance create --file JSON [--json]", "record a bounded immutable advisory proposal through current task authority; no activation or probe"],
144
+ ["ahub guidance list --task N --task-created MS [--cursor TOKEN] [--json]", "bounded guidance metadata pages; withdrawn history and withheld fields remain explicit"],
145
+ ["ahub guidance show --task N --task-created MS --id HASH [--json]", "screened editable-section diff selected by existing variant id, never a displayed experiment label"],
146
+ ["ahub guidance withdraw --task N --task-created MS --revision R --id HASH [--json]", "one-way withdrawal using current task flow; retained history never becomes active guidance"],
147
+ ["ahub lineage show (--task N | --attempt ra-id | --root JSON [--task-scope N --task-created MS]) [--cursor TOKEN] [--nodes N --edges N --bytes N] [--json]", "bounded execution metadata and explicit evidence strengths; unavailable stays unknown, with no probes or replay"],
148
+ ["ahub lineage link --task N --task-created MS --revision N --ref JSON [--from JSON] [--json]", "register a declared metadata link through the task's current authority and revision; no producer attestation"],
141
149
  ["ahub turns [peer] [--limit N] [--json] [--color=auto|always|never]", "recent turns and the files each changed (a git work tree only)"],
142
150
  ["ahub undo <turn> [--yes] [--context]", "put back the files a turn changed; refuses files changed since. Without --yes it only lists them; --context also drops a Codex turn from its conversation"],
143
151
  ["ahub report [--since 7d|<iso>] [--by task] [--json] [--color=auto|always|never]", "turns, tokens, messages, overlaps and task events per period"],
@@ -15,6 +15,8 @@ export const LIVE_TEST_PERSON_REFUSAL = "live-test cannot write person-attribute
15
15
 
16
16
  /** Person verdicts and user-authored workflow content are never delegated. */
17
17
  export function liveTestRefusal(command: string, args: readonly string[], context: { repairedFresh?: boolean } = {}): boolean {
18
+ if (command === "lineage" && args[0] === "link") return true;
19
+ if (command === "guidance" && ["create", "withdraw"].includes(args[0] ?? "")) return true;
18
20
  if (command === "model") return true; // #1317: even listing runtime overrides is person-only, never live-test delegated.
19
21
  if (command === "sdlc" && (args[0] === "authorize-release" || args[0] === "plan-review" || args[0] === "release-assign" || args[0] === "merge" || args[0] === "train" && args[1] !== "report")) return true;
20
22
  if (args.some(arg => arg === "--as-user" || arg.startsWith("--as-user="))) return true;
@@ -27,7 +29,7 @@ export function liveTestRefusal(command: string, args: readonly string[], contex
27
29
  // #601: a campaign's draft, revise, approve and close are the person's verdicts; only `show` is a read. Without this an agent shell could run them as the person through `--live-test`.
28
30
  || (command === "study" && sub !== "show" && sub !== "experiments")
29
31
  || (command === "recovery" && (sub === "reattach" || sub === "dispose" && context.repairedFresh === true))
30
- || (command === "board" && args[0] === "import") || (command === "sdlc" && (args[0] === "record" || args[0] === "accept" || args[0] === "accept-departure"))
32
+ || (command === "board" && args[0] === "import") || (command === "sdlc" && (args[0] === "record" || args[0] === "accept" || args[0] === "accept-departure" || args[0] === "adopt-merge"))
31
33
  || (command === "bench" && args.find(arg => arg !== "--json") === "run") || command === "pet"
32
34
  // #691: trusting an untested agent CLI version is the person's consent, never a delegated live-test operation.
33
35
  || command === "autonomy" || command === "title"
@@ -154,9 +156,12 @@ export function classifyPeerCommand(command: string, args: readonly string[], ca
154
156
  if (conductorOperation(command,args)) return "conductor";
155
157
  if (command === "stop") return "console";
156
158
  if (command === "sdlc" && ["release-guard", "release-guard-hook"].includes(args[0] ?? "")) return "allowed";
157
- // #786, #1063: guarded merge and recording explicitly instructed release consent admit the person or unique configured conductor; the daemon checks the role.
158
- if (command === "sdlc" && ["merge", "authorize-release"].includes(args[0] ?? "")) return "conductor";
159
+ // #786, #1063, #1328: guarded merge, merge adoption and explicitly instructed release consent admit the person or unique configured conductor; the daemon checks the role.
160
+ if (command === "sdlc" && ["merge", "authorize-release", "adopt-merge"].includes(args[0] ?? "")) return "conductor";
159
161
  if (command === "role") return ["list", "show"].includes(args[0] ?? "") ? "allowed" : "console";
162
+ // The original tools identity reaches Tasks for read visibility or task-scoped link admission.
163
+ if (command === "lineage") return ["show", "link"].includes(args[0] ?? "") ? "allowed" : "console";
164
+ if (command === "guidance") return ["create", "list", "show", "withdraw"].includes(args[0] ?? "") ? "allowed" : "console";
160
165
  if (command === "task") {
161
166
  // #933: cancel, label and role act on the caller's own task only; the daemon refuses another peer's task by role (Tasks.cancel, task_catalog_role, task_label_check).
162
167
  if (["propose", "show", "cancel", "label", "role"].includes(args[0] ?? "")) return "allowed";
@@ -196,6 +201,8 @@ export function classifyPeerCommand(command: string, args: readonly string[], ca
196
201
 
197
202
  /** No argument text is included: notices and refusal logs must not copy task text or credentials. */
198
203
  export function cliCommandLabel(command: string, args: readonly string[], catalog?: ProjectAdapterCatalog): string {
204
+ if (command === "lineage") return ["show", "link"].includes(args[0] ?? "") ? `lineage ${args[0]}` : "lineage";
205
+ if (command === "guidance") return ["create", "list", "show", "withdraw"].includes(args[0] ?? "") ? `guidance ${args[0]}` : "guidance";
199
206
  if (command === "model") return ["list", "set", "clear"].includes(args[0] ?? "") ? `model ${args[0]}` : "model";
200
207
  if (command === "peer") return args[0] === "takeover" ? "peer takeover" : "peer";
201
208
  if (command === "backlog") return ["list", "add", "pull", "pull-ready", "split", "return", "plan", "pin", "undo"].includes(args[0] ?? "") ? `backlog ${args[0]}` : "backlog";
@@ -64,6 +64,7 @@ export function shownDefault(id: string): string {
64
64
  : id === "coordination" ? DEFAULT_CONFIG.coordination
65
65
  : id === "specs.enabled" ? DEFAULT_SPECS_CONFIG.enabled
66
66
  : id === "specs.review" ? DEFAULT_SPECS_CONFIG.review
67
+ : id === "sdlc.required_checks" ? "none"
67
68
  : id === "sdlc.mode" ? "off" // no file is written for it: the loader's own default (src/hub/sdlc.ts)
68
69
  : row.id.endsWith(".enabled") ? false // a legacy `<kind>.enabled` switch that the template does not carry reads as off
69
70
  : undefined;
@@ -84,8 +85,11 @@ const oneOf = (id: string, label: string, values: readonly string[], shown: stri
84
85
  export interface InitQuestionContext {
85
86
  /** The agent set `ahub setup` chose on this machine (the default shown for the agents question), or `undefined` for the shipped default. */
86
87
  machineAgents?: readonly string[];
88
+ /** Effective research default for this new project, read from the trusted setup choice (else off). */
89
+ machineResearch?: boolean;
87
90
  /** Project packs a profile answer may name besides the shipped profiles. */
88
91
  packs?: readonly string[];
92
+ discoverChecks?: () => Promise<readonly string[]>;
89
93
  /** Shadow history is offered only for a folder with no Git work tree. */
90
94
  shadowAvailable?: boolean;
91
95
  }
@@ -105,15 +109,17 @@ export function initQuestions(context: InitQuestionContext = {}): InitQuestion[]
105
109
  id: "start.agents", label: "Agents ahub up starts", choices: `${START_AGENTS_ALLOWED.join(",")} as a comma list, or none`, shown: (context.machineAgents ?? START_AGENTS_DEFAULT).join(", ") || "none",
106
110
  read: text => INIT_SETTINGS.find(row => row.id === "start.agents")!.parse(text.trim().toLowerCase()),
107
111
  };
108
- const switches = INIT_SETTINGS.filter(row => row.id.endsWith(".enabled") && !["specs.enabled", "memory.enabled", "snapshots.enabled"].includes(row.id));
112
+ const switches = INIT_SETTINGS.filter(row => row.id.endsWith(".enabled") && !["specs.enabled", "memory.enabled", "research.enabled", "snapshots.enabled"].includes(row.id));
109
113
  const all: InitQuestion[] = [
110
114
  profile,
111
115
  agents,
112
116
  onOff("specs.enabled", "Design specs and their freshness checks", shownDefault("specs.enabled") as "on" | "off"),
113
117
  oneOf("specs.review", "Spec review mode", SPEC_REVIEW_MODES, shownDefault("specs.review")),
114
118
  oneOf("sdlc.mode", "SDLC mode", SDLC_MODES, shownDefault("sdlc.mode")),
119
+ { id: "sdlc.required_checks", label: "Required CI checks", choices: "comma-separated names", shown: "none", read: text => INIT_SETTINGS.find(row => row.id === "sdlc.required_checks")!.parse(text) },
115
120
  oneOf("coordination", "Coordination", COORDINATION_MODES, shownDefault("coordination")),
116
121
  onOff("memory.enabled", "Shared memory", shownDefault("memory.enabled") as "on" | "off"),
122
+ onOff("research.enabled", "Research records", context.machineResearch === true ? "on" : "off"),
117
123
  onOff("snapshots.enabled", "Per-turn snapshots", shownDefault("snapshots.enabled") as "on" | "off"),
118
124
  ...switches.map(row => onOff(row.id, row.describe.charAt(0).toUpperCase() + row.describe.slice(1), shownDefault(row.id) as "on" | "off")),
119
125
  oneOf("autonomy", "Machine autonomy preset", AUTONOMY_CHOICES, "inherit"),
@@ -133,7 +139,14 @@ export const questionLine = (question: InitQuestion): string => `${question.labe
133
139
  export async function runInitPrompt(ports: InitPromptPorts, context: InitQuestionContext, preview: (answers: InitAnswers) => string[]): Promise<InitPromptResult> {
134
140
  const answers: InitAnswers = { request: { values: {} }, shadow: false, releaseGuard: false };
135
141
  ports.print("ahub init: press Enter to keep the default in brackets. N at the end, Ctrl-C or Ctrl-D writes nothing.");
136
- for (const question of initQuestions(context)) {
142
+ for (const original of initQuestions(context)) {
143
+ let question = original;
144
+ if (question.id === "sdlc.required_checks") {
145
+ if (!["advise", "enforce"].includes(String(answers.request.values["sdlc.mode"]))) continue;
146
+ const names = await context.discoverChecks?.() ?? [];
147
+ answers.request.values["sdlc.required_checks"] = [...names];
148
+ question = { ...question, shown: names.join(", ") || "none; supply check names" };
149
+ }
137
150
  let settled = false;
138
151
  for (let attempt = 0; attempt < MAX_TRIES && !settled; attempt++) {
139
152
  const answer = await ports.ask(questionLine(question));
@@ -0,0 +1,122 @@
1
+ import { constants, openSync, fstatSync, readSync, closeSync, readdirSync, lstatSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { githubOriginRepository } from "../hub/task-repository.ts";
4
+ import { requiredChecksFor } from "../hub/sdlc-merge.ts";
5
+ import { hubGitSync } from "../hub/git.ts";
6
+ import { loadSdlc, sdlcGh, type SdlcGh } from "../hub/sdlc.ts";
7
+ import type { InitSettingsRequest } from "./init-settings.ts";
8
+
9
+ const DISCOVERY_DEADLINE_MS = 20_000;
10
+ const DISCOVERY_READ_MS = 5_000;
11
+ const DISCOVERY_BYTES = 512 * 1024;
12
+ const DISCOVERY_JOBS = 100;
13
+ const WORKFLOW_FILES = 32;
14
+ const WORKFLOW_BYTES = 256 * 1024;
15
+
16
+ export interface InitCheckDiscovery { names: string[]; source: "CI" | "workflows" | "unknown"; reason?: string }
17
+ const validNames = (names: unknown[]): names is string[] => names.length > 0 && names.length <= 32 && names.every(name => typeof name === "string" && name.trim() === name && name.length > 0 && name.length <= 120 && !/[\p{Cc}]/u.test(name));
18
+
19
+ /** Literal block-style jobs only. ponytail: expressions, matrices and YAML aliases need an explicit override until a bounded YAML resolver is specified. */
20
+ export function workflowCheckNames(text: string): string[] | undefined {
21
+ const lines = text.split(/\r?\n/), start = lines.findIndex(line => /^jobs:\s*(?:#.*)?$/.test(line));
22
+ if (start < 0) return undefined;
23
+ const names: string[] = [];
24
+ let id: string | undefined, name: string | undefined, dynamic = false;
25
+ const finish = () => { if (id) names.push(name ?? id); };
26
+ for (const line of lines.slice(start + 1)) {
27
+ if (/^[^\s#]/.test(line)) break;
28
+ const job = /^ ([A-Za-z_][A-Za-z0-9_-]*):\s*(?:#.*)?$/.exec(line);
29
+ if (job) { finish(); id = job[1]!; name = undefined; continue; }
30
+ if (!line.trim() || /^\s*#/.test(line)) continue;
31
+ if (/^ \S/.test(line)) { dynamic = true; continue; }
32
+ if (!id) continue;
33
+ if (/^ (?:strategy|uses):/.test(line) || /^ <<:/.test(line)) dynamic = true;
34
+ const named = /^ name:\s*(.*?)\s*$/.exec(line);
35
+ if (named) {
36
+ const raw = named[1]!;
37
+ if (/\$\{|^[>|*&!{\[]/.test(raw)) { dynamic = true; continue; }
38
+ try {
39
+ if (raw.startsWith("'")) {
40
+ const quoted = /^'((?:[^']|'')*)'\s*(?:#.*)?$/.exec(raw);
41
+ if (!quoted) { dynamic = true; continue; }
42
+ name = quoted[1]!.replaceAll("''", "'");
43
+ } else if (raw.startsWith('"')) {
44
+ const quoted = /^("(?:[^"\\]|\\.)*")\s*(?:#.*)?$/.exec(raw);
45
+ if (!quoted) { dynamic = true; continue; }
46
+ name = JSON.parse(quoted[1]!);
47
+ } else name = raw.replace(/\s+#.*$/, "");
48
+ } catch { dynamic = true; }
49
+ }
50
+ }
51
+ finish();
52
+ const unique = [...new Set(names)];
53
+ return !dynamic && validNames(unique) ? unique : undefined;
54
+ }
55
+
56
+ function workflowChecks(cwd: string): InitCheckDiscovery {
57
+ const unknown: InitCheckDiscovery = { names: [], source: "unknown", reason: "CI unavailable or workflows have no complete literal job names; pass --required-checks <a,b,...>" };
58
+ const folder = join(cwd, ".github", "workflows");
59
+ try {
60
+ if (lstatSync(join(cwd, ".github")).isSymbolicLink() || lstatSync(folder).isSymbolicLink()) return unknown;
61
+ const files = readdirSync(folder).filter(file => file.endsWith(".yml")).sort();
62
+ if (!files.length || files.length > WORKFLOW_FILES) return unknown;
63
+ const names: string[] = [];
64
+ for (const file of files) {
65
+ const fd = openSync(join(folder, file), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
66
+ try {
67
+ const stat = fstatSync(fd);
68
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size > WORKFLOW_BYTES) return unknown;
69
+ const bytes = Buffer.alloc(WORKFLOW_BYTES + 1);
70
+ let length = 0, count = 0;
71
+ while ((count = readSync(fd, bytes, length, bytes.length - length, null)) > 0) { length += count; if (length > WORKFLOW_BYTES) return unknown; }
72
+ const after = fstatSync(fd);
73
+ if (stat.size !== after.size || stat.mtimeMs !== after.mtimeMs || length !== after.size) return unknown;
74
+ const text = bytes.subarray(0, length).toString("utf8");
75
+ const found = workflowCheckNames(text);
76
+ if (!found) return unknown;
77
+ names.push(...found);
78
+ } finally { closeSync(fd); }
79
+ }
80
+ const unique = [...new Set(names)];
81
+ return validNames(unique) ? { names: unique, source: "workflows" } : unknown;
82
+ } catch { return unknown; }
83
+ }
84
+
85
+ /** At most three capped reads under one deadline; any incomplete evidence falls back to bounded local workflow data. No shell or YAML execution. */
86
+ export async function discoverInitChecks(cwd: string, run: SdlcGh = sdlcGh): Promise<InitCheckDiscovery> {
87
+ const deadline = performance.now() + DISCOVERY_DEADLINE_MS;
88
+ try {
89
+ const repo = githubOriginRepository(cwd);
90
+ if (!repo) return workflowChecks(cwd);
91
+ const read = async (args: string[]) => {
92
+ const remaining = deadline - performance.now();
93
+ if (remaining <= 0) throw new Error("discovery deadline");
94
+ const reply = await run(args, Math.min(DISCOVERY_READ_MS, remaining), cwd, DISCOVERY_BYTES);
95
+ if (reply.code !== 0 || Buffer.byteLength(reply.stdout) >= DISCOVERY_BYTES || performance.now() >= deadline) throw new Error("discovery unavailable");
96
+ return JSON.parse(reply.stdout);
97
+ };
98
+ const local = hubGitSync(["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"], { cwd, encoding: "utf8", timeout: DISCOVERY_READ_MS });
99
+ const remaining = deadline - performance.now();
100
+ const target = local.status === 0 && remaining > 0 ? hubGitSync(["rev-parse", "--verify", "refs/remotes/origin/HEAD^{commit}"], { cwd, encoding: "utf8", timeout: Math.min(DISCOVERY_READ_MS, remaining) }) : undefined;
101
+ let branch = local.status === 0 && target?.status === 0 ? local.stdout.trim().replace(/^refs\/remotes\/origin\//, "") : undefined;
102
+ if (!branch) branch = (await read(["api", `repos/${repo}`])).default_branch;
103
+ if (typeof branch !== "string" || !branch || /[\r\n]/.test(branch)) return workflowChecks(cwd);
104
+ const runs = await read(["api", "--method", "GET", `repos/${repo}/actions/runs`, "-f", `branch=${branch}`, "-f", "status=completed", "-f", "per_page=1"]);
105
+ const latest = runs.workflow_runs?.[0];
106
+ if (!Number.isSafeInteger(latest?.id) || latest.id <= 0 || latest.status !== "completed" || latest.head_branch !== branch) return workflowChecks(cwd);
107
+ const body = await read(["api", "--method", "GET", `repos/${repo}/actions/runs/${latest.id}/jobs`, "-f", `per_page=${DISCOVERY_JOBS}`]);
108
+ const jobs = body.jobs;
109
+ if (!Array.isArray(jobs) || body.total_count !== jobs.length || jobs.length >= DISCOVERY_JOBS) return workflowChecks(cwd);
110
+ const names: unknown[] = [...new Set(jobs.map(job => job?.name))];
111
+ return validNames(names) ? { names, source: "CI" } : workflowChecks(cwd);
112
+ } catch { return workflowChecks(cwd); }
113
+ }
114
+
115
+ /** The CLI resolves discovery before preview or write; an override never contacts GitHub. */
116
+ export async function withInitChecks(cwd: string, request: InitSettingsRequest, discover = discoverInitChecks): Promise<InitSettingsRequest> {
117
+ if (!["advise", "enforce"].includes(String(request.values["sdlc.mode"])) || Object.hasOwn(request.values, "sdlc.required_checks")) return request;
118
+ if (requiredChecksFor(loadSdlc(cwd), githubOriginRepository(cwd)).length) return request;
119
+ const result = await discover(cwd);
120
+ if (!result.names.length && request.values["sdlc.mode"] === "enforce") throw new Error(`enforce needs required CI checks: ${result.reason}; nothing was written`);
121
+ return { ...request, values: { ...request.values, "sdlc.required_checks": result.names } };
122
+ }