@staix/agent-hub 0.37.0 → 0.39.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 (164) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +17 -7
  3. package/docs/adding-an-ai-tool.md +6 -4
  4. package/docs/agent-notes/README.md +16 -0
  5. package/docs/agent-notes/adapters.md +4 -2
  6. package/docs/agent-notes/budget.md +8 -0
  7. package/docs/agent-notes/daemon.md +15 -8
  8. package/docs/agent-notes/local-worker.md +1 -1
  9. package/docs/agent-notes/security-review.md +55 -0
  10. package/docs/agent-notes/tasks.md +15 -4
  11. package/docs/agent-notes/tests.md +3 -2
  12. package/docs/design/adapters.md +51 -0
  13. package/docs/design/agent-hub-architecture.md +29 -1
  14. package/docs/design/guidance-probes.md +365 -0
  15. package/docs/design/task-board.md +151 -5
  16. package/docs/dogfood.md +22 -7
  17. package/docs/events.md +3 -3
  18. package/docs/memory.md +5 -5
  19. package/docs/operations.md +189 -32
  20. package/docs/profiles.md +101 -9
  21. package/docs/quickstart.md +38 -4
  22. package/docs/research.md +6 -3
  23. package/docs/roles.md +52 -0
  24. package/docs/sdlc.md +187 -1
  25. package/docs/security.md +56 -13
  26. package/docs/text-projection.md +1 -0
  27. package/docs/verification/2026-11-11-0.38.0.md +41 -0
  28. package/docs/verification/2026-11-11-guidance-probe-t3-1226.md +85 -0
  29. package/docs/verification/2026-11-11-guidance-probe-t4-1226.md +65 -0
  30. package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
  31. package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
  32. package/docs/verification/2026-11-14-0.39.0.md +51 -0
  33. package/docs/verified.json +48 -25
  34. package/package.json +3 -3
  35. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  36. package/plugins/agent-hub/kimi-hook.js +1989 -474
  37. package/plugins/agent-hub/server.js +2056 -512
  38. package/src/adapters/acp-model-policy.ts +1 -1
  39. package/src/adapters/acp-session-model.ts +35 -0
  40. package/src/adapters/acp.ts +14 -0
  41. package/src/adapters/agy/definition.ts +1 -1
  42. package/src/adapters/agy/hooks.ts +7 -0
  43. package/src/adapters/claude-channel.ts +3 -2
  44. package/src/adapters/claude-implementer.ts +8 -0
  45. package/src/adapters/claude-print-child.ts +26 -2
  46. package/src/adapters/claude-print.ts +4 -0
  47. package/src/adapters/codex-appserver.ts +90 -16
  48. package/src/adapters/codex-review-isolation.ts +2 -0
  49. package/src/adapters/compat.ts +4 -4
  50. package/src/adapters/conformance/fakes/acp-server.ts +11 -2
  51. package/src/adapters/conformance/fakes/app-server.ts +5 -1
  52. package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
  53. package/src/adapters/definitions/builtin-metadata.ts +6 -6
  54. package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
  55. package/src/adapters/definitions/native-quota.ts +122 -0
  56. package/src/adapters/definitions/native-recovery.ts +3 -0
  57. package/src/adapters/definitions/qwen.ts +1 -1
  58. package/src/adapters/kimi-review.ts +23 -0
  59. package/src/adapters/kimi-wire-usage.ts +39 -16
  60. package/src/adapters/local-probe.ts +65 -6
  61. package/src/adapters/local-worker.ts +6 -3
  62. package/src/adapters/pi-state-model.ts +12 -0
  63. package/src/adapters/pi.ts +22 -0
  64. package/src/adapters/print-result-model.ts +24 -0
  65. package/src/adapters/registry-types.ts +10 -1
  66. package/src/adapters/registry.ts +19 -2
  67. package/src/adapters/reviewer-print.ts +130 -15
  68. package/src/adapters/role-eligibility.ts +99 -0
  69. package/src/adapters/same-directory.ts +16 -0
  70. package/src/cli/agy-mcp.ts +18 -7
  71. package/src/cli/console-state.ts +3 -1
  72. package/src/cli/free-text.ts +20 -0
  73. package/src/cli/handoff-args.ts +1 -1
  74. package/src/cli/help.ts +61 -6
  75. package/src/cli/identity.ts +10 -4
  76. package/src/cli/init-prompt.ts +31 -2
  77. package/src/cli/init-roles.ts +156 -0
  78. package/src/cli/init-settings.ts +24 -2
  79. package/src/cli/init.ts +141 -17
  80. package/src/cli/main.ts +216 -56
  81. package/src/cli/model.ts +1 -1
  82. package/src/cli/output.ts +64 -5
  83. package/src/cli/preview.ts +1 -1
  84. package/src/cli/recovery-launch.ts +114 -0
  85. package/src/cli/recovery-package.ts +14 -7
  86. package/src/cli/recovery-version-preflight.ts +104 -0
  87. package/src/cli/role-doctor.ts +39 -0
  88. package/src/cli/sdlc-output.ts +66 -1
  89. package/src/cli/study-output.ts +54 -0
  90. package/src/cli/study.ts +14 -1
  91. package/src/cli/terminal-recovery.ts +14 -0
  92. package/src/cli/upgrade-presentation.ts +4 -0
  93. package/src/cli/upgrade-restore-state.ts +12 -3
  94. package/src/cli/upgrade-runtime.ts +41 -3
  95. package/src/cli/upgrade.ts +8 -4
  96. package/src/hub/advisor-survey.ts +139 -0
  97. package/src/hub/audit-source.ts +66 -0
  98. package/src/hub/board.ts +479 -14
  99. package/src/hub/budget.ts +54 -4
  100. package/src/hub/bus.ts +2 -2
  101. package/src/hub/conductor.ts +14 -8
  102. package/src/hub/config-apply.ts +2 -1
  103. package/src/hub/config-edit-host.ts +77 -5
  104. package/src/hub/considered-findings.ts +47 -0
  105. package/src/hub/control-client.ts +1 -1
  106. package/src/hub/daemon.ts +373 -66
  107. package/src/hub/deliverable-files.ts +17 -1
  108. package/src/hub/dogfood-profile.ts +3 -2
  109. package/src/hub/envelope.ts +6 -1
  110. package/src/hub/events.ts +23 -2
  111. package/src/hub/folder-trigger.ts +11 -4
  112. package/src/hub/guidance-probe-store.ts +345 -14
  113. package/src/hub/guidance-probes.ts +338 -4
  114. package/src/hub/hub-tools.ts +88 -16
  115. package/src/hub/kimi-usage.ts +34 -2
  116. package/src/hub/lifecycle-schema.ts +3 -3
  117. package/src/hub/manager.ts +24 -1
  118. package/src/hub/memory-profile.ts +9 -1
  119. package/src/hub/memory-sync-state.ts +1 -0
  120. package/src/hub/model-overrides.ts +2 -1
  121. package/src/hub/no-writes.ts +2 -0
  122. package/src/hub/operational-authority.ts +8 -2
  123. package/src/hub/operational-view.ts +5 -1
  124. package/src/hub/peers.ts +2 -0
  125. package/src/hub/person-command.ts +25 -0
  126. package/src/hub/plan-conformance.ts +20 -2
  127. package/src/hub/quota-account.ts +34 -0
  128. package/src/hub/recovery-policy.ts +18 -4
  129. package/src/hub/research-evidence.ts +51 -3
  130. package/src/hub/research.ts +77 -13
  131. package/src/hub/restart.ts +14 -0
  132. package/src/hub/review-budget.ts +88 -0
  133. package/src/hub/review-findings.ts +93 -12
  134. package/src/hub/reviewer-pool-config.ts +6 -2
  135. package/src/hub/reviewer-pool.ts +39 -6
  136. package/src/hub/routing.ts +7 -3
  137. package/src/hub/sdlc-merge.ts +1 -1
  138. package/src/hub/sdlc-queue.ts +14 -4
  139. package/src/hub/sdlc-release.ts +1 -1
  140. package/src/hub/sdlc.ts +10 -6
  141. package/src/hub/security-audit.ts +178 -0
  142. package/src/hub/security-pass.ts +115 -0
  143. package/src/hub/settings.ts +11 -5
  144. package/src/hub/source-read.ts +80 -2
  145. package/src/hub/sources.ts +57 -9
  146. package/src/hub/startup-event-seeds.ts +5 -3
  147. package/src/hub/startup-timing.ts +1 -0
  148. package/src/hub/supervision.ts +3 -2
  149. package/src/hub/synthesis-readiness.ts +279 -0
  150. package/src/hub/tasks.ts +1131 -72
  151. package/src/hub/text-projection.ts +11 -1
  152. package/src/local/probe-types.ts +2 -0
  153. package/src/local/probe-workspace.ts +191 -2
  154. package/src/memory/capture.ts +2 -1
  155. package/src/ui/guidance-panel.ts +34 -2
  156. package/src/ui/guidance-view.ts +33 -0
  157. package/src/ui/index.html +3 -0
  158. package/src/ui/office-model.ts +11 -3
  159. package/src/ui/office-space.ts +50 -30
  160. package/src/ui/plugin.ts +31 -14
  161. package/templates/AGENTS.block.md +14 -14
  162. package/templates/profiles/general.json +1 -1
  163. package/templates/profiles/research.json +1 -1
  164. package/templates/profiles/writing.json +1 -1
@@ -6,3 +6,23 @@ export function freeText(words: string[], usage: string): string {
6
6
  if (flag) throw new Error(`the message would absorb the flag "${flag}"; put it after "--" to send it as text; usage: ${usage}`);
7
7
  return (end === -1 ? words : [...before, ...words.slice(end + 1)]).join(" ");
8
8
  }
9
+
10
+ /**
11
+ * #1433: the first word of a write command's free text that reads as an option the command does not know: it starts with `--`, or is `-h`. Words after a lone `--` are text, as in `freeText`.
12
+ * A command that takes its flags out first passes what is left.
13
+ */
14
+ export function unknownOption(words: readonly string[]): string | undefined {
15
+ const end = words.indexOf("--");
16
+ return (end === -1 ? words : words.slice(0, end)).find(word => word.startsWith("--") || word === "-h");
17
+ }
18
+
19
+ /** The text words with the lone `--` separator removed. */
20
+ export function withoutSeparator(words: readonly string[]): string[] {
21
+ const end = words.indexOf("--");
22
+ return end === -1 ? [...words] : [...words.slice(0, end), ...words.slice(end + 1)];
23
+ }
24
+
25
+ /** The refusal for an option-like word where a write command wanted text, said before anything is filed. */
26
+ export function unknownOptionRefusal(word: string, command: string, usage: string | undefined): string {
27
+ return `unknown option ${JSON.stringify(word)} for ${command}; nothing was filed. Put "--" before text that starts with dashes${usage ? `. Usage: ${usage}` : ""}`;
28
+ }
@@ -23,7 +23,7 @@ export function parseHandoffArgs(operands: readonly string[]): HandoffCliRequest
23
23
  const value = operands[++i];
24
24
  if (value === undefined || value.startsWith("--")) return { usage: HANDOFF_USAGE };
25
25
  if (arg === "--path") paths.push(value); else { if (Object.hasOwn(one, arg)) return { usage: HANDOFF_USAGE }; one[arg] = value; }
26
- } else if (arg.startsWith("--")) return { usage: HANDOFF_USAGE };
26
+ } else if (arg.startsWith("--") || arg === "-h") return { usage: `unknown option ${JSON.stringify(arg)}; nothing was filed\n${HANDOFF_USAGE}` };
27
27
  else rest.push(arg);
28
28
  }
29
29
  const project = one["--project"];
package/src/cli/help.ts CHANGED
@@ -5,6 +5,22 @@ import { paint, wrap, type Span } from "./console-state.ts";
5
5
  /** One usage form of `ahub help`: the usage starts with `ahub <command>`, alternatives joined by `|`. */
6
6
  export interface HelpEntry { section: string; usage: string; description: string }
7
7
 
8
+ /** #1405: one source for the probe usage, read by `ahub help` and by the refusal of a malformed probe command. */
9
+ export const GUIDANCE_PROBE_USAGE = {
10
+ register: "register --file JSON [--json]",
11
+ start: "start --id HASH --revision N [--variant G1-HASH] [--json]",
12
+ show: "show --id HASH [--json]",
13
+ receipts: "receipts --id HASH [--json]",
14
+ cancel: "cancel --id HASH --revision N [--json]",
15
+ } as const;
16
+ /** What to print when `ahub guidance probe ...` did not parse: the typed subcommand's own usage, or all five for an unknown one. */
17
+ export function guidanceProbeUsage(args: readonly string[]): string {
18
+ const typed = args[1], known = typed !== undefined && Object.hasOwn(GUIDANCE_PROBE_USAGE, typed);
19
+ const forms = known ? [GUIDANCE_PROBE_USAGE[typed as keyof typeof GUIDANCE_PROBE_USAGE]] : Object.values(GUIDANCE_PROBE_USAGE);
20
+ const id = known && typed === "register" ? "" : " HASH is the 64-character probe id that ahub guidance probe register printed; no command lists probes.";
21
+ return `${known ? `ahub guidance probe ${typed} has a missing or malformed argument` : "unknown guidance probe command"}; usage: ${forms.map(form => `ahub guidance probe ${form}`).join(" | ")}.${id}`;
22
+ }
23
+
8
24
  const SECTIONS: [string, [usage: string, description: string][]][] = [
9
25
  ["Projects", [
10
26
  ["ahub specs list [--json] | check [--require-fresh] [--base <ref>] [--json] | covers <file...> | stamp <id-or-document...> [--yes]", "read design specs, validate their graph and source freshness, or find covering specs; runs without a daemon; check exits 1 on errors and, with --require-fresh, stale documents; stamp is person only (a terminal, never an agent): it shows old -> new, asks (--yes skips the question but still needs a terminal), and then changes only the verified-against line (or the stamps-file entry) to the full HEAD SHA, refused while the covered paths have uncommitted changes"],
@@ -13,7 +29,7 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
13
29
  ["ahub projects [--json] [--full] [--color=auto|always|never]", "list registered projects and live status"],
14
30
  ["ahub projects remove <id>", "forget a stopped registration (keeps project files)"],
15
31
  ["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"],
32
+ ["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] [--conductor <peer>|none] [--planner <a,b,...>] [--reviewer <a,b,...>|person] [--track-config|--no-track-config] [--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). --track-config keeps .agenthub/config.json, routing.toml and sdlc.toml visible to git (a rule that ignores one is named and nothing is written; a routing.toml that names a machine endpoint stays ignored) and lists them to commit; --no-track-config ignores them; either sets the AGENTS.md role sentence, and neither keeps what git and the block say today. 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. --conductor, --planner and --reviewer (#1408) choose who conducts, plans and reviews, each on its own: the shared config.json roles are written as an explicit list for every peer whose roles change (the one that loses a role too), implementer and verifier are untouched, a peer that cannot hold the role (a headless conductor, a kind that cannot plan) is refused before any write with the reason and the eligible peers, --conductor none leaves the person conducting from ahub console and --reviewer person sends reviews to the person; Executables, secrets, models and permissions stay file edits"],
17
33
  ["ahub --live-test [--project <path|id>] <command> [args...]", "user-authorized operational console delegation; ordinary calls retain peer identity; person-authored content refuses"],
18
34
  ["ahub help [command]", "this help, or one command's entries; also --help and -h"],
19
35
  ["ahub version | --version", "print the installed version"],
@@ -27,9 +43,14 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
27
43
  ["ahub pet --palette <blue|teal|violet|ochre>", "retired floating-window option: run acon ui and open Mini"],
28
44
  ["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
45
  ["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"],
46
+ ["ahub sdlc survey start [--focus bugs|tests|debt|deps|dx|docs] [--json] [--color=auto|always|never]", "person or current conductor: file one read-only planner survey at a pinned source ref; only explicitly vetted findings produce backlog cards"],
47
+ ["ahub sdlc survey show <task> [--json] [--color=auto|always|never]", "read findings and their vet decisions; unchanged or unknown prior rejections remain rejected before, and reconsideration needs an explicit vetted reason"],
48
+ ["ahub sdlc audit start [--profile quick|standard] [--since <ref>] [--json] [--color=auto|always|never]", "file one read-only security audit task and seed its coverage ledger from [security] in sdlc.toml (person or current conductor); quick and scoped runs read as partial"],
49
+ ["ahub sdlc audit show [<audit>] [--json] [--color=auto|always|never]", "the newest (or named) audit: source, coverage counts by unit state, each unit and finding; open important finding details are shown to the person only"],
30
50
  ["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)"],
31
51
  ["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)"],
32
52
  ["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)"],
53
+ ["ahub sdlc configure [--mode off|advise] [--required-checks names] [--json] [--color=auto|always|never]", "save only lifecycle mode/check names through loader validation and backup, pending restart (person or current unique conductor on the person's explicit instruction in its own session; enforce and other fields remain person-only; no release consent)"],
33
54
  ["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"],
34
55
  ["ahub sdlc release-guard-hook <remote-name> <remote-url>", "internal pre-push readback; validates version tags and forwards exact stdin on success"],
35
56
  ["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)"],
@@ -43,7 +64,7 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
43
64
  ["ahub status [--json] [--full] [--color=auto|always|never]", "the hub, its peers, model backends and task counts, plus a specs line (errors and stale documents) when the project has design specs"],
44
65
  ["ahub status --all [--json] [--color=auto|always|never]", "show every registered project"],
45
66
  ["ahub logs [-f]", "person: last 100 hub.log lines (-f starts at 10); conductor: bounded public lines and follow while authority remains"],
46
- ["ahub doctor [--json] [--full] [--color=auto|always|never]", "check the tools, daemon, plugin, gateway, models, memory library and memory capture setup (read from `amem setup <tool> --json`, a preview) this project uses, and the runtime capture pruning ledger; warn when the CLI or plugin is older than its running daemon"],
67
+ ["ahub doctor [--json] [--full] [--color=auto|always|never]", "check the tools, daemon, plugin, gateway, models, memory library and memory capture setup (read from `amem setup <tool> --json`, a preview) this project uses, the runtime capture pruning ledger, whether the shared config.json tracking matches the AGENTS.md roles sentence, and who holds conductor, planner and reviewer as the loader settled them (a warning, never a failure); warn when the CLI or plugin is older than its running daemon"],
47
68
  ["ahub doctor --stale-anchors [--json]", "read-only bounded report of public memory symbol anchors at current HEAD; private or unavailable evidence stays unknown"],
48
69
  ["ahub doctor --orphans [--kill] [--json] [--color=auto|always|never]", "person: inspect missing-root registrations; conductor --kill: selected project only; signed hub ownership is required before any stop"],
49
70
  ["ahub agents [--json]", "show each gated agent CLI's installed version and verdict (verified, in-line, trusted, refused or unknown)"],
@@ -78,6 +99,7 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
78
99
  ["ahub answer [<set> <question>=<option>[,<option>]... [--other [<question>=]<text>]] [--json] [--color=auto|always|never]", "person only: without operands list the questions agents asked with hub_ask; with them answer one set (every question once, known options only, other text only where offered)"],
79
100
  ["ahub results [--unread] [--read <id> | --read-all | --unread-last] [--json] [--color=auto|always|never]", "person only: list what the runs you started left behind (unread ones marked *); --read marks one read, --read-all every one, --unread-last lights the most recent read one again; listing never marks anything"],
80
101
  ["ahub roster [--json] [--color=auto|always|never]", "every known peer, participation, start mode and retained work"],
102
+ ["ahub roles [--json] [--color=auto|always|never]", "each rostered peer's flow roles as the running hub settled them, the planner and who reviews when no reviewer can run; works from a task worktree"],
81
103
  ["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"],
82
104
  ["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"],
83
105
  ["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"],
@@ -114,6 +136,7 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
114
136
  ["ahub capabilities [--json] [--color=auto|always|never]", "person only, never a conductor or an agent shell: list the skills and commands each attached peer offers (Kimi 2.3.2 and Qwen 0.26.1 sessions, Codex 0.166.0 skills; other versions list nothing), whether you share each one, its digest and the class a call would count as; sharing is invocation.share in .agenthub/config.local.json, this machine only; it only lists and never calls anything"],
115
137
  ["ahub learn list [--all] | accept <id> | reject <id> [--json] [--color=auto|always|never]", "person only, never a conductor or an agent shell: review a recurring-unmet-criterion candidate the hub filed (#514a); accept writes its one review checklist line, added to your current checklist, to .agenthub/config.local.json through the settings writer (this machine only, never a tracked file, ahub settings undo puts it back, applies after a restart) and closes the card; reject only closes it"],
116
138
  ["ahub study draft <parent> <contract.json> | revise <id> <revision> <contract.json> | approve <id> <revision> | close <id> <revision> --reason <text> | approve-protocol <hash> [--json] [--color=auto|always|never]", "person only: store a research campaign contract as a draft, revise it, approve it (the only step that creates the unit tasks and lets work start) or close it; approve-protocol binds approval to the exact protocol and evaluator hashes; a planner drafts through hub_study_draft and hub_study_revise and can never approve"],
139
+ ["ahub study evidence <ev-id> [--revision <n>] | evidence --task <task> | check <task> <manifest.json> [--json] [--color=auto|always|never]", "explicit evidence provenance and offline synthesis readiness: single-link reads reuse research scope/privacy; task inventory and check are person-only. Complete claim/link inventories and registered deliverable hashes bind the manifest. Separate citation, locator, person judgment, contradiction and artifact statuses never certify truth; a non-ready check exits nonzero"],
117
140
  ["ahub study show [<id> | --after <id>] [--json] [--color=auto|always|never]", "read-only for anyone: list this project's research campaigns, 50 per page (the page names the --after cursor that continues it), or one campaign's coverage per unit, handoff state, budget support and why dispatch is held; a private campaign, task or source shows ids, counts and states only"],
118
141
  ["ahub study experiments (--campaign <id> [--after <n>] | --attempt <ra-id> [--events-after <n>] | --plan <hash> --baseline <ra-id> --variant <ra-id>) [--json] [--color=auto|always|never]", "read-only for anyone, the same read as hub_experiment_show: a campaign's recorded attempts (50 a page, --after continues), one attempt with its events, or one comparison under a recorded plan; each value names its provenance and a declared value is never shown as observed"],
119
142
  ["ahub deliverables [--task <id>] [--approved] [--check] [--json] [--color=auto|always|never]", "what each task delivered and a reviewer approved, by id, hash and size (a path only where the PII screen allows); --check measures the files now and marks one changed since review; an agent sees only the tasks hub_task_show shows it"],
@@ -121,10 +144,10 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
121
144
  ["ahub task role <id> <role|none>", "the person, or an agent on a task it owns: change bounded catalog guidance on an open task; routing and authority are unchanged"],
122
145
  ["ahub task assign <id> <peer> [--role owner|reviewer|planner] [--revision N]", "name the owner (default), reviewer or person-only planner; a task that still waits reserves its owner; a peer that cannot take it is refused with the reason; --revision refuses stale console actions"],
123
146
  ["ahub task unassign <id> [--role owner|reviewer] [--revision N]", "person or configured conductor: remove the owner/reservation or reviewer without routing a replacement or stopping native work; preserves the actual actor"],
124
- ["ahub task claim <id> <slot> <supported|unsupported|unclear> [--model <label>] [--model-said <supported|unsupported|unclear>]", "person only: record your verdict on one declared plan claim (by its 1-based slot, never its text), with the model label and what the model said, so the research scorecard can show agreement; a later verdict for the slot replaces the earlier one"],
147
+ ["ahub task claim <id> <slot> <supported|unsupported|unclear> [--model <label>] [--model-said <supported|unsupported|unclear>] [--manifest <manifest.json> --disposition <resolved|qualified>]", "person only: record your verdict on one declared plan claim (by its 1-based slot, never its text), with optional model agreement metadata; paired manifest/disposition fields bind an adjudicated or explicitly qualified research conclusion to the exact synthesis manifest; a later verdict for the slot replaces the earlier one"],
125
148
  ["ahub task cancel <id> --reason <text> [--superseded-by <ref>] [--revision N] [--json] [--color=auto|always|never]", "the person, or an agent on its own task as hub_task_cancel allows: close obsolete work with a reason; retain its history without stopping native work or releasing dependents; eligibility follows the task-board policy"],
126
149
  ["ahub task label <id> ok|regressed|reverted|incomplete|wrong|abandoned [--created <time>]", "your later verdict on an approved task, kept in the research records (research must be on); an agent labels only a task it owns, and its record names it; --created is the person's"],
127
- ["ahub review <id> approved|changes_requested [note...] [--unmet <item>]... [--head <sha>] [--findings <json>]", "give a review verdict on a task; the person can do the same in ahub console: Tasks, select the task, r, then a (approve) or c (request changes, with a note)"],
150
+ ["ahub review <id> approved|changes_requested [note...] [--unmet <item>]... [--head <sha>] [--findings <json>] [--security-pass <json>]", "give a review verdict on a task; the person can do the same in ahub console: Tasks, select the task, r, then a (approve) or c (request changes, with a note)"],
128
151
  ["ahub review brief <id>", "print the review brief of a task's commit: reviewable and excluded files, rules, coverage to account for"],
129
152
  ["ahub route explain <id>", "why a task went where it went, its reserved owner and the planner walk included"],
130
153
  ["ahub route explain --class <c> <title...>", "what would happen to such a task now"],
@@ -132,14 +155,14 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
132
155
  ["ahub remember <text...>", "save a note to the memory all agents share"],
133
156
  ]],
134
157
  ["Budget", [
135
- ["ahub budget [--json] [--full] [--color=auto|always|never]", "quota windows per peer with each number's kind (native, count, manual) and source, why a peer shows no number, and who is paused until when"],
158
+ ["ahub budget [--json] [--full] [--color=auto|always|never]", "quota windows per peer with each number's kind (native, count, manual) and source, why a peer shows no number, who is paused until when, and the reviewer quota admission rule"],
136
159
  ["ahub budget set <peer> <0..1> [--resets-in 30m] [--window 5h|week]", "feed a reading by hand (also: test the relay)"],
137
160
  ["ahub budget resume <peer>", "override a budget pause; readings are ignored for that peer until the window resets"],
138
161
  ["ahub budget execution status [id] [--json] [--color=auto|always|never]", "read execution counters and limits"],
139
162
  ["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"],
140
163
  ]],
141
164
  ["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"],
165
+ [`ahub guidance probe ${Object.values(GUIDANCE_PROBE_USAGE).join(" | ")}`, "person or configured conductor only: bounded T1 declaration and fake-only probe lifecycle; receipts reads the sealed receipts, the outcome denominator and the comparability reasons, read-only; production execution is unavailable"],
143
166
  ["ahub guidance create --file JSON [--json]", "record a bounded immutable advisory proposal through current task authority; no activation or probe"],
144
167
  ["ahub guidance list --task N --task-created MS [--cursor TOKEN] [--json]", "bounded guidance metadata pages; withdrawn history and withheld fields remain explicit"],
145
168
  ["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"],
@@ -234,6 +257,38 @@ export function renderHelp(columns: number, color: boolean, command?: string, de
234
257
  return lines.map(line => paint(line, color)).join("\n");
235
258
  }
236
259
 
260
+ /** Split a usage at its top-level " | " only: a pipe inside [...] or <...> belongs to one alternative (`[--class <c> | <class>]`). */
261
+ function topLevelPieces(usage: string): string[] {
262
+ // Blank out each bracketed or angled group (same length), split the blanked text at " | ", and cut the real usage at the same widths.
263
+ const blanked = usage.replace(/\[[^\]]*\]|<[^>]*>|\([^)]*\)/g, group => " ".repeat(group.length));
264
+ const pieces: string[] = [];
265
+ let rest = usage;
266
+ for (const part of blanked.split(" | ")) { pieces.push(rest.slice(0, part.length).trim()); rest = rest.slice(part.length + " | ".length); }
267
+ return pieces;
268
+ }
269
+
270
+ /** The subcommand pieces a command documents, each with the words that name it: `ahub task show <id> | escalate <id>` has show and escalate. */
271
+ function subcommandPieces(command: string): { subs: string[]; usage: string }[] {
272
+ return HELP.filter(entry => helpCommands(entry).includes(command)).flatMap(entry => {
273
+ const prefix = COMMAND.exec(entry.usage)?.[0] ?? "";
274
+ return topLevelPieces(entry.usage).map((piece, index) => {
275
+ const body = index === 0 ? piece.slice(prefix.length).trim() : piece;
276
+ const token = body.split(/\s/)[0]!.replace(/[\[\]]/g, "");
277
+ return { subs: token.split("|").filter(word => /^[a-z][a-z0-9-]*$/.test(word)), usage: `ahub ${command} ${body}` };
278
+ });
279
+ });
280
+ }
281
+
282
+ /** #1433: whether the help lists `ahub <command> <sub>`, so `ahub <command> <sub> --help` asks for help instead of running it. Free text is never a listed subcommand: `ahub say try ls -h` stays a message. */
283
+ export function listsSubcommand(command: string, sub: string): boolean {
284
+ return subcommandPieces(command).some(piece => piece.subs.includes(sub));
285
+ }
286
+
287
+ /** The documented usage line of one subcommand, for a refusal that names it. */
288
+ export function subcommandUsage(command: string, sub: string): string | undefined {
289
+ return subcommandPieces(command).find(piece => piece.subs.includes(sub))?.usage;
290
+ }
291
+
237
292
  /** Body-free configured command guidance; no native argv or environment values enter help. */
238
293
  export function configuredAcpHelp(kind: string): string {
239
294
  return `ahub ${kind} [--mode headless] [--as <instance>] [--session-id <id>] [--print-command | --dry-run]\nConfigured ACP runs headless through the hub, with native permissions and NO hub sandbox.\nDeclare it in untracked .agenthub/config.local.json, restart the hub, then enable roster.${kind}.\nPreview withholds native argv and starts nothing. Native/model overrides and --unattended are refused.`;
@@ -15,8 +15,10 @@ 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 === "sdlc" && args[0] === "configure") return true;
18
19
  if (command === "lineage" && args[0] === "link") return true;
19
20
  if (command === "guidance" && ["create", "withdraw"].includes(args[0] ?? "")) return true;
21
+ if (command === "sdlc" && args[0] === "survey" && args[1] !== "show") return true;
20
22
  if (command === "model") return true; // #1317: even listing runtime overrides is person-only, never live-test delegated.
21
23
  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;
22
24
  if (args.some(arg => arg === "--as-user" || arg.startsWith("--as-user="))) return true;
@@ -97,12 +99,14 @@ const peerReadForms: Readonly<Record<string, Readonly<Record<string, PeerReadFor
97
99
  room: { list: { displayFlags: ["--json"] }, status: { positional: 1, displayFlags: ["--json"] } },
98
100
  queue: { list: { valueFlags: ["--peer"], displayFlags: [...publicReadDisplayFlags, "--all"] } },
99
101
  roster: { "": { displayFlags: publicReadDisplayFlags } },
102
+ // #1411 T2: who holds which flow role, read from the running hub; nothing else takes this command.
103
+ roles: { "": { displayFlags: sdlcReadDisplayFlags } },
100
104
  settings: { "": { displayFlags: ["--json"] }, list: { displayFlags: ["--json"] }, get: { positional: 1, minimum: 1, displayFlags: ["--json"] } },
101
105
  // #814 renders these reads for people and keeps JSON as an explicit data format.
102
106
  sdlc: { status: { positional: 1, displayFlags: sdlcReadDisplayFlags }, explain: { positional: 1, displayFlags: sdlcReadDisplayFlags }, queue: { positional: 1, minimum: 1, displayFlags: sdlcReadDisplayFlags }, release: { positional: 33, minimum: 1, displayFlags: sdlcReadDisplayFlags } },
103
107
  release: { show: { positional: 1, minimum: 1, displayFlags: [] } },
104
108
  // #601: reading a campaign is harmless for any agent (the hub stubs a private one); draft, revise, approve and close fall to `console`.
105
- study: { show: { positional: 1, valueFlags: ["--after"], displayFlags: sdlcReadDisplayFlags }, experiments: { valueFlags: ["--campaign", "--attempt", "--after", "--events-after", "--plan", "--baseline", "--variant"], displayFlags: sdlcReadDisplayFlags } },
109
+ study: { evidence: { positional: 1, minimum: 1, valueFlags: ["--revision"], displayFlags: sdlcReadDisplayFlags }, show: { positional: 1, valueFlags: ["--after"], displayFlags: sdlcReadDisplayFlags }, experiments: { valueFlags: ["--campaign", "--attempt", "--after", "--events-after", "--plan", "--baseline", "--variant"], displayFlags: sdlcReadDisplayFlags } },
106
110
  projects: { "": {} },
107
111
  models: { status: {} },
108
112
  recovery: { status: { positional: 1 } },
@@ -157,7 +161,7 @@ export function classifyPeerCommand(command: string, args: readonly string[], ca
157
161
  if (command === "stop") return "console";
158
162
  if (command === "sdlc" && ["release-guard", "release-guard-hook"].includes(args[0] ?? "")) return "allowed";
159
163
  // #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";
164
+ if (command === "sdlc" && ["merge", "authorize-release", "adopt-merge", "configure"].includes(args[0] ?? "")) return "conductor";
161
165
  if (command === "role") return ["list", "show"].includes(args[0] ?? "") ? "allowed" : "console";
162
166
  // The original tools identity reaches Tasks for read visibility or task-scoped link admission.
163
167
  if (command === "lineage") return ["show", "link"].includes(args[0] ?? "") ? "allowed" : "console";
@@ -201,6 +205,8 @@ export function classifyPeerCommand(command: string, args: readonly string[], ca
201
205
 
202
206
  /** No argument text is included: notices and refusal logs must not copy task text or credentials. */
203
207
  export function cliCommandLabel(command: string, args: readonly string[], catalog?: ProjectAdapterCatalog): string {
208
+ if (command === "sdlc" && args[0] === "configure") return "sdlc configure";
209
+ if (command === "sdlc" && args[0] === "survey") return ["start", "show"].includes(args[1] ?? "") ? `sdlc survey ${args[1]}` : "sdlc survey";
204
210
  if (command === "lineage") return ["show", "link"].includes(args[0] ?? "") ? `lineage ${args[0]}` : "lineage";
205
211
  if (command === "guidance") return ["create", "list", "show", "withdraw"].includes(args[0] ?? "") ? `guidance ${args[0]}` : "guidance";
206
212
  if (command === "model") return ["list", "set", "clear"].includes(args[0] ?? "") ? `model ${args[0]}` : "model";
@@ -221,7 +227,7 @@ export function cliCommandLabel(command: string, args: readonly string[], catalo
221
227
  if (command === "learn") return ["list", "accept", "reject"].includes(args.find(arg => arg !== "--json") ?? "") ? `learn ${args.find(arg => arg !== "--json")}` : "learn";
222
228
  if (command === "source") return ["add", "list"].includes(args.find(arg => arg !== "--json") ?? "") ? `source ${args.find(arg => arg !== "--json")}` : "source";
223
229
  // #601: a campaign id and a contract path are text the person chose, so the audit names the subcommand only.
224
- if (command === "study") return ["draft", "revise", "approve", "close", "show", "experiments"].includes(args[0] ?? "") ? `study ${args[0]}` : "study";
230
+ if (command === "study") return ["draft", "revise", "approve", "close", "show", "experiments", "evidence", "check"].includes(args[0] ?? "") ? `study ${args[0]}` : "study";
225
231
  if (command === "release") return ["new", "list", "show", "plan", "activate", "freeze", "ship", "drop"].includes(args[0] ?? "") ? `release ${args[0]}` : "release";
226
232
  // #1084: `autonomy`, `deliverables` and `usage` were missing from the table below, so a refusal and its audit line named them "unknown". Operands (a flag value, a task id) never reach the label.
227
233
  if (command === "autonomy") { const sub = args.find(arg => !arg.startsWith("--")); return sub !== undefined && ["on", "off", "status"].includes(sub) ? `autonomy ${sub}` : "autonomy"; }
@@ -233,7 +239,7 @@ export function cliCommandLabel(command: string, args: readonly string[], catalo
233
239
  if (command === "specs") return ["list", "check", "covers", "stamp"].includes(args[0] ?? "") ? `specs ${args[0]}` : "specs";
234
240
  // #1057: the audit names the subcommand and whether it confirms, never a path, a branch or a fingerprint.
235
241
  if (command === "worktrees") return args[0] === "tidy" ? (args.some(arg => arg === "--confirm" || arg.startsWith("--confirm=")) ? "worktrees tidy confirm" : "worktrees tidy") : "worktrees";
236
- if (!(catalog?.definitionOf(command) ?? definitionOf(command)) && !["upgrade", "restart", "recovery", "recovery-run", "help", "--help", "--version", "version", "completion", "projects", "ui", "manager", "setup", "init", "daemon", "up", "console", "stop", "models", "say", "queue", "tail", "watch", "budget", "board", "task", "review", "remember", "ask", "route", "pause", "resume", "permit", "answer", "permission", "results", "settings", "roster", "status", "pet", "logs", "export", "report", "research", "memory", "goal", "bench", "sdlc", "role", "facts", "check-path", "turns", "undo", "kill", "down", "reset", "doctor", "agents", "source", "broker", "schedule", "intake", "learn", "study"].includes(command)) return "unknown";
242
+ if (!(catalog?.definitionOf(command) ?? definitionOf(command)) && !["upgrade", "restart", "recovery", "recovery-run", "help", "--help", "--version", "version", "completion", "projects", "ui", "manager", "setup", "init", "daemon", "up", "console", "stop", "roles", "models", "say", "queue", "tail", "watch", "budget", "board", "task", "review", "remember", "ask", "route", "pause", "resume", "permit", "answer", "permission", "results", "settings", "roster", "status", "pet", "logs", "export", "report", "research", "memory", "goal", "bench", "sdlc", "role", "facts", "check-path", "turns", "undo", "kill", "down", "reset", "doctor", "agents", "source", "broker", "schedule", "intake", "learn", "study"].includes(command)) return "unknown";
237
243
  if (["task", "queue", "budget", "route", "recovery", "models", "projects", "research", "memory", "goal", "bench", "agents", "roster", "settings"].includes(command)) {
238
244
  const sub = command === "bench" || command === "memory" || command === "goal" ? args.find((arg) => arg !== "--json") : args[0];
239
245
  if (sub && ["propose", "show", "assign", "unassign", "escalate", "cancel", "claim", "label", "list", "add", "resolve", "resume", "set", "execution", "explain", "status", "abort", "dispose", "reattach", "setup", "start", "stop", "remove", "discard", "export", "backfill", "addons", "run", "report", "compare", "search", "graph", "promote", "demote", "forget", "supersede", "dedupe", "decay", "rebuild", "sync", "machine", "import", "suggestions", "confirm", "reject", "new", "link", "state", "done", "take", "trust"].includes(sub)) return `${command} ${sub}`;
@@ -10,13 +10,14 @@
10
10
  * Who is offered it is decided by `promptGate`: a person at a terminal, on a new project, with no setting flag and no `--yes`. A delegated peer, a live test and any run without a
11
11
  * terminal never reach `runInitPrompt` and get defaults plus their flags (AC5).
12
12
  */
13
- import { INIT_SETTINGS, SDLC_MODES, SPEC_REVIEW_MODES, COORDINATION_MODES, AUTONOMY_CHOICES, type InitSettingRow, type InitSettingsRequest } from "./init-settings.ts";
13
+ import { INIT_SETTINGS, TRACK_CONFIG, SDLC_MODES, SPEC_REVIEW_MODES, COORDINATION_MODES, AUTONOMY_CHOICES, type InitSettingRow, type InitSettingsRequest } from "./init-settings.ts";
14
14
  import { readFileSync } from "node:fs";
15
15
  import { join } from "node:path";
16
16
  import { PROFILE_NAMES } from "../hub/profiles.ts";
17
17
  import { DEFAULT_CONFIG } from "../hub/daemon.ts";
18
18
  import { DEFAULT_SPECS_CONFIG } from "../hub/specs-config.ts";
19
19
  import { START_AGENTS_ALLOWED, START_AGENTS_DEFAULT } from "../hub/start-agents.ts";
20
+ import { NO_CONDUCTOR, PERSON_REVIEWS, ROLE_FLAGS, eligiblePeers, parseRoleFlag, roleKeyOf, type RoleFlag } from "./init-roles.ts";
20
21
 
21
22
  /** What a prompt needs from its surroundings. `ask` resolves to `null` at the end of input and after Ctrl-C (the caller turns both into `null`); it never throws for either. */
22
23
  export interface InitPromptPorts {
@@ -31,7 +32,7 @@ export interface InitAnswers { request: InitSettingsRequest; profile?: string; s
31
32
  export type InitPromptResult = { ok: true; answers: InitAnswers } | { ok: false; reason: "declined" | "interrupted" | "refused"; message: string };
32
33
 
33
34
  /** The four questions that are choices of `ahub init` but not rows of the settings table. */
34
- const NOT_ROWS: ReadonlySet<string> = new Set(["profile", "autonomy", "release-guard", "shadow"]);
35
+ const NOT_ROWS: ReadonlySet<string> = new Set(["profile", TRACK_CONFIG, "autonomy", "release-guard", "shadow", ...Object.values(ROLE_FLAGS).map(roleKeyOf)]);
35
36
  const MAX_TRIES = 3;
36
37
  const NOTHING = "nothing was written";
37
38
  const yes = (text: string) => /^(y|yes)$/i.test(text.trim());
@@ -92,6 +93,8 @@ export interface InitQuestionContext {
92
93
  discoverChecks?: () => Promise<readonly string[]>;
93
94
  /** Shadow history is offered only for a folder with no Git work tree. */
94
95
  shadowAvailable?: boolean;
96
+ /** The peers whose agent CLI is on this machine, offered first in the role questions (#1408). */
97
+ installedPeers?: readonly string[];
95
98
  }
96
99
 
97
100
  /**
@@ -109,10 +112,29 @@ export function initQuestions(context: InitQuestionContext = {}): InitQuestion[]
109
112
  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",
110
113
  read: text => INIT_SETTINGS.find(row => row.id === "start.agents")!.parse(text.trim().toLowerCase()),
111
114
  };
115
+ // #1408 T2: one question per role, with only the peers that can hold it (a new project has no start modes yet, so each kind is judged in its own default form). Installed agents come first.
116
+ const roleQuestion = (flag: RoleFlag): InitQuestion => {
117
+ const role = ROLE_FLAGS[flag], peers = eligiblePeers(role, () => undefined, context.installedPeers ?? []);
118
+ const shown = shippedHolders(role);
119
+ return {
120
+ id: roleKeyOf(role), label: role === "conductor" ? "Conductor (reports to you, asks for your decisions; needs an interactive peer)" : role === "planner" ? "Planner" : "Reviewer",
121
+ choices: role === "conductor" ? [...peers, NO_CONDUCTOR].join("|") : role === "reviewer" ? `${peers.join(",")} as a comma list, or ${PERSON_REVIEWS}` : `${peers.join(",")} as a comma list`, shown,
122
+ read: text => {
123
+ const choice = parseRoleFlag(flag, text.trim().toLowerCase());
124
+ const named = choice === NO_CONDUCTOR || choice === PERSON_REVIEWS ? [] : Array.isArray(choice) ? choice : [choice];
125
+ const refused = named.find(peer => !peers.includes(peer));
126
+ if (refused !== undefined) throw new Error(`${refused} cannot be ${role} here; answer ${role === "conductor" ? [...peers, NO_CONDUCTOR].join(", ") : peers.join(", ")}`);
127
+ return choice;
128
+ },
129
+ };
130
+ };
112
131
  const switches = INIT_SETTINGS.filter(row => row.id.endsWith(".enabled") && !["specs.enabled", "memory.enabled", "research.enabled", "snapshots.enabled"].includes(row.id));
113
132
  const all: InitQuestion[] = [
114
133
  profile,
115
134
  agents,
135
+ roleQuestion("--conductor"), roleQuestion("--planner"), roleQuestion("--reviewer"),
136
+ // #1411: Enter leaves the choice out, so .gitignore stays as git has it today and the block follows that.
137
+ { ...onOff(TRACK_CONFIG, "Commit the shared hub config (config.json, routing.toml, sdlc.toml) to git", "off"), shown: "as .gitignore has it" },
116
138
  onOff("specs.enabled", "Design specs and their freshness checks", shownDefault("specs.enabled") as "on" | "off"),
117
139
  oneOf("specs.review", "Spec review mode", SPEC_REVIEW_MODES, shownDefault("specs.review")),
118
140
  oneOf("sdlc.mode", "SDLC mode", SDLC_MODES, shownDefault("sdlc.mode")),
@@ -129,6 +151,13 @@ export function initQuestions(context: InitQuestionContext = {}): InitQuestion[]
129
151
  return all.filter(question => NOT_ROWS.has(question.id) || ids.has(question.id));
130
152
  }
131
153
 
154
+ /** Who holds `role` in the shipped `templates/config.json` (what Enter keeps), or `none` when nobody does: read from the template so the bracket cannot drift from what is written. */
155
+ function shippedHolders(role: "conductor" | "planner" | "reviewer"): string {
156
+ const roles = at(TEMPLATE, ["roles"]);
157
+ const holders = roles && typeof roles === "object" ? Object.entries(roles as Record<string, unknown>).filter(([, list]) => Array.isArray(list) && list.includes(role)).map(([peer]) => peer) : [];
158
+ return holders.join(", ") || (role === "reviewer" ? PERSON_REVIEWS : "none");
159
+ }
160
+
132
161
  /** The question line: `label (a|b|c) [default]: `. */
133
162
  export const questionLine = (question: InitQuestion): string => `${question.label} (${question.choices}) [${question.shown}]: `;
134
163
 
@@ -0,0 +1,156 @@
1
+ /**
2
+ * #1408 T2 (R3): who conducts, plans and reviews, chosen at `ahub init`. Three independent choices, each one flag and one guided question:
3
+ *
4
+ * --conductor <peer>|none --planner <peer>[,<peer>...] --reviewer <peer>[,<peer>...]|person
5
+ *
6
+ * Pure: no file is read or written. `parseRoleFlag` checks a flag's shape; `planRoles` takes the parsed shared and local config and returns the `roles` entries that change, or throws the
7
+ * refusal (the reason from `roleEligibility` and the eligible alternatives) before anything is written. Only conductor, planner and reviewer move: implementer, verifier and every catalog
8
+ * role stay as they are. A peer whose roles change is written as one explicit list, including the peer that loses a role, because `roles` merges per peer and a missing entry keeps the default.
9
+ */
10
+ import { SUPPORTED_PEERS, defaultPeerRoles, definitionOf } from "../adapters/registry.ts";
11
+ import { roleEligibility, type EligibleRole } from "../adapters/role-eligibility.ts";
12
+ import { START_MODES, type StartMode } from "../hub/start-mode.ts";
13
+
14
+ export const ROLE_FLAGS = { "--conductor": "conductor", "--planner": "planner", "--reviewer": "reviewer" } as const satisfies Record<string, EligibleRole>;
15
+ export type RoleFlag = keyof typeof ROLE_FLAGS;
16
+ /** The request keys the three choices use in `InitSettingsRequest.values`. */
17
+ export const ROLE_KEYS = ["roles.conductor", "roles.planner", "roles.reviewer"] as const;
18
+ export type RoleKey = typeof ROLE_KEYS[number];
19
+ export const roleKeyOf = (role: EligibleRole): RoleKey => `roles.${role}`;
20
+
21
+ /** `none` as the conductor and `person` as the reviewer are choices, not peers: the person conducts from `ahub console`, and reviews go to the person. */
22
+ export const NO_CONDUCTOR = "none", PERSON_REVIEWS = "person";
23
+ /** The value of a choice: a peer or `none` (conductor), a list of peers (planner), a list of peers or `person` (reviewer). */
24
+ export type RoleChoice = string | string[];
25
+
26
+ /** The most planners a project can name; the loader refuses a longer `planner` list. */
27
+ const MAX_PLANNERS = 8;
28
+ /** What a flag accepts, for a refusal and for help. */
29
+ export const ROLE_ALLOWED: Record<RoleFlag, string> = {
30
+ "--conductor": "a peer or none",
31
+ "--planner": "a peer, or a comma-separated list of peers",
32
+ "--reviewer": "a peer, a comma-separated list of peers, or person",
33
+ };
34
+ const CANONICAL = ["planner", "implementer", "verifier", "reviewer", "conductor"] as const;
35
+ const nothing = "nothing was written";
36
+
37
+ const isPeer = (word: string) => (SUPPORTED_PEERS as readonly string[]).includes(word);
38
+ const clip = (text: string) => JSON.stringify(text.slice(0, 48));
39
+
40
+ /** A flag's text into its choice, or a refusal that names what is accepted. The eligibility of a peer is judged by `planRoles`, which sees the files. */
41
+ export function parseRoleFlag(flag: RoleFlag, text: string): RoleChoice {
42
+ const words = text.split(/[\s,]+/).map(word => word.trim().toLowerCase()).filter(Boolean);
43
+ const allowed = `${flag} takes ${ROLE_ALLOWED[flag]}; peers are ${SUPPORTED_PEERS.join(", ")}`;
44
+ if (!words.length) throw new Error(`${flag} needs a value: ${allowed}; ${nothing}`);
45
+ if (flag === "--conductor") {
46
+ if (words.length !== 1) throw new Error(`${flag}: at most one conductor; ${allowed}; ${nothing}`);
47
+ if (words[0] === NO_CONDUCTOR || isPeer(words[0]!)) return words[0]!;
48
+ throw new Error(`${flag}: ${clip(text)} is not a peer or none; ${allowed}; ${nothing}`);
49
+ }
50
+ if (flag === "--reviewer" && words.includes(PERSON_REVIEWS)) {
51
+ if (words.length !== 1) throw new Error(`${flag}: person stands alone (reviews go to the person); name peers or person, not both; ${nothing}`);
52
+ return PERSON_REVIEWS;
53
+ }
54
+ const unknown = words.find(word => !isPeer(word));
55
+ if (unknown !== undefined) throw new Error(`${flag}: ${clip(unknown)} is not a peer; ${allowed}; ${nothing}`);
56
+ if (new Set(words).size !== words.length) throw new Error(`${flag}: a peer is named twice; ${nothing}`);
57
+ if (flag === "--planner" && words.length > MAX_PLANNERS) throw new Error(`${flag}: at most ${MAX_PLANNERS} planners; ${nothing}`);
58
+ return words;
59
+ }
60
+
61
+ /** The peers `role` may go to, given each peer's start mode (`undefined`: the kind's own default form). Installed agents come first, each group in registry order. */
62
+ export function eligiblePeers(role: EligibleRole, startMode: (peer: string) => StartMode | undefined = () => undefined, installed: readonly string[] = []): string[] {
63
+ const ok = SUPPORTED_PEERS.filter(peer => roleEligibility(peer, role, startMode(peer)).eligible);
64
+ return [...ok.filter(peer => installed.includes(peer)), ...ok.filter(peer => !installed.includes(peer))];
65
+ }
66
+
67
+ /** The peers whose agent CLI is on PATH, by the command each adapter definition names. A hub-owned peer (the local worker, `trust.onPrem`) runs inside the hub and needs no CLI. */
68
+ export function installedPeers(which: (binary: string) => string | null | undefined = binary => Bun.which(binary)): string[] {
69
+ return SUPPORTED_PEERS.filter(peer => {
70
+ const definition = definitionOf(peer);
71
+ return definition?.trust.onPrem === true || (!!definition && !!which(definition.cli.command));
72
+ });
73
+ }
74
+
75
+ const isObject = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
76
+ const listOf = (value: unknown): string[] | undefined => Array.isArray(value) && value.every(item => typeof item === "string") ? [...value] : undefined;
77
+ /** The effective start mode of a peer in the two files: `config.local.json` wins over the shared file, as the loader reads them. */
78
+ export function startModeIn(peer: string, shared: Record<string, unknown>, local: Record<string, unknown>): StartMode | undefined {
79
+ for (const doc of [local, shared]) {
80
+ const mode = isObject(doc.peers) && isObject(doc.peers[peer]) ? (doc.peers[peer] as { start_mode?: unknown }).start_mode : undefined;
81
+ if ((START_MODES as readonly unknown[]).includes(mode)) return mode as StartMode;
82
+ }
83
+ return undefined;
84
+ }
85
+ /** The roles a peer holds now: its entry in the shared file, else the adapter default (a peer left out of `roles` keeps its default). */
86
+ export function effectiveRoles(peer: string, shared: Record<string, unknown>): string[] {
87
+ return (isObject(shared.roles) ? listOf(shared.roles[peer]) : undefined) ?? defaultPeerRoles(true)[peer] ?? [];
88
+ }
89
+
90
+ export interface RoleChange { peer: string; from: string[]; to: string[] }
91
+
92
+ /** The refusal for a peer that cannot take the role: the reason and fix from `roleEligibility`, and who can. */
93
+ function refusal(flag: RoleFlag, peer: string, role: EligibleRole, startMode: StartMode | undefined, alternatives: readonly string[]): Error {
94
+ const verdict = roleEligibility(peer, role, startMode);
95
+ const others = alternatives.length ? `eligible: ${alternatives.join(", ")}` : `no peer can hold ${role} here`;
96
+ return new Error(`${flag} ${peer}: ${verdict.reason}; ${verdict.fix}; ${others}; ${nothing}`);
97
+ }
98
+
99
+ /**
100
+ * The `roles` entries the choices change, given the parsed shared and local config. A choice that is not given changes nothing; one that already holds changes nothing. Refuses, before any write:
101
+ * a peer that cannot hold the role (its reason, its fix and the eligible peers), a peer whose roles `config.local.json` overrides (the shared write would not take effect), and a planner choice
102
+ * while a `planner` setting is present (it outranks the roles).
103
+ */
104
+ export function planRoles(choices: Partial<Record<RoleKey, unknown>>, shared: Record<string, unknown>, local: Record<string, unknown>): RoleChange[] {
105
+ const startMode = (peer: string) => startModeIn(peer, shared, local);
106
+ const peers = new Set<string>([...SUPPORTED_PEERS, ...(isObject(shared.roles) ? Object.keys(shared.roles) : [])]);
107
+ const held = new Map<string, Set<string>>([...peers].map(peer => [peer, new Set(effectiveRoles(peer, shared))]));
108
+ const give = (role: EligibleRole, to: readonly string[]) => {
109
+ for (const roles of held.values()) roles.delete(role);
110
+ for (const peer of to) (held.get(peer) ?? held.set(peer, new Set()).get(peer)!).add(role);
111
+ };
112
+ const check = (flag: RoleFlag, role: EligibleRole, named: readonly string[]) => {
113
+ for (const peer of named) if (!roleEligibility(peer, role, startMode(peer)).eligible) throw refusal(flag, peer, role, startMode(peer), eligiblePeers(role, startMode));
114
+ };
115
+ const conductor = choices["roles.conductor"], planner = choices["roles.planner"], reviewer = choices["roles.reviewer"];
116
+ if (conductor !== undefined) {
117
+ const named = conductor === NO_CONDUCTOR ? [] : [String(conductor)];
118
+ check("--conductor", "conductor", named);
119
+ give("conductor", named);
120
+ }
121
+ if (planner !== undefined) {
122
+ const named = planner as string[];
123
+ check("--planner", "planner", named);
124
+ if (shared.planner !== undefined || local.planner !== undefined) throw new Error(`--planner: a planner setting is present in .agenthub/config.json or config.local.json and outranks roles; remove that key (or set it with ahub settings set planner), then run ahub init again; ${nothing}`);
125
+ give("planner", named);
126
+ }
127
+ if (reviewer !== undefined) {
128
+ const named = reviewer === PERSON_REVIEWS ? [] : reviewer as string[];
129
+ check("--reviewer", "reviewer", named);
130
+ give("reviewer", named);
131
+ }
132
+ const rank = (role: string) => { const at = CANONICAL.indexOf(role as typeof CANONICAL[number]); return at === -1 ? CANONICAL.length : at; };
133
+ const changes: RoleChange[] = [];
134
+ for (const [peer, roles] of held) {
135
+ const from = effectiveRoles(peer, shared);
136
+ // The roles the peer keeps stay in the order the file has them; a role it gains follows, in the canonical order.
137
+ const to = [...from.filter(role => roles.has(role)), ...[...roles].filter(role => !from.includes(role)).sort((a, b) => rank(a) - rank(b))];
138
+ if (to.length === from.length && to.every(role => from.includes(role))) continue;
139
+ changes.push({ peer, from, to });
140
+ }
141
+ const overridden = isObject(local.roles) ? changes.filter(change => Object.hasOwn(local.roles as object, change.peer)) : [];
142
+ if (overridden.length) throw new Error(`config.local.json roles.${overridden[0]!.peer} overrides the shared roles for ${overridden[0]!.peer}, so the choice would not take effect; change it there (or remove that entry), then run ahub init again; ${nothing}`);
143
+ return changes;
144
+ }
145
+
146
+ /** What each choice means, in the words of the init summary. Printed after the writes, and for a choice that changed nothing too. */
147
+ export function roleSummaryLines(choices: Partial<Record<RoleKey, unknown>>): string[] {
148
+ const lines: string[] = [];
149
+ const conductor = choices["roles.conductor"], planner = choices["roles.planner"], reviewer = choices["roles.reviewer"];
150
+ if (conductor === NO_CONDUCTOR) lines.push("- Conductor: none. You conduct from ahub console.");
151
+ else if (typeof conductor === "string") lines.push(`- Conductor: ${conductor}. It must run interactively; ahub doctor shows who holds each role.`);
152
+ if (Array.isArray(planner)) lines.push(`- Planner: ${planner.join(", ")}.`);
153
+ if (reviewer === PERSON_REVIEWS) lines.push("- Reviewer: person. No peer holds the reviewer role, so reviews go to you.");
154
+ else if (Array.isArray(reviewer)) lines.push(`- Reviewer: ${reviewer.join(", ")}.`);
155
+ return lines;
156
+ }
@@ -9,6 +9,7 @@
9
9
  import { checkStartAgents, START_AGENTS_ALLOWED } from "../hub/start-agents.ts";
10
10
  import { editSdlcText } from "../hub/config-edit.ts";
11
11
  import { ADAPTERS } from "../adapters/registry.ts";
12
+ import { ROLE_ALLOWED, ROLE_FLAGS, ROLE_KEYS, parseRoleFlag, planRoles, roleKeyOf, type RoleFlag } from "./init-roles.ts";
12
13
 
13
14
  export type InitSettingFile = "config.json" | "config.local.json" | "sdlc.toml";
14
15
  export const SDLC_MODES = ["off", "advise", "enforce"] as const;
@@ -76,10 +77,12 @@ export interface InitSettingsRequest {
76
77
  }
77
78
 
78
79
  /** The usage line `ahub init` prints for a bad argument; help.ts shows the same flags. */
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]";
80
+ 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] [--conductor <peer>|none] [--planner <a,b,...>] [--reviewer <a,b,...>|person] [--track-config|--no-track-config] [--autonomy inherit|off] [--shadow] [--release-guard] [--yes] [--dry-run --json]";
80
81
 
81
82
  /** Every flag the table and the two non-key choices own, for the caller's own argument loop and for help. */
82
- export const INIT_SETTING_FLAGS: readonly string[] = [...INIT_SETTINGS.flatMap(row => row.flags.map(flag => flag.flag)), "--autonomy"];
83
+ export const INIT_SETTING_FLAGS: readonly string[] = [...INIT_SETTINGS.flatMap(row => row.flags.map(flag => flag.flag)), "--track-config", "--no-track-config", "--autonomy", ...Object.keys(ROLE_FLAGS)];
84
+ /** #1411: the request key of `--track-config` / `--no-track-config` (true / false); absent keeps what git says today. */
85
+ export const TRACK_CONFIG = "track-config";
83
86
 
84
87
  /**
85
88
  * Separates the setting flags from the rest of an `ahub init` argv. A value flag takes the next word; a switch takes none. A flag given twice with different
@@ -102,6 +105,16 @@ export function parseInitSettings(args: readonly string[]): { request: InitSetti
102
105
  request.autonomy = text as typeof AUTONOMY_CHOICES[number];
103
106
  continue;
104
107
  }
108
+ // #1411: whether the repository commits its hub config. Not a config key (init.ts reads it for .gitignore and the block's role sentence), but it rides in `values` so every
109
+ // caller that asks "was a setting given" sees it.
110
+ if (arg === "--track-config" || arg === "--no-track-config") { set(TRACK_CONFIG, arg, arg === "--track-config"); continue; }
111
+ // #1408 T2: who conducts, plans and reviews. Each is one request key; init-roles.ts judges eligibility against the files when the plan is made.
112
+ if (Object.hasOwn(ROLE_FLAGS, arg)) {
113
+ const text = args[++i];
114
+ if (text === undefined) throw new Error(`${arg} needs a value: ${ROLE_ALLOWED[arg as RoleFlag]}; nothing was written`);
115
+ set(roleKeyOf(ROLE_FLAGS[arg as RoleFlag]), arg, parseRoleFlag(arg as RoleFlag, text));
116
+ continue;
117
+ }
105
118
  const row = INIT_SETTINGS.find(def => def.flags.some(flag => flag.flag === arg));
106
119
  if (!row) { rest.push(arg); continue; }
107
120
  const flag = row.flags.find(entry => entry.flag === arg)!;
@@ -231,5 +244,14 @@ export function planInitSettings(request: InitSettingsRequest, texts: InitSettin
231
244
  next[file] = current[file]!;
232
245
  rows.push({ key: row.id, file, ...(held === undefined ? {} : { from: held }), to } as InitSettingRow);
233
246
  }
247
+ // #1408 T2: the role choices, judged against the config.json this plan produces and the local file; each peer whose roles change is written as one explicit list.
248
+ if (ROLE_KEYS.some(key => Object.hasOwn(request.values, key))) {
249
+ const changes = planRoles(request.values, parsed("config.json"), parsed("config.local.json"));
250
+ for (const change of changes) {
251
+ current["config.json"] = editJsonText(current["config.json"] ?? "{}\n", ["roles", change.peer], change.to);
252
+ rows.push({ key: `roles.${change.peer}`, file: "config.json", from: change.from, to: change.to });
253
+ }
254
+ if (changes.length) next["config.json"] = current["config.json"]!;
255
+ }
234
256
  return { rows, next };
235
257
  }