@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
@@ -48,8 +48,14 @@ export const INIT_SETTINGS: readonly InitSettingDef[] = [
48
48
  catch (error) { throw new Error(`${(error as Error).message}; allowed: ${START_AGENTS_ALLOWED.join(", ")} or none; nothing was written`); }
49
49
  } },
50
50
  { id: "sdlc.mode", flags: [{ flag: "--sdlc" }], file: "sdlc.toml", path: ["mode"], allowed: SDLC_MODES.join("|"), describe: "SDLC mode", parse: choice("sdlc.mode", "--sdlc", SDLC_MODES) },
51
+ { id: "sdlc.required_checks", flags: [{ flag: "--required-checks" }], file: "sdlc.toml", path: ["required_checks"], allowed: "comma-separated check names", describe: "required CI checks", parse: text => {
52
+ const names = text.split(",").map(name => name.trim());
53
+ if (!names.length || names.some(name => !name || name.length > 120 || /[\p{Cc}]/u.test(name)) || new Set(names).size !== names.length || names.length > 32) throw new Error("--required-checks needs 1 to 32 distinct check names, each at most 120 characters; nothing was written");
54
+ return names;
55
+ } },
51
56
  { id: "coordination", flags: [{ flag: "--coordination" }], file: "config.json", path: ["coordination"], allowed: COORDINATION_MODES.join("|"), describe: "coordination mode", parse: choice("coordination", "--coordination", COORDINATION_MODES) },
52
57
  { id: "memory.enabled", flags: [{ flag: "--memory", value: true }, { flag: "--no-memory", value: false }], file: "config.json", path: ["memory", "enabled"], allowed: "on|off", describe: "shared memory", parse: () => { throw new Error("unreachable"); } },
58
+ { id: "research.enabled", flags: [{ flag: "--research", value: true }, { flag: "--no-research", value: false }], file: "config.local.json", path: ["research", "enabled"], allowed: "on|off", describe: "research records", parse: () => { throw new Error("unreachable"); } },
53
59
  { id: "snapshots.enabled", flags: [{ flag: "--snapshots", value: true }, { flag: "--no-snapshots", value: false }], file: "config.json", path: ["snapshots", "enabled"], allowed: "on|off", describe: "per-turn snapshots", parse: () => { throw new Error("unreachable"); } },
54
60
  // #1064 T3: the design-specs feature. `--no-specs` also removes the AGENT_HUB_SPECS block from AGENTS.md and `--specs` restores it (init.ts reads the planned `specs.enabled`); the key is shared, so a team commits the choice.
55
61
  { id: "specs.enabled", flags: [{ flag: "--specs", value: true }, { flag: "--no-specs", value: false }], file: "config.json", path: ["specs", "enabled"], allowed: "on|off", describe: "design specs and their freshness checks", parse: () => { throw new Error("unreachable"); } },
@@ -70,7 +76,7 @@ export interface InitSettingsRequest {
70
76
  }
71
77
 
72
78
  /** The usage line `ahub init` prints for a bad argument; help.ts shows the same flags. */
73
- export const INIT_USAGE = "usage: 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]";
79
+ export const INIT_USAGE = "usage: 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]";
74
80
 
75
81
  /** Every flag the table and the two non-key choices own, for the caller's own argument loop and for help. */
76
82
  export const INIT_SETTING_FLAGS: readonly string[] = [...INIT_SETTINGS.flatMap(row => row.flags.map(flag => flag.flag)), "--autonomy"];
@@ -207,13 +213,13 @@ export function planInitSettings(request: InitSettingsRequest, texts: InitSettin
207
213
  if (!Object.hasOwn(request.values, row.id)) continue;
208
214
  const to = request.values[row.id];
209
215
  if (row.file === "sdlc.toml") {
210
- let from: unknown = "off";
216
+ let from: unknown = row.id === "sdlc.mode" ? "off" : [];
211
217
  if (texts["sdlc.toml"] !== null) {
212
- try { const mode = (Bun.TOML.parse(texts["sdlc.toml"]) as Record<string, unknown>).mode; if (mode !== undefined) from = mode; }
218
+ try { const held = (Bun.TOML.parse(texts["sdlc.toml"]) as Record<string, unknown>)[row.path[0]!]; if (held !== undefined) from = held; }
213
219
  catch { throw new Error(".agenthub/sdlc.toml is not valid TOML; fix it in your editor, then run ahub init again; nothing was written"); }
214
220
  }
215
221
  if (same(from, to)) continue; // off with no file is the shipped state: no file is written for it
216
- const text = editSdlcText(next["sdlc.toml"] ?? texts["sdlc.toml"], [{ path: ["mode"], value: to }]);
222
+ const text = editSdlcText(next["sdlc.toml"] ?? texts["sdlc.toml"], [{ path: [...row.path], value: to }]);
217
223
  if (text !== null) next["sdlc.toml"] = text;
218
224
  rows.push({ key: row.id, file: "sdlc.toml", from, to });
219
225
  continue;
package/src/cli/init.ts CHANGED
@@ -12,7 +12,9 @@ import { hubGitArgv, hubGitEnv, hubGitSync } from "../hub/git.ts";
12
12
  import { KIMI_MCP_FILE } from "./kimi-mcp.ts";
13
13
  import { AGY_PLUGIN_FILES } from "./agy-mcp.ts";
14
14
  import { loadConfig } from "../hub/daemon.ts";
15
- import { sdlcConfig } from "../hub/sdlc.ts";
15
+ import { requiredChecksFor } from "../hub/sdlc-merge.ts";
16
+ import { githubOriginRepository } from "../hub/task-repository.ts";
17
+ import { loadSdlc, sdlcConfig } from "../hub/sdlc.ts";
16
18
  import { VERSION } from "../version.ts";
17
19
  import { planInitSettings, type InitSettingFile, type InitSettingRow, type InitSettingsRequest } from "./init-settings.ts";
18
20
 
@@ -249,7 +251,7 @@ function changes(cwd: string, requestedName?: string, shadow = false, releaseGua
249
251
  for (const name of Object.keys(result.next) as InitSettingFile[]) {
250
252
  const path = files[name], text = result.next[name]!;
251
253
  const row = changed.find(entry => entry.path === path);
252
- const reason = `set ${result.rows.filter(entry => entry.file === name).map(entry => entry.key).join(", ")} from the init flags`;
254
+ const reason = `set ${result.rows.filter(entry => entry.file === name).map(entry => entry.key).join(", ")} from the init settings`;
253
255
  if (row) { row.next = text; row.reason = `${row.reason}; ${reason}`; }
254
256
  else changed.push({ action: existsSync(path) ? "modify" : "create", path, next: text, reason, ...(name === "config.local.json" ? { privateFile: true as const } : {}) });
255
257
  }
@@ -273,7 +275,10 @@ function checkCandidate(cwd: string, plan: readonly PlannedWrite[]): void {
273
275
  catch (error) { throw new Error(`the resulting .agenthub config does not pass the hub's config check: ${(error as Error).message}; fix that key in your editor, then run ahub init again; nothing was written`); }
274
276
  }
275
277
  if (sdlc !== undefined) {
276
- try { sdlcConfig(Bun.TOML.parse(sdlc), VERSION); }
278
+ try {
279
+ const lifecycle = sdlcConfig(Bun.TOML.parse(sdlc), VERSION);
280
+ if (lifecycle.mode === "enforce" && !requiredChecksFor(lifecycle, githubOriginRepository(cwd)).length) throw new Error("enforce needs required CI checks; pass --required-checks <a,b,...>");
281
+ }
277
282
  catch (error) { throw new Error(`the resulting .agenthub/sdlc.toml does not pass the hub's check: ${(error as Error).message}; fix it in your editor, then run ahub init again; nothing was written`); }
278
283
  }
279
284
  }
@@ -296,6 +301,37 @@ export function planInit(cwd: string, profile?: string, shadow = false, releaseG
296
301
  export function initSettingRows(cwd: string, profile?: string, shadow = false, releaseGuard = false, settings?: InitSettingsRequest): InitSettingRow[] {
297
302
  return changes(cwd, profile, shadow, releaseGuard, settings).settingRows;
298
303
  }
304
+ /** A pre-existing local project choice wins; missing or unreadable machine defaults are off. Validation still runs before any write. */
305
+ export function initResearchDefault(cwd: string, machineValue: boolean | undefined): boolean {
306
+ const local = join(cwd, ".agenthub", "config.local.json");
307
+ try {
308
+ if (existsSync(local)) {
309
+ const value = JSON.parse(readFileSync(local, "utf8"))?.research?.enabled;
310
+ if (typeof value === "boolean") return value;
311
+ }
312
+ } catch { /* the init candidate validation reports malformed local files before writes */ }
313
+ return machineValue === true;
314
+ }
315
+ /** Add only a new project's effective on default to the normal plan. Off is the shipped default; explicit flags always win. Never writes machine defaults. */
316
+ export function withInitResearch(cwd: string, request: InitSettingsRequest, machineValue: boolean | undefined): InitSettingsRequest {
317
+ if (existsSync(join(cwd, ".agenthub", "config.json")) || Object.hasOwn(request.values, "research.enabled") || !initResearchDefault(cwd, machineValue)) return request;
318
+ return { ...request, values: { ...request.values, "research.enabled": true } };
319
+ }
320
+ /** Prepare person guidance before writes; the CLI prints it only after successful apply. Creates no lifecycle evidence or acceptance. */
321
+ export function initNextSteps(cwd: string, settings?: InitSettingsRequest): string[] {
322
+ const lines = [
323
+ "Next steps:",
324
+ "- Review and commit AGENTS.md, .agenthub/config.json and other shared init changes; keep config.local.json untracked.",
325
+ "- Start with ahub up or ahub claude; sessions started otherwise miss hub pushes.",
326
+ ];
327
+ const mode = settings?.values["sdlc.mode"] ?? loadSdlc(cwd, VERSION).mode;
328
+ if (mode !== "off") lines.push(
329
+ `- SDLC ${mode}: accept the planner-recorded spec with ahub sdlc accept <task> --issue <n>.`,
330
+ "- When a plan departure needs your consent: ahub sdlc accept-departure <task> <head> <reason...>.",
331
+ "- After hub_task_done on the open PR, reviewer approval and green exact-head CI, use guarded merge: ahub sdlc merge <task>.",
332
+ );
333
+ return lines;
334
+ }
299
335
  /** Returns the paths it changed, applying the same plan as the preview. */
300
336
  export function init(cwd: string, profile?: string, shadow = false, releaseGuard = false, settings?: InitSettingsRequest): string[] {
301
337
  const plan = changes(cwd, profile, shadow, releaseGuard, settings).writes;
@@ -53,11 +53,16 @@ export function stableBunRuntime(options: { runtime?: string; pathRuntime?: stri
53
53
  return candidate && lexicalTarget(candidate) && samePath(candidate, runtime) ? candidate : runtime;
54
54
  }
55
55
 
56
+ /** The package root of the `ahub` on PATH, when it is a proven CLI entry (#1385). */
57
+ export function globalCliRoot(env: NodeJS.ProcessEnv = process.env): string | undefined {
58
+ const invocation = Bun.which("ahub", { PATH: env.PATH ?? "" });
59
+ return invocation ? pathPackageRoot(invocation) : undefined;
60
+ }
61
+
56
62
  /** Advice only; a staged daemon upgrade does not update the person's global CLI installation. */
57
63
  export function globalCliUpdateStep(version?: string, options: InstallPathOptions = {}): string {
58
64
  const env = options.env ?? process.env;
59
- const invocation = Bun.which("ahub", { PATH: env.PATH ?? "" });
60
- const root = invocation ? pathPackageRoot(invocation) : undefined;
65
+ const root = globalCliRoot(env);
61
66
  const generic = `update the global CLI${version ? ` to ${version}` : ""} the way it was installed`;
62
67
  if (!root) return generic;
63
68
  const global = join(env.BUN_INSTALL || join(options.home ?? homedir(), ".bun"), "install/global/node_modules");
@@ -0,0 +1,78 @@
1
+ import { executionReferenceKey, executionText, parseExecutionReference, type ExecutionReferenceV1 } from "../hub/execution-reference.ts";
2
+ import { LINEAGE_LIMITS, type LineageResult } from "../hub/execution-lineage.ts";
3
+ import { executionLineageLines } from "../ui/lineage-view.ts";
4
+ import { terminalText } from "./console-state.ts";
5
+
6
+ export const LINEAGE_USAGE = "usage: 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] | link --task N --task-created MS --revision N --ref JSON [--from JSON] [--json]";
7
+ type Show = { op: "show"; json: boolean; taskId?: number; attemptId?: string; root?: ExecutionReferenceV1; task?: { id: number; created: number }; cursor?: string; nodes?: number; edges?: number; bytes?: number };
8
+ type Link = { op: "link"; json: boolean; taskId: number; taskCreated: number; flowRevision: number; reference: ExecutionReferenceV1; from?: ExecutionReferenceV1 };
9
+ const invalid = (): never => { throw new Error(`invalid lineage arguments; ${LINEAGE_USAGE}`); };
10
+ const integer = (raw: string | undefined, minimum: number, maximum = Number.MAX_SAFE_INTEGER): number => {
11
+ if (raw === undefined || !/^(0|[1-9][0-9]*)$/.test(raw)) return invalid();
12
+ const value = Number(raw);
13
+ if (!Number.isSafeInteger(value) || value < minimum || value > maximum) return invalid();
14
+ return value;
15
+ };
16
+ function reference(raw: string | undefined): ExecutionReferenceV1 {
17
+ if (raw === undefined || Buffer.byteLength(raw) > 8192) return invalid();
18
+ try { return parseExecutionReference(JSON.parse(raw)); } catch { return invalid(); }
19
+ }
20
+ /** Shortcuts remain selectors: only the source host can supply their project identity. */
21
+ export function parseLineageCommand(args: readonly string[]): Show | Link {
22
+ const [op, ...rest] = args;
23
+ if (op !== "show" && op !== "link") return invalid();
24
+ const values = new Map<string, string>(); let json = false;
25
+ const allowed = op === "show"
26
+ ? ["--task", "--attempt", "--root", "--task-scope", "--task-created", "--cursor", "--nodes", "--edges", "--bytes"]
27
+ : ["--task", "--task-created", "--revision", "--ref", "--from"];
28
+ for (let i = 0; i < rest.length; i++) {
29
+ const flag = rest[i]!;
30
+ if (flag === "--json") { if (json) return invalid(); json = true; continue; }
31
+ if (!allowed.includes(flag) || values.has(flag)) return invalid();
32
+ const value = rest[++i]; if (value === undefined || value.startsWith("--")) return invalid();
33
+ values.set(flag, value);
34
+ }
35
+ if (op === "link") return { op, json, taskId: integer(values.get("--task"), 1), taskCreated: integer(values.get("--task-created"), 0),
36
+ flowRevision: integer(values.get("--revision"), 0), reference: reference(values.get("--ref")),
37
+ ...(values.has("--from") ? { from: reference(values.get("--from")) } : {}) };
38
+ if (["--task", "--attempt", "--root"].filter(key => values.has(key)).length !== 1) return invalid();
39
+ const result: Show = { op, json };
40
+ if (values.has("--task")) result.taskId = integer(values.get("--task"), 1);
41
+ if (values.has("--attempt")) {
42
+ const attemptId = values.get("--attempt")!;
43
+ if (!/^ra-[0-9a-f]{12}$/.test(attemptId)) return invalid();
44
+ result.attemptId = attemptId;
45
+ }
46
+ if (values.has("--root")) result.root = reference(values.get("--root"));
47
+ if (values.has("--task-scope") || values.has("--task-created")) {
48
+ if (!result.root) return invalid();
49
+ result.task = { id: integer(values.get("--task-scope"), 1), created: integer(values.get("--task-created"), 0) };
50
+ }
51
+ if (values.has("--cursor")) {
52
+ const cursor = values.get("--cursor")!;
53
+ if (cursor.length > LINEAGE_LIMITS.cursor || !/^[A-Za-z0-9_-]+$/.test(cursor)) return invalid();
54
+ result.cursor = cursor;
55
+ }
56
+ if (values.has("--nodes")) result.nodes = integer(values.get("--nodes"), 1, LINEAGE_LIMITS.nodes);
57
+ if (values.has("--edges")) result.edges = integer(values.get("--edges"), 1, LINEAGE_LIMITS.edges);
58
+ if (values.has("--bytes")) result.bytes = integer(values.get("--bytes"), LINEAGE_LIMITS.minimumBytes, LINEAGE_LIMITS.bytes);
59
+ return result;
60
+ }
61
+
62
+ /** The closed shape check lives in the hub module, beside the reader that produces it, so the console reads it identically (#1220 T3). */
63
+ export { parseLineageResult as validateLineageReply } from "../hub/execution-lineage.ts";
64
+ export interface LineageLinkReceipt { id: string; taskId: number; reference: ExecutionReferenceV1; strength: "declared"; already: boolean }
65
+ export function validateLineageLink(value: unknown, command: { taskId: number; reference: ExecutionReferenceV1 }): LineageLinkReceipt {
66
+ const bad = (): never => { throw new Error("lineage link reply is unconfirmed; inspect ahub lineage show before retrying the link"); };
67
+ try {
68
+ if (!value || typeof value !== "object" || Array.isArray(value) || Buffer.byteLength(JSON.stringify(value)) > 8192) return bad();
69
+ const row = value as Record<string, unknown>, keys = ["id", "taskId", "reference", "strength", "already"];
70
+ if (Object.keys(row).length !== keys.length || !keys.every(key => Object.hasOwn(row, key)) || !executionText(row.id, 256) ||
71
+ row.taskId !== command.taskId || row.strength !== "declared" || typeof row.already !== "boolean" ||
72
+ executionReferenceKey(parseExecutionReference(row.reference)) !== executionReferenceKey(command.reference)) return bad();
73
+ return value as LineageLinkReceipt;
74
+ } catch { return bad(); }
75
+ }
76
+ /** The CLI is a terminal: the shared view crosses `terminalText` here, at this surface's own boundary. */
77
+ export const renderExecutionLineage = (result: LineageResult): string[] =>
78
+ executionLineageLines(result).map(line => terminalText(line).replace(/[\r\n]+/g, " "));
package/src/cli/main.ts CHANGED
@@ -46,6 +46,7 @@ import { autonomyHomeStatus, usedClaudeHomes } from "./autonomy-homes.ts";
46
46
  import { shellQuote } from "./shell-quote.ts";
47
47
  import { discoverClaudeHomes } from "./claude-homes.ts";
48
48
  import { setupClaudeHomes } from "./setup-homes.ts";
49
+ import { setupResearchDefault } from "./setup-research.ts";
49
50
  import { registerAconPlugin } from "./acon-register.ts";
50
51
  import { petView, readPet, renderPet } from "./pet.ts";
51
52
  import { PET_WINDOW_RETIRED_NOTICE, petPalette } from "../pet/config.ts";
@@ -76,7 +77,8 @@ import { inspectProject, startProject, stopProject, runProjectDaemon } from "../
76
77
  import { processLiveness, processSignature } from "../pi/process-signature.ts";
77
78
  import { openManager, startManager, stopManager } from "../hub/manager.ts";
78
79
  import { OmniRoute } from "../omniroute/client.ts";
79
- import { autonomyInheritanceChange, init, initSettingRows, planInit } from "./init.ts";
80
+ import { autonomyInheritanceChange, init, initNextSteps, initResearchDefault, withInitResearch, initSettingRows, planInit } from "./init.ts";
81
+ import { discoverInitChecks, withInitChecks } from "./init-required-checks.ts";
80
82
  import { INIT_USAGE, parseInitSettings } from "./init-settings.ts";
81
83
  import { promptGate, runInitPrompt, settingLines, shadowOffered, type InitAnswers } from "./init-prompt.ts";
82
84
  import { loadPacks } from "../hub/packs.ts";
@@ -127,6 +129,7 @@ import { COMPLETION_SHELLS, completionScript } from "./completion.ts";
127
129
  import { agentShellCause, classifyPeerCommand, cliCommandLabel, detectCliIdentity, LIVE_TEST_PERSON_REFUSAL, liveTestRefusal, peerCommandRefusal } from "./identity.ts";
128
130
  import { recordCliAudit, recordDelegatedCliAudit } from "./identity-audit.ts";
129
131
  import { runConsole } from "./console.ts";
132
+ import { installedVersions } from "./console-versions.ts";
130
133
  import { paint, permissionBoundary, resolveColor, wrap, type Span } from "./console-state.ts";
131
134
  import { outputWidth, renderRuntimeModels, renderRoster, renderStatus, renderBoard, renderBacklog, renderBoardColumns, boardColumnModel, renderBudget, renderDoctor, renderProjects, renderQueue, renderTurns, renderOrphans, renderOrphanCleanup, renderQueueShow, renderModelsStatus, renderExecutionBudgetStatus, renderReport, renderUsage, renderLimits, renderTotal, type DoctorCheck } from "./output.ts";
132
135
  import { renderHelp, configuredAcpHelp } from "./help.ts";
@@ -246,12 +249,14 @@ const requireNamedPeerFeature = (hub: ControlClient, peer: string | undefined) =
246
249
  const projectConfig = () => {
247
250
  const config = loadConfig(cwd);
248
251
  for (const line of config.ignored ?? []) console.error(`note: ${line}; only a config file nobody committed may set it`);
252
+ for (const line of config.releasePolicyNotices ?? []) console.error(`note: ${line}`);
249
253
  return config;
250
254
  };
251
255
  const stateDir = selected.stateDir;
252
256
  var operationalAuditReady=false, operationalRefusalRecorded=false;
253
257
  const caller = declaredInstances ? detectCliIdentity(process.env, declaredInstances) : unboundCaller;
254
- const commandLabel = cliCommandLabel(cmd, args, projectCatalog);
258
+ const commandLabel = cmd === "guidance" && args[0] === "probe" && ["register", "start", "show", "cancel"].includes(args[1] ?? "")
259
+ ? `guidance probe ${args[1]}` : cliCommandLabel(cmd, args, projectCatalog);
255
260
  let commandAccess = classifyPeerCommand(cmd, args, projectCatalog);
256
261
  const continuationPeer = process.env.AGENTHUB_RECOVERY_CONDUCTOR;
257
262
  const continuationId = process.env.AGENTHUB_RECOVERY_OPERATION;
@@ -273,7 +278,10 @@ if (continuationPeer !== undefined) {
273
278
  }
274
279
  const conductorPeer = !liveTest && caller.role === "tools" && (recoveryRunnerContinuation || ["restart", "upgrade", "recovery"].includes(cmd) && commandAccess === "conductor") ? caller.peer : undefined;
275
280
  // Agent-authored content keeps its peer. Operational starts/holds may borrow console authority for live verification.
276
- const delegationRefused = liveTest && caller.role === "tools" && commandAccess !== "allowed" && liveTestRefusal(cmd, args);
281
+ const guidanceProbeDelegationRefused = liveTest && caller.role === "tools" && cmd === "guidance"
282
+ && args[0] === "probe" && ["register", "start", "show", "cancel"].includes(args[1] ?? "");
283
+ const delegationRefused = liveTest && caller.role === "tools" && commandAccess !== "allowed"
284
+ && (liveTestRefusal(cmd, args) || guidanceProbeDelegationRefused);
277
285
  const delegatedPeer = liveTest && caller.role === "tools" && commandAccess !== "allowed" && !delegationRefused ? caller.peer : undefined;
278
286
  const identity = delegatedPeer || recoveryLauncher ? { role: "console" as const } : caller;
279
287
  operationalAuditReady=identity.role==="tools" && commandAccess==="conductor" && conductorOperation(cmd,args)!==undefined;
@@ -870,6 +878,8 @@ const LOCAL_OPERATION_ARGS: Record<string, () => void> = {
870
878
  "source add": () => { const operands = args.filter(arg => arg !== "--json" && arg !== "--full" && !arg.startsWith("--color=")); if (operands[0] !== "add" || operands.length !== 2 || !operands[1]) fail(SOURCE_USAGE); },
871
879
  };
872
880
 
881
+ // Outside the command bodies: test/lifecycle-starting-1232.test.ts runs the `up` body as a plain function, where import.meta does not parse.
882
+ const consoleInstalled = () => installedVersions(join(import.meta.dir, "..", ".."));
873
883
  const commands: Record<string, () => Promise<void> | void> = {
874
884
  upgrade: () => upgrade("upgrade"),
875
885
  restart: () => upgrade("restart"),
@@ -1065,9 +1075,13 @@ const commands: Record<string, () => Promise<void> | void> = {
1065
1075
  recoveryLauncherCurrent?.();
1066
1076
  assertLifecycleAvailable(cwd);
1067
1077
  const root = join(import.meta.dir, "..", "..");
1068
- const setupFlags = takeFlags(args.filter(arg => arg !== "--yes"), ["--agents"], []);
1069
- if (setupFlags.rest.length) fail("usage: ahub setup [--yes] [--agents <a,b>]");
1078
+ if (args.includes("--research") && args.includes("--no-research")) fail("--research conflicts with --no-research; give one; nothing was written");
1079
+ const research = args.includes("--research") ? true : args.includes("--no-research") ? false : undefined;
1080
+ const setupFlags = takeFlags(args.filter(arg => !["--yes", "--research", "--no-research"].includes(arg)), ["--agents"], []);
1081
+ if (setupFlags.rest.length) fail("usage: ahub setup [--yes] [--agents <a,b>] [--research|--no-research]");
1082
+ if (research !== undefined && (liveTest || delegatedPeer || recoveryLauncherCurrent)) fail("the machine research default requires the person's own ahub setup; nothing was written");
1070
1083
  const registry = new Registry(), rl = process.stdin.isTTY ? createInterface({ input: process.stdin, output: process.stdout }) : undefined;
1084
+ let machineRoots = [cwd];
1071
1085
  let homesFailed = false, homesFailure: unknown;
1072
1086
  try {
1073
1087
  const found = recoveryLauncherCurrent || delegatedPeer ? await discoverClaudeHomes({ home: homedir(), env: process.env }) : await usedClaudeHomes(registry, homedir(), process.env);
@@ -1088,8 +1102,11 @@ const commands: Record<string, () => Promise<void> | void> = {
1088
1102
  ...(rl ? { ask: async (prompt: string) => { try { return await rl.question(prompt); } catch { return null; } } } : {}), print: line => console.log(terminalText(line)) });
1089
1103
  if (refused) fail(refused);
1090
1104
  }
1105
+ if (research !== undefined) machineRoots = [...registry.list().map(row => row.root), cwd];
1091
1106
  } finally { registry.close(); rl?.close(); }
1092
1107
  if (homesFailed) fail(startupDiagnostic(homesFailure));
1108
+ try { if (research !== undefined) assertLifecycleAvailable(cwd); const line = setupResearchDefault(hubHome(), machineRoots, research); if (line) console.log(terminalText(line)); }
1109
+ catch (error) { return fail((error as Error).message); }
1093
1110
  // #935: register the acon console plugin (acon reads it at its next start; no acon install is needed for this).
1094
1111
  const acon = registerAconPlugin(hubHome(), join(root, "src", "ui", "plugin.ts"));
1095
1112
  console.log("error" in acon ? `acon plugin not registered: ${acon.error}` : acon.changed ? `acon plugin registered: ${acon.path}` : `acon plugin up to date: ${acon.path}`);
@@ -1106,6 +1123,7 @@ const commands: Record<string, () => Promise<void> | void> = {
1106
1123
  // A pack is a project file in .agenthub/roles/<name>.pack.json (#513a); init resolves the name and refuses an unknown one with the profiles and packs it knows.
1107
1124
  let requestedProfile = flags.one["--profile"];
1108
1125
  const newProject = !existsSync(join(cwd, ".agenthub/config.json"));
1126
+ const initMachine = newProject ? readAutonomyDefaults(hubHome(), [cwd]) : undefined;
1109
1127
  let request = settings.request, asked = Object.keys(request.values).length > 0;
1110
1128
  let shadow = args.includes("--shadow"), releaseGuard = args.includes("--release-guard");
1111
1129
  // #1065 T2: a person at a terminal on a new project, with no flag that sets anything and no --yes, is asked each setting (init-prompt.ts). Every other run, including a delegated peer, a live test and any run
@@ -1118,8 +1136,9 @@ const commands: Record<string, () => Promise<void> | void> = {
1118
1136
  const ask = (question: string): Promise<string | null> => Promise.race([rl.question(question).catch(() => null), interrupted]);
1119
1137
  const machine = readAutonomyDefaults(hubHome(), [cwd]);
1120
1138
  const preview = (answers: InitAnswers): string[] => {
1121
- const rows = initSettingRows(cwd, answers.profile, answers.shadow, answers.releaseGuard, answers.request);
1122
- const plan = planInit(cwd, answers.profile, answers.shadow, answers.releaseGuard, answers.request);
1139
+ const planned = withInitResearch(cwd, answers.request, initMachine?.researchEnabled);
1140
+ const rows = initSettingRows(cwd, answers.profile, answers.shadow, answers.releaseGuard, planned);
1141
+ const plan = planInit(cwd, answers.profile, answers.shadow, answers.releaseGuard, planned);
1123
1142
  // The same autonomy-inheritance row `--dry-run` shows, from the one helper: a new project inherits the trusted machine preset after the writes unless the answer was off.
1124
1143
  const inherit = autonomyInheritanceChange(cwd, machine.enabled, answers.request.autonomy);
1125
1144
  if (inherit) plan.push(inherit);
@@ -1128,11 +1147,13 @@ const commands: Record<string, () => Promise<void> | void> = {
1128
1147
  let result: Awaited<ReturnType<typeof runInitPrompt>>;
1129
1148
  try {
1130
1149
  result = await runInitPrompt({ ask, print: line => console.log(terminalText(line)) },
1131
- { ...(machine.startAgents ? { machineAgents: machine.startAgents } : {}), packs: [...loadPacks(cwd).packs.keys()], shadowAvailable: shadowOffered(repoOf(cwd)) }, preview);
1150
+ { ...(machine.startAgents ? { machineAgents: machine.startAgents } : {}), machineResearch: initResearchDefault(cwd, initMachine?.researchEnabled), packs: [...loadPacks(cwd).packs.keys()], discoverChecks: async () => (await discoverInitChecks(cwd)).names, shadowAvailable: shadowOffered(repoOf(cwd)) }, preview);
1132
1151
  } finally { rl.close(); }
1133
1152
  if (!result.ok) { console.error(`ahub init: ${result.reason === "refused" ? result.message : result.reason === "interrupted" ? `interrupted; ${result.message}` : result.message}`); process.exitCode = result.reason === "refused" ? 1 : 0; return; }
1134
1153
  requestedProfile = result.answers.profile; request = result.answers.request; asked = Object.keys(request.values).length > 0; shadow = result.answers.shadow; releaseGuard = result.answers.releaseGuard;
1135
1154
  }
1155
+ request = withInitResearch(cwd, request, initMachine?.researchEnabled);
1156
+ try { request = await withInitChecks(cwd, request); } catch (error) { return fail((error as Error).message); }
1136
1157
  // `--autonomy off` skips the machine inheritance on a new project; `inherit` is today's behaviour. Neither changes an existing project.
1137
1158
  const inheritAutonomy = newProject && request.autonomy !== "off";
1138
1159
  if (!newProject && request.autonomy !== undefined) console.error("note: --autonomy applies to a new project only; this project already exists, so its autonomy settings are unchanged");
@@ -1150,8 +1171,8 @@ const commands: Record<string, () => Promise<void> | void> = {
1150
1171
  }
1151
1172
  assertLifecycleAvailable(cwd);
1152
1173
  if (inheritAutonomy && delegatedPeer && readAutonomyDefaults(hubHome(), [cwd]).enabled) fail("machine autonomy inheritance is person-only; delegated live tests cannot apply it (ahub init --autonomy off skips it)");
1153
- let changed: string[];
1154
- try { changed = init(cwd, requestedProfile, shadow, releaseGuard, request); } catch (error) { return fail((error as Error).message); }
1174
+ let changed: string[], nextSteps: string[];
1175
+ try { nextSteps = initNextSteps(cwd, request); changed = init(cwd, requestedProfile, shadow, releaseGuard, request); } catch (error) { return fail((error as Error).message); }
1155
1176
  const project = registeredProject();
1156
1177
  console.log(changed.length ? changed.map((p) => `${existsSync(p) ? "wrote" : "removed"} ${p}`).join("\n") : "already up to date");
1157
1178
  if (newProject) {
@@ -1165,6 +1186,7 @@ const commands: Record<string, () => Promise<void> | void> = {
1165
1186
  }
1166
1187
  const config = projectConfig(), examples = resolveProfile(config.profile, config.profile_overrides).example_checks;
1167
1188
  if (examples.length) console.log(terminalText("Example checks (advisory):\n" + examples.map(example => "- " + example).join("\n")));
1189
+ console.log(nextSteps.join("\n"));
1168
1190
  },
1169
1191
 
1170
1192
  // Internal: the detached daemon process started by ahub up or the manager.
@@ -1178,7 +1200,7 @@ const commands: Record<string, () => Promise<void> | void> = {
1178
1200
  if (args.some(arg => arg !== "--panels" && arg !== "--no-pet" && !arg.startsWith("--color=")) || args.filter(arg => arg.startsWith("--color=")).length > 1) fail("usage: ahub console [--panels] [--no-pet] [--color=auto|always|never]");
1179
1201
  const color = resolveColor(args.find(arg => arg.startsWith("--color="))?.slice("--color=".length), { isTTY: !!process.stdin.isTTY && !!process.stdout.isTTY, TERM: process.env.TERM, NO_COLOR: process.env.NO_COLOR });
1180
1202
  if (color instanceof Error) return fail("usage: ahub console [--panels] [--no-pet] [--color=auto|always|never]");
1181
- await runConsole({ client: await connect(), cwd, stateDir, liveTest, panels: args.includes("--panels"), noPet: args.includes("--no-pet"), color });
1203
+ await runConsole({ client: await connect(), cwd, stateDir, liveTest, panels: args.includes("--panels"), noPet: args.includes("--no-pet"), color, installed: consoleInstalled() });
1182
1204
  },
1183
1205
 
1184
1206
  up: async () => {
@@ -1195,7 +1217,7 @@ const commands: Record<string, () => Promise<void> | void> = {
1195
1217
  for (const line of await startProjectAgents({ root: cwd, stateDir }, chosen.agents)) console.log(terminalText(line));
1196
1218
  } catch (error) { console.error(`default agents were not started: ${terminalText((error as Error).message)}`); }
1197
1219
  }
1198
- if (process.stdin.isTTY && process.stdout.isTTY && !args.includes("--no-console")) await runConsole({ client: await connect(), cwd, stateDir, liveTest });
1220
+ if (process.stdin.isTTY && process.stdout.isTTY && !args.includes("--no-console")) await runConsole({ client: await connect(), cwd, stateDir, liveTest, installed: consoleInstalled() });
1199
1221
  },
1200
1222
 
1201
1223
  ...Object.fromEntries(BUILTIN_CLI_ENTRIES.map(entry => [entry.command, async () => {
@@ -1225,6 +1247,118 @@ const commands: Record<string, () => Promise<void> | void> = {
1225
1247
  return entry.execute(context);
1226
1248
  }])),
1227
1249
 
1250
+ guidance: async () => {
1251
+ const { parseGuidanceCommand, validateGuidancePageReply, validateGuidanceDiffReply, validateGuidanceReceipt, renderGuidance, renderGuidanceReceipt } = await import("./guidance.ts");
1252
+ const { parseGuidanceVariantV1, GUIDANCE_RECORD_MAX_BYTES } = await import("../hub/guidance-variants.ts");
1253
+ const { parseGuidanceProbeSubcommand, parseGuidanceProbeRegistration, GUIDANCE_PROBE_REGISTRATION_BYTES,
1254
+ parseGuidanceProbePublicReceipt, parseGuidanceProbePublicStatus } = await import("../hub/guidance-probes.ts");
1255
+ let probeCommand;
1256
+ try { probeCommand = parseGuidanceProbeSubcommand(args); } catch { return fail("invalid guidance probe command; use probe register, start, show or cancel with the documented bounded arguments"); }
1257
+ if (probeCommand) {
1258
+ if (liveTest) return fail("live-test cannot perform guidance probe operations as the person; use a current person or configured conductor session");
1259
+ let registration: ReturnType<typeof parseGuidanceProbeRegistration> | undefined;
1260
+ if (probeCommand.op === "register") {
1261
+ try {
1262
+ const fd = openSync(resolve(invokedFrom, probeCommand.file), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
1263
+ try {
1264
+ if (!fstatSync(fd).isFile()) return fail("the guidance probe file must be a bounded regular JSON file");
1265
+ const bytes = Buffer.alloc(GUIDANCE_PROBE_REGISTRATION_BYTES + 1); let got = 0;
1266
+ while (got < bytes.length) { const read = readSync(fd, bytes, got, bytes.length - got, null); if (!read) break; got += read; }
1267
+ if (got > GUIDANCE_PROBE_REGISTRATION_BYTES) return fail("the guidance probe registration exceeds its derived envelope bound");
1268
+ registration = parseGuidanceProbeRegistration(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, got))));
1269
+ if (!registration) return fail("invalid guidance probe registration; retain its complete bounded manifest and snapshots without trimming");
1270
+ } finally { closeSync(fd); }
1271
+ } catch { return fail("cannot read a valid bounded guidance probe registration; check its closed V1 manifest and snapshots"); }
1272
+ }
1273
+ const hub = await connect();
1274
+ try {
1275
+ if (!hub.features.includes("guidance_probes")) return fail("running hub lacks guidance_probes; upgrade and restart the hub, then retry ahub guidance");
1276
+ const request = probeCommand.op === "register" ? { t: "guidance_probe_register", registration: registration! }
1277
+ : probeCommand.op === "start" ? { t: "guidance_probe_start", id: probeCommand.id, revision: probeCommand.revision, ...(probeCommand.variantId ? { variantId: probeCommand.variantId } : {}) }
1278
+ : probeCommand.op === "cancel" ? { t: "guidance_probe_cancel", id: probeCommand.id, revision: probeCommand.revision }
1279
+ : { t: "guidance_probe_show", id: probeCommand.id };
1280
+ const result = await hub.request(request);
1281
+ if (result.ok !== true) {
1282
+ const detail = terminalText(result.error ?? "guidance probe outcome is unconfirmed").replace(/[\r\n]+/g, " ").slice(0, 512);
1283
+ const nextStep = probeCommand.op === "register" ? "" : `; inspect ahub guidance probe show --id ${probeCommand.id} before any explicit retry`;
1284
+ return fail(`${detail}${nextStep}`);
1285
+ }
1286
+ if (probeCommand.op === "show") {
1287
+ const status = parseGuidanceProbePublicStatus(result.status);
1288
+ if (!status) return fail("guidance probe status is malformed; refresh its id and current task context");
1289
+ if (args.includes("--json")) console.log(JSON.stringify(status, null, 2));
1290
+ else console.log(`guidance probe ${status.id}: ${status.state}; revision ${status.revision}; evidence ${status.evidence}; workers ${status.counters.workerAttempts}; editors ${status.counters.editorAttempts}; model calls ${status.counters.modelCalls}; tool calls ${status.counters.toolCalls}; token usage ${status.counters.usageUnknown || status.counters.modelCalls === 0 ? "unknown" : status.counters.tokensObservedKnown}; cancelled ${status.cancelRequested ? "yes" : "no"}`);
1291
+ } else {
1292
+ const receipt = parseGuidanceProbePublicReceipt(result.receipt);
1293
+ if (!receipt) return fail("guidance probe receipt is malformed; inspect retained probe state before retrying");
1294
+ if (args.includes("--json")) console.log(JSON.stringify(receipt, null, 2));
1295
+ else console.log(`guidance probe ${receipt.id}: ${receipt.state}; revision ${receipt.revision}; evidence ${receipt.evidence}${receipt.already ? "; already recorded" : ""}`);
1296
+ }
1297
+ } finally { hub.close(); }
1298
+ return;
1299
+ }
1300
+ let command; try { command = parseGuidanceCommand(args); } catch (error) { return fail((error as Error).message); }
1301
+ if (liveTest && (command.op === "create" || command.op === "withdraw")) return fail("live-test cannot write guidance declarations as the person; use the current task actor without --live-test");
1302
+ let variant: ReturnType<typeof parseGuidanceVariantV1> | undefined;
1303
+ if (command.op === "create") {
1304
+ try {
1305
+ const fd = openSync(resolve(invokedFrom, command.file), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
1306
+ try {
1307
+ if (!fstatSync(fd).isFile()) return fail("the guidance file must be a bounded regular JSON file");
1308
+ const bytes = Buffer.alloc(GUIDANCE_RECORD_MAX_BYTES + 1); let got = 0;
1309
+ while (got < bytes.length) { const read = readSync(fd, bytes, got, bytes.length - got, null); if (!read) break; got += read; }
1310
+ if (got > GUIDANCE_RECORD_MAX_BYTES) return fail("the guidance file exceeds the 32 KiB input bound");
1311
+ variant = parseGuidanceVariantV1(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, got))));
1312
+ } finally { closeSync(fd); }
1313
+ } catch { return fail("cannot read a valid bounded GuidanceVariantV1 file; check its shape, content id and protected role bytes"); }
1314
+ }
1315
+ const hub = await connect();
1316
+ try {
1317
+ if (!hub.features.includes("guidance_views")) return fail("running hub lacks guidance_views; upgrade and restart the hub and refresh the client plugin, then retry ahub guidance");
1318
+ const { op, json, ...fields } = command;
1319
+ const message = op === "create" ? { variant } : fields;
1320
+ const result = await hub.request({ t: `guidance_${op}`, ...message });
1321
+ if (result.ok !== true) return fail(`${terminalText(result.error ?? "guidance request is unconfirmed").replace(/[\r\n]+/g, " ").slice(0, 512)}; inspect ahub guidance list for the task before explicitly retrying a write`, result.refusalAudited === true, result.authorityRefused);
1322
+ const options = { json };
1323
+ if (command.op === "create" || command.op === "withdraw") {
1324
+ let receipt;
1325
+ try { receipt = validateGuidanceReceipt(result.receipt, command.op === "create" ? { id: variant!.id, taskId: variant!.taskId } : { id: command.id, taskId: command.taskId, status: "withdrawn" }); }
1326
+ catch (error) { return fail((error as Error).message); }
1327
+ if (options.json) console.log(JSON.stringify(receipt, null, 2)); else console.log(renderGuidanceReceipt(receipt).join("\n"));
1328
+ } else {
1329
+ let page;
1330
+ try { page = command.op === "list" ? validateGuidancePageReply(result.guidance, command) : validateGuidanceDiffReply(result.guidance, command); }
1331
+ catch { return fail("guidance reply is unavailable or malformed; refresh the task scope and upgrade the hub/client before retrying"); }
1332
+ if (options.json) console.log(JSON.stringify(page, null, 2)); else console.log(renderGuidance(page).join("\n"));
1333
+ }
1334
+ } finally { hub.close(); }
1335
+ },
1336
+
1337
+ lineage: async () => {
1338
+ const { parseLineageCommand, renderExecutionLineage, validateLineageReply, validateLineageLink } = await import("./lineage.ts");
1339
+ let command;
1340
+ try { command = parseLineageCommand(args); } catch (error) { return fail((error as Error).message); }
1341
+ if (liveTest && command.op === "link") return fail("live-test cannot register execution links; retry without --live-test as the task's authorized actor");
1342
+ const hub = await connect();
1343
+ try {
1344
+ if (!hub.features.includes("execution_lineage")) return fail("running hub lacks execution_lineage support; upgrade and restart the hub, then retry ahub lineage");
1345
+ const { op, json, ...message } = command;
1346
+ const result = await hub.request({ t: op === "show" ? "lineage_show" : "lineage_link", ...message });
1347
+ if (result.ok !== true) return fail(`${terminalText(result.error ?? "lineage request refused").replace(/[\r\n]+/g, " ").slice(0, 512)}; check task scope, current flow revision and source access before retrying ahub lineage`, result.refusalAudited === true, result.authorityRefused);
1348
+ const options = { json };
1349
+ if (op === "show") {
1350
+ let lineage;
1351
+ try { lineage = validateLineageReply(result.lineage); } catch (error) { return fail((error as Error).message); }
1352
+ if (options.json) console.log(JSON.stringify(lineage, null, 2));
1353
+ else console.log(renderExecutionLineage(lineage).join("\n"));
1354
+ } else {
1355
+ let link;
1356
+ try { link = validateLineageLink(result.link, command); } catch (error) { return fail((error as Error).message); }
1357
+ if (options.json) console.log(JSON.stringify(link, null, 2));
1358
+ else console.log(`Declared execution metadata link ${link.already ? "already registered" : "registered"} for task #${link.taskId}; this does not attest to producer execution.`);
1359
+ }
1360
+ } finally { hub.close(); }
1361
+ },
1228
1362
  model: async () => {
1229
1363
  const { parseModelCommand, projectModelStatus } = await import("./model.ts");
1230
1364
  let command;
@@ -1862,6 +1996,21 @@ const commands: Record<string, () => Promise<void> | void> = {
1862
1996
  } finally { hub.close(); }
1863
1997
  return;
1864
1998
  }
1999
+ if (sub === "adopt-merge") {
2000
+ const flags = takeFlags(args.slice(2), ["--pr"], []), pr = Number(flags.one["--pr"]);
2001
+ if (flags.rest.length || !Number.isSafeInteger(id) || id! <= 0 || !Number.isSafeInteger(pr) || pr <= 0) fail("usage: ahub sdlc adopt-merge <task> --pr <n>");
2002
+ const hub = await connect();
2003
+ try {
2004
+ const reply = await hub.request({ t: "sdlc", op: "adopt-merge", id, pr }, 60_000);
2005
+ if (!reply.ok) {
2006
+ const reason = typeof reply.error === "string" ? reply.error : "merge adoption failed without a reason; inspect the hub log and retry ahub sdlc adopt-merge";
2007
+ if (/unknown SDLC operation|does not know|SDLC readback is console only/.test(reason)) fail(`${reason}; the running hub does not support adopt-merge; upgrade agent-hub and run ahub restart before retrying ahub sdlc adopt-merge`);
2008
+ fail(reason);
2009
+ }
2010
+ console.log(`task #${id}: merged outside the hub; approved`);
2011
+ } finally { hub.close(); }
2012
+ return;
2013
+ }
1865
2014
  if (sub === "merge") {
1866
2015
  // #786 T1: the guarded merge of one approved task; a person or the configured conductor asks, the daemon re-reads every gate.
1867
2016
  // #899: the decision prints for a person; `--json` is the same view as a document. The presentation flags are read before the
@@ -2238,7 +2387,8 @@ const commands: Record<string, () => Promise<void> | void> = {
2238
2387
  if (!Object.hasOwn(allowed, sub) || flags.some((flag) => !allowed[sub]!.includes(flag)) || extra.length) fail(usage);
2239
2388
  if ((sub === "get" && (!key || text !== undefined)) || (sub === "set" && (!key || text === undefined)) || ((sub === "list" || sub === "undo" || sub === "reload") && key !== undefined)) fail(usage);
2240
2389
  const { scope: settingScope, error: settingScopeError } = localDeclarations();
2241
- const def = key === undefined ? undefined : settingDef(key, settingScope.instances, settingScope.catalog);
2390
+ const sdlcRead = sub === "get" && ["sdlc.mode", "sdlc.required_checks"].includes(key ?? "");
2391
+ const def = key === undefined || sdlcRead ? undefined : settingDef(key, settingScope.instances, settingScope.catalog);
2242
2392
  if (typeof def === "string") fail(settingScopeError && def.startsWith("unknown setting") ? `${key}: ${def}; the project config could not be read: ${settingScopeError}` : `${key}: ${def}`);
2243
2393
  if (flags.includes("--now") && (typeof def !== "object" || def.group !== "Roster")) fail(usage);
2244
2394
  const value = sub === "set" ? parseSettingText(def!, text!) : undefined;
@@ -2257,6 +2407,12 @@ const commands: Record<string, () => Promise<void> | void> = {
2257
2407
  }
2258
2408
  return reply;
2259
2409
  };
2410
+ if (sdlcRead) {
2411
+ const view = await request({ t: "settings_get" }), entry = view.sdlc?.[key!];
2412
+ if (!entry || !Object.hasOwn(entry, "value") || !Object.hasOwn(entry, "fileValue")) fail("running hub lacks SDLC settings reads; upgrade and restart it first");
2413
+ if (flags.includes("--json")) return console.log(JSON.stringify({ key, ...entry }, null, 2));
2414
+ return console.log(terminalText(`${key}: running ${JSON.stringify(entry.value)}; file ${JSON.stringify(entry.fileValue)}${entry.problem ? "; file unavailable" : ""}`));
2415
+ }
2260
2416
  if (sub === "reload") {
2261
2417
  let result = await request({ t: "settings_reload" });
2262
2418
  const confirmation = result.confirmation;
@@ -2993,6 +3149,7 @@ const commands: Record<string, () => Promise<void> | void> = {
2993
3149
 
2994
3150
  const config = loadConfig(cwd);
2995
3151
  row(!config.ignored, "config", config.ignored ? `${config.ignored.join("; ")} (move them to .agenthub/config.local.json)` : "no machine-local field ignored");
3152
+ for (const line of config.releasePolicyNotices ?? []) row(false, "release policy", line);
2996
3153
  for (const line of config.retired ?? []) row(false, "retired setting", line);
2997
3154
  const { routing, errors: routingErrors } = inspectDoctorRouting(cwd);
2998
3155
  for (const error of routingErrors) row(false, "routing", error);
@@ -3146,7 +3303,7 @@ async function runConductorCommand(): Promise<void> {
3146
3303
  }
3147
3304
  let op: string;
3148
3305
  let input: Record<string, unknown>;
3149
- if (cmd === "sdlc") return commands.sdlc!(); // #786: `sdlc merge` is the one conductor-class sdlc subcommand; the daemon checks the role.
3306
+ if (cmd === "sdlc") return commands.sdlc!(); // SDLC operational subcommands are role-checked by the daemon.
3150
3307
  if (cmd === "task") {
3151
3308
  op = args[0] === "assign" ? "hub_task_assign" : "hub_task_escalate";
3152
3309
  const { one, rest: positional } = takeFlags(args.slice(1), args[0] === "assign" ? ["--role"] : [], []);
@@ -1,9 +1,9 @@
1
1
  import { globalCliUpdateStep, type InstallPathOptions } from "./install-paths.ts";
2
2
  import type { DoctorCheck } from "./output.ts";
3
3
  import { parseList, pluginState, type InstalledPlugin } from "./setup.ts";
4
+ import { displayVersion } from "../version.ts";
4
5
 
5
- const VERSION = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?(?:\+[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?$/;
6
- const version = (value: unknown): string | undefined => typeof value === "string" && value.length <= 64 && VERSION.exec(value)?.[0] === value ? value : undefined;
6
+ const version = displayVersion;
7
7
 
8
8
  /** Authenticated daemon status and the existing plugin inventory only. Suggestions never run an update. */
9
9
  export function runtimeVersionWarnings(daemonVersion: unknown, cliVersion: unknown, pluginVersion: unknown, install: InstallPathOptions = {}): DoctorCheck[] {
@@ -169,17 +169,21 @@ export function renderSdlcRelease(reply: unknown, columns?: number, now = Date.n
169
169
  const r = (reply as any)?.report ?? {};
170
170
  const out: Line[] = [...heading(`Release readiness ${r.repo ?? "unknown repository"}`, columns)];
171
171
  const w = 12;
172
- out.push(...pair("version", r.version ?? "unknown", columns, w), ...pair("head", short(r.head), columns, w), ...pair("tag", r.tag ? `${r.tag} at ${short(r.tagCommit)}` : "none", columns, w));
172
+ out.push(...pair("version", r.version ?? (r.releasePolicy ? "undetermined" : "unknown"), columns, w), ...pair("head", short(r.head), columns, w), ...pair("tag", r.tag ? `${r.tag} at ${short(r.tagCommit)}` : "none", columns, w));
173
173
  out.push(...pair("source ready", yes(r.sourceReady), columns, w, readyTone(r.sourceReady)), ...pair("native", String(r.native ?? "unverified"), columns, w, "attention"), ...pair("release ready", yes(r.ready), columns, w, readyTone(r.ready)));
174
174
  out.push(...pair("commits", `${plural(list(r.commits).length, "commit")} since the last tag`, columns, w));
175
175
  if (list(r.mergedPrs).length) out.push(...pair("merged PRs", list(r.mergedPrs).map((p: any) => `#${p.pr}`).join(", "), columns, w));
176
176
  const docs = r.documents;
177
- out.push(blank, ...pair("documents", docs ? `${docs.fresh ? "fresh" : "not fresh"}, ${plural(docs.errors ?? 0, "error")}, ${plural(list(docs.documents).length, "document")}` : "not read", columns, w, docs?.fresh ? "success" : "attention"));
178
- for (const d of list(docs?.documents)) if (d.state !== "fresh") out.push(...pair(d.state, `${d.path ?? "(path withheld)"}${d.dirty ? " (uncommitted changes)" : ""}`, columns, w, "attention", " "));
177
+ if (r.releasePolicy?.docsSource === "none") out.push(blank, ...pair("documents", r.releasePolicy.authorization === "matched" ? "none (explicit exemption recorded)" : "none (configured exemption; no matching authorization)", columns, w, "muted"));
178
+ else {
179
+ out.push(blank, ...pair("documents", docs ? `${docs.fresh ? "fresh" : "not fresh"}, ${plural(docs.errors ?? 0, "error")}, ${plural(list(docs.documents).length, "document")}` : "not read", columns, w, docs?.fresh ? "success" : "attention"));
180
+ for (const d of list(docs?.documents)) if (d.state !== "fresh") out.push(...pair(d.state, `${d.path ?? "(path withheld)"}${d.dirty ? " (uncommitted changes)" : ""}`, columns, w, "attention", " "));
181
+ }
182
+ if (r.releasePolicy) out.push(...pair("release policy", `version ${r.releasePolicy.versionSource}, docs ${r.releasePolicy.docsSource}, authorization ${r.releasePolicy.authorization}`, columns, w, r.releasePolicy.authorization === "matched" ? "success" : "attention"));
179
183
  if (list(r.liveIssues).length) out.push(blank, ...grid(["ISSUE", "STATE"], list(r.liveIssues).map((i: any) => [s(`#${i.id}`, "issueRef"), s(i.state, i.state === "closed" ? "success" : "attention")]), columns));
180
184
  const a = r.authorization;
181
185
  if (a) out.push(blank, ...pair("authorization", `${a.state}: version ${a.receipt?.version ?? "unknown"} at ${short(a.receipt?.commit)}, approved ${moment(a.receipt?.at, now)}`, columns, w, a.state === "matched" ? "success" : "attention"));
182
- else out.push(blank, ...pair("authorization", "none recorded: run ahub sdlc authorize-release <version>", columns, w, "muted"));
186
+ else out.push(blank, ...pair("authorization", r.releasePolicy ? `none recorded for ${r.releasePolicy.versionSource}: run ahub sdlc authorize-release <version>` : "none recorded: run ahub sdlc authorize-release <version>", columns, w, "muted"));
183
187
  for (const t of list(r.trains)) out.push(...pair(`train #${t.release?.id ?? "?"}`, `${t.readiness?.trigger ?? "unknown"}${list(t.readiness?.blockers).length ? `, ${list(t.readiness.blockers).join("; ")}` : ""}`, columns, w, list(t.readiness?.blockers).length ? "attention" : undefined));
184
188
  const rm = r.releaseMetrics;
185
189
  if (rm) {
@@ -249,7 +253,7 @@ export function renderAuthorization(authorization: unknown, columns?: number, no
249
253
  const w = 8;
250
254
  return [...heading("Release authorized", columns),
251
255
  ...pair("version", a?.version ?? "unknown", columns, w), ...pair("commit", short(a?.commit), columns, w), ...pair("by", a?.by ?? "unknown", columns, w),
252
- ...pair("at", moment(a?.at, now), columns, w), ...pair("docs", a?.docs ? `${a.docs.fresh ? "fresh" : "not fresh"}, ${plural(a.docs.documents ?? 0, "document")}, digest ${short(a.docs.digest)}` : "unknown", columns, w),
256
+ ...pair("at", moment(a?.at, now), columns, w), ...pair("docs", a?.docs?.source === "none" ? "none (explicit exemption)" : a?.docs ? `${a.docs.fresh ? "fresh" : "not fresh"}, ${plural(a.docs.documents ?? 0, "document")}, digest ${short(a.docs.digest)}` : "unknown", columns, w),
253
257
  ...pair("id", a?.id ?? "unknown", columns, w, "muted"), blank,
254
258
  ...para("A daemon restart revokes this authorization.", columns, "muted")];
255
259
  }