@staix/agent-hub 0.39.0 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +12 -6
  3. package/docs/adding-an-ai-tool.md +1 -1
  4. package/docs/agent-notes/README.md +7 -0
  5. package/docs/agent-notes/adapters.md +5 -3
  6. package/docs/agent-notes/benchmarks.md +2 -0
  7. package/docs/agent-notes/budget.md +1 -0
  8. package/docs/agent-notes/bus.md +1 -0
  9. package/docs/agent-notes/daemon.md +8 -3
  10. package/docs/agent-notes/local-worker.md +3 -1
  11. package/docs/agent-notes/security-review.md +1 -0
  12. package/docs/agent-notes/tasks.md +7 -2
  13. package/docs/agent-notes/tests.md +7 -7
  14. package/docs/contracts/companion-cli-v1.json +4 -0
  15. package/docs/design/adapters.md +91 -0
  16. package/docs/design/agent-hub-architecture.md +17 -0
  17. package/docs/design/agent-hub.md +10 -0
  18. package/docs/design/bus.md +7 -0
  19. package/docs/design/cli-output.md +183 -0
  20. package/docs/design/execution-reference.md +6 -1
  21. package/docs/design/roadmap.md +191 -0
  22. package/docs/design/task-board.md +34 -0
  23. package/docs/dogfood.md +11 -4
  24. package/docs/events.md +4 -4
  25. package/docs/memory.md +3 -3
  26. package/docs/operations.md +153 -41
  27. package/docs/profiles.md +1 -0
  28. package/docs/quickstart.md +17 -4
  29. package/docs/sdlc.md +3 -1
  30. package/docs/security.md +40 -4
  31. package/docs/verification/2026-11-14-codex-0169-reviewer-isolation.md +70 -0
  32. package/docs/verification/2026-11-14-codex-0169-reviewer-tool-call.md +48 -0
  33. package/docs/verification/2026-11-14-pi-152-compat.md +45 -0
  34. package/docs/verification/2026-11-15-0.40.0.md +39 -0
  35. package/docs/verification/2026-11-16-pi-loopback-1447.md +39 -0
  36. package/docs/verification/pi-152-model-free.ts +57 -0
  37. package/docs/verification/pi-152-native.mjs +21 -0
  38. package/docs/verified.json +22 -22
  39. package/package.json +3 -3
  40. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  41. package/plugins/agent-hub/kimi-hook.js +332 -89
  42. package/plugins/agent-hub/kimi-review-policy-worker.js +16 -11
  43. package/plugins/agent-hub/server.js +417 -160
  44. package/src/adapters/agy/definition.ts +1 -1
  45. package/src/adapters/claude-channel.ts +1 -1
  46. package/src/adapters/codex-review-isolation.ts +61 -17
  47. package/src/adapters/compat.ts +7 -7
  48. package/src/adapters/definitions/builtin-metadata.ts +6 -6
  49. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  50. package/src/adapters/definitions/native-config-policy.ts +1 -1
  51. package/src/adapters/definitions/qwen.ts +1 -1
  52. package/src/adapters/local-worker.ts +5 -3
  53. package/src/adapters/pi.ts +54 -11
  54. package/src/adapters/registry-types.ts +2 -1
  55. package/src/adapters/reviewer-print.ts +2 -1
  56. package/src/cli/answer-args.ts +11 -3
  57. package/src/cli/console-question.ts +1 -1
  58. package/src/cli/console-state.ts +95 -10
  59. package/src/cli/console.ts +6 -2
  60. package/src/cli/error-format.ts +19 -0
  61. package/src/cli/help.ts +290 -25
  62. package/src/cli/identity-audit.ts +8 -7
  63. package/src/cli/identity.ts +17 -0
  64. package/src/cli/init.ts +102 -9
  65. package/src/cli/main.js +2 -2
  66. package/src/cli/main.ts +57 -21
  67. package/src/cli/output-standard.ts +56 -0
  68. package/src/cli/output.ts +143 -8
  69. package/src/cli/roadmap.ts +215 -0
  70. package/src/cli/smoke-pty-bridge.ts +7 -24
  71. package/src/cli/task-output.ts +3 -1
  72. package/src/cli/upgrade-presentation-flags.ts +2 -2
  73. package/src/hub/board.ts +200 -3
  74. package/src/hub/bus.ts +9 -0
  75. package/src/hub/check-runner.ts +3 -4
  76. package/src/hub/ci-watch.ts +19 -4
  77. package/src/hub/control-client.ts +1 -1
  78. package/src/hub/daemon.ts +245 -43
  79. package/src/hub/events.ts +2 -2
  80. package/src/hub/execution-reference.ts +1 -1
  81. package/src/hub/github-import.ts +81 -0
  82. package/src/hub/hub-tools.ts +34 -9
  83. package/src/hub/install-policy.ts +23 -0
  84. package/src/hub/lifecycle-schema.ts +2 -2
  85. package/src/hub/no-writes.ts +3 -0
  86. package/src/hub/operational-authority.ts +3 -1
  87. package/src/hub/operational-view.ts +1 -1
  88. package/src/hub/pi-failure.ts +7 -0
  89. package/src/hub/question-desk.ts +26 -7
  90. package/src/hub/questions.ts +33 -5
  91. package/src/hub/restart.ts +7 -0
  92. package/src/hub/roadmap-triage.ts +86 -0
  93. package/src/hub/roadmap-unplaced.ts +169 -0
  94. package/src/hub/roadmap-view.ts +83 -0
  95. package/src/hub/roadmap.ts +127 -0
  96. package/src/hub/sdlc-merge.ts +5 -4
  97. package/src/hub/sdlc-queue.ts +3 -3
  98. package/src/hub/sdlc.ts +37 -2
  99. package/src/hub/specs-task.ts +7 -0
  100. package/src/hub/task-sweep.ts +29 -2
  101. package/src/hub/task-worktree.ts +37 -0
  102. package/src/hub/tasks.ts +381 -7
  103. package/src/pi/dependency-publish.ts +50 -0
  104. package/src/pi/extension.ts +1 -1
  105. package/src/pi/launch.ts +1 -1
  106. package/src/pi/task-dependencies.ts +249 -0
  107. package/src/ui/index.html +53 -13
  108. package/src/ui/plugin-questions.ts +5 -0
  109. package/src/ui/plugin.ts +6 -1
  110. package/templates/config.json +1 -1
package/src/cli/help.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import { ADAPTERS, deriveAdapterLists, type AdapterDefinition } from "../adapters/registry.ts";
2
2
  import { VERSION } from "../version.ts";
3
- import { paint, wrap, type Span } from "./console-state.ts";
3
+ import { ROADMAP_FORMS } from "./roadmap.ts";
4
+ import { paint, wrap, Report as LayoutReport, type Span } from "./console-state.ts";
4
5
 
5
6
  /** One usage form of `ahub help`: the usage starts with `ahub <command>`, alternatives joined by `|`. */
6
- export interface HelpEntry { section: string; usage: string; description: string }
7
+ export interface HelpEntry { section: string; usage: string; description: string; /** #1504: the overview row of a native agent, from the third element of its definition's `cli.usage` entry; never a table in this file that names a peer. */ summary?: string }
7
8
 
8
9
  /** #1405: one source for the probe usage, read by `ahub help` and by the refusal of a malformed probe command. */
9
10
  export const GUIDANCE_PROBE_USAGE = {
@@ -31,7 +32,7 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
31
32
  ["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"],
32
33
  ["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"],
33
34
  ["ahub --live-test [--project <path|id>] <command> [args...]", "user-authorized operational console delegation; ordinary calls retain peer identity; person-authored content refuses"],
34
- ["ahub help [command]", "this help, or one command's entries; also --help and -h"],
35
+ ["ahub help [command [--ascii]]", "this help, or one command's entries; also --help and -h"],
35
36
  ["ahub version | --version", "print the installed version"],
36
37
  ["ahub completion zsh|bash|fish", "print a shell completion script; its candidates come from these help entries"],
37
38
  ]],
@@ -40,6 +41,7 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
40
41
  ["ahub console [--panels] [--color=auto|always|never]", "enter the human console; P cycles built-in pet characters/off; exiting leaves the daemon running"],
41
42
  ["ahub console --no-pet", "turn off attention for this session; combines with --panels and --color"],
42
43
  ["ahub pet [--short]", "read attention without connecting; --short prints ahub!N only when action is needed"],
44
+ ["ahub pet --window [--close]", "retired floating-window options: run acon ui and open Mini"],
43
45
  ["ahub pet --palette <blue|teal|violet|ochre>", "retired floating-window option: run acon ui and open Mini"],
44
46
  ["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"],
45
47
  ["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"],
@@ -61,10 +63,10 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
61
63
  ["ahub sdlc costs [owner/repo] [--json] [--color=auto|always|never]", "read bounded planner cost metrics for linked merged PRs"],
62
64
  ["ahub sdlc metrics [--since <YYYY-MM-DD|ISO time>] [--json] [--color=auto|always|never]", "read SDLC metrics and control band tiers from board history (planner or person; read-only)"],
63
65
  ["ahub backlog groom | return <task> <revision> <reason...> [--reserved <peer> | --unreserve] [--json] [--color=auto|always|never]", "read grooming findings or return accepted untouched work to backlog (planner/person); --reserved names the peer the card is reserved for as it goes back, --unreserve clears the reservation (a person's reservation needs the person)"],
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"],
66
+ ["ahub status [--json] [--full] [--verbose] [--ascii] [--color=auto|always|never]", "is the hub OK, and what to do next: an Attention list (each item with its next command), then the hub, peers and tasks; --verbose or --full prints every detail (model backends, specs, queue pressure, schedules, per-peer notes)"],
65
67
  ["ahub status --all [--json] [--color=auto|always|never]", "show every registered project"],
66
68
  ["ahub logs [-f]", "person: last 100 hub.log lines (-f starts at 10); conductor: bounded public lines and follow while authority remains"],
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"],
69
+ ["ahub doctor [--json] [--full] [--ascii] [--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"],
68
70
  ["ahub doctor --stale-anchors [--json]", "read-only bounded report of public memory symbol anchors at current HEAD; private or unavailable evidence stays unknown"],
69
71
  ["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"],
70
72
  ["ahub agents [--json]", "show each gated agent CLI's installed version and verdict (verified, in-line, trusted, refused or unknown)"],
@@ -96,9 +98,9 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
96
98
  ["ahub tail", "live stream of messages, states and permission requests"],
97
99
  ["ahub permission [<peer> [ask|ask-when-needed|never-ask]] [--yes]", "human only: inspect or set a running peer mode; never-ask requires --yes; config never-ask waits for console y"],
98
100
  ["ahub permit <id> <option>", "answer a permission request shown by tail (\"deny\" cancels)"],
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)"],
101
+ ["ahub answer [<set> <question>=<option>[,<option>]... [--other [<question>=]<text>] [--instructed <quote>]] [--json] [--color=auto|always|never]", "without operands list open hub_ask questions; with them the person answers one set. Only the configured conductor may use --instructed on the person's explicit instruction in its own session (#1328); never its own set or a relayed instruction"],
100
102
  ["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"],
101
- ["ahub roster [--json] [--color=auto|always|never]", "every known peer, participation, start mode and retained work"],
103
+ ["ahub roster [list] [--json] [--color=auto|always|never]", "every known peer, participation, start mode and retained work"],
102
104
  ["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"],
103
105
  ["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"],
104
106
  ["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"],
@@ -119,6 +121,13 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
119
121
  ["ahub task propose [--class <c> | <class>] <title...> [--owner <peer>] [--path <p>]... [--after <id>]... [--urgent] [--needs-network] [--needs-worktree] [--backlog] [--detail <text>]", "put a task on the board; --needs-network keeps it away from a peer whose shell has none; --needs-worktree keeps it away from a sandboxed peer unless the hub can make the task worktree for it (it makes it, commits and pushes at done); a first word that names a class is taken as the class; while a task named by --after is not approved yet, --owner reserves the task for that peer, offered to it first once it is ready; otherwise --owner assigns it now"],
120
122
  ["ahub task handoff --list | --sync | --project <root|id> [<class>] <title...> [--path <p>]... [--issue <n>] [--task <n>] [--detail <text>] [--duplicate-ok <reason>] [--key <uuid>] [--json] [--color=auto|always|never]", "person only: register work that belongs to ANOTHER project that runs agent-hub on that project's board (an ownerless proposal its own roles take from there); the target must be registered and running, nothing is queued; a feature or behavior change first needs a spec issue there (--issue), and an issue that already has an open task there is refused with those ids unless --duplicate-ok <reason>; a handoff the target did not confirm is reported as outcome_unknown with a key, and --key <uuid> files the same request once; --list shows each handoff with its age and whether its target is reachable (reachable, unreachable with the cause, or moved), and --sync asks every target now instead of at the next 5-minute pass; its state changes show in ahub board --handoffs (an agent that hands off gets them as task messages)"],
121
123
  ["ahub backlog list [--json] [--full] [--color=auto|always|never] | add <class> <title...> | plan <id> <revision> <fields-json> <reason...> | pin <id> <revision> true|false <reason...> | person <id> <revision> true|false <reason...> | undo <id> <revision> [--json] [--color=auto|always|never]", "person only: plan work with a reason; {} records a note-only revision, fields.sdlc sets backlog repo/issue identity and clears old spec acceptance; preserve pins/frozen scope and refuse stale edits; person marks a leg only the person can run (live receipts, their accounts or approvals): no agent is offered it, auto pull and the idle sweep skip it, and it counts toward no planner WIP; list is by rank and shows it as waiting on the person (--json: raw listing)"],
124
+ [`ahub roadmap ${ROADMAP_FORMS.list} | ${ROADMAP_FORMS.show}`, "read public milestone membership and computed progress; private work is a count, unavailable evidence stays unknown"],
125
+ [`ahub roadmap ${ROADMAP_FORMS.new}`, "planner or conductor: create a milestone without GitHub writes or roadmap model calls"],
126
+ [`ahub roadmap ${ROADMAP_FORMS.edit}`, "edit at the current revision; reload roadmap show after a stale-revision refusal"],
127
+ [`ahub roadmap ${ROADMAP_FORMS.link} | ${ROADMAP_FORMS.unlink} | ${ROADMAP_FORMS.order} | ${ROADMAP_FORMS.state}`, "planner or conductor: link and order; done and dropped require the person"],
128
+ [`ahub roadmap ${ROADMAP_FORMS.unplaced}`, "read open issues, tasks and active or draft specs no milestone places, each with why; private tasks are a count; partial means a lower bound"],
129
+ [`ahub roadmap ${ROADMAP_FORMS.triage} | ${ROADMAP_FORMS.accept} | ${ROADMAP_FORMS.reject}`, "planner or conductor: the hub model suggests a milestone for unplaced work, citing ids and words; nothing is linked until accept"],
130
+ [`ahub roadmap ${ROADMAP_FORMS.importGithub}`, "person only: create proposed milestones from open GitHub milestones and link their issues; a dry run unless --apply, idempotent, never writes GitHub"],
122
131
  ["ahub release new <name> <goal> <order> | list | show <name> | plan <name> <revision> <dates-json> | activate|freeze|ship|drop <name> <revision> [--json] [--color=auto|always|never]", "person only, except show (any agent, public metadata): planned UTC millisecond dates and phased scope; ship records a time after approval, never tags or publishes"],
123
132
  ["ahub backlog split <id> <revision> <parts-json> <reason...> [--json] [--color=auto|always|never]", "person only: stage2..8 child prerequisites; original task retains integration, undo refuses used or changed children"],
124
133
  ["ahub backlog pull-ready <id> <revision> <reason...> [--json] [--color=auto|always|never]", "person only: reserve an eligible WIP slot before routing; pending unowned work can be undone"],
@@ -213,12 +222,12 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
213
222
  export function helpEntries(definitions: readonly AdapterDefinition[] = ADAPTERS): readonly HelpEntry[] {
214
223
  const byKind = new Map(definitions.map(definition => [definition.kind, definition]));
215
224
  const order = deriveAdapterLists(definitions).HELP_ORDER;
216
- const native = order.flatMap(kind => byKind.get(kind)?.cli.usage ?? []);
225
+ const native: readonly (readonly [string, string, string?])[] = order.flatMap(kind => byKind.get(kind)?.cli.usage ?? []);
217
226
  const instanceKinds = order.filter(kind => byKind.get(kind)?.instances !== undefined);
218
227
  const instances: readonly [string, string] = [`ahub ${instanceKinds.join("|")} --as <instance> [options...]`, "start an extra instance of that kind declared under instances in .agenthub/config.local.json"];
219
228
  return SECTIONS.flatMap(([section, rows]) => {
220
- const entries: readonly (readonly [string, string])[] = section === "Agents" ? [rows[0]!, ...native, ...(instanceKinds.length ? [instances] : []), ...rows.slice(1)] : rows;
221
- return entries.map(([usage, description]) => ({ section, usage, description }));
229
+ const entries: readonly (readonly [string, string, string?])[] = section === "Agents" ? [rows[0]!, ...native, ...(instanceKinds.length ? [instances] : []), ...rows.slice(1)] : rows;
230
+ return entries.map(([usage, description, summary]) => ({ section, usage, description, ...(summary ? { summary } : {}) }));
222
231
  });
223
232
  }
224
233
  export const HELP = helpEntries();
@@ -229,32 +238,288 @@ export function helpCommands(entry: HelpEntry): string[] {
229
238
  return COMMAND.exec(entry.usage)?.[1]!.split(/ ?\| ?/) ?? [];
230
239
  }
231
240
 
241
+
242
+ /**
243
+ * CLI output standard v1, Help: the overview lists each command once per group as ` <name> <one-line summary>` in two aligned columns; the long text, every usage form
244
+ * and every flag are in `ahub help <command>`. A summary is at most SUMMARY_MAX cells. A command not named here (the native agents, whose text comes from their
245
+ * adapter definitions, never from a table that names a peer) takes the first clause of its description. `<group>/<command>` wins over `<command>` where one name
246
+ * means two things (`backlog`, `check-path`).
247
+ */
248
+ const SUMMARY_MAX = 56;
249
+ const SUMMARIES: Readonly<Record<string, string>> = {
250
+ specs: "read design specs and check their freshness", worktrees: "list worktrees, preview and confirm cleanup", "--project": "run a command against another project",
251
+ projects: "list registered projects and live status", setup: "install the plugin and hooks, choose default agents", init: "write .agenthub/config.json and the AGENTS.md block",
252
+ "--live-test": "user-authorized console delegation (person only)", help: "this overview, or one command's usage", version: "print the installed version", completion: "print a shell completion script",
253
+ up: "start the daemon and this project's default agents", console: "open the human console", pet: "read attention without connecting", sdlc: "read lifecycle gates and the next action",
254
+ "Daemon and runtime/backlog": "return accepted untouched work to the backlog", status: "is the hub OK, and what to do next", logs: "show the hub log", doctor: "check tools, daemon, plugin, models and memory",
255
+ agents: "show each agent CLI's version and verdict", kill: "stop this project's hub", down: "stop this project's hub (same as kill)", reset: "discard queued deliveries and clear holds",
256
+ restart: "recover this project's runtime", upgrade: "review and upgrade this project", recovery: "inspect, resume or abort a held operation",
257
+ daemon: "internal: the detached hub process", "recovery-run": "internal: a detached recovery runner",
258
+ role: "read catalog guidance for a role", stop: "stop a hub-owned headless peer", peer: "hand the attached session to a standby", models: "inspect local model state",
259
+ say: "send a message as the console user", watch: "watch a headless ACP peer's activity", tail: "live stream of messages and states", permission: "inspect or set a peer's permission mode",
260
+ permit: "answer a permission request", answer: "list and answer open hub_ask questions", results: "list what your runs left behind", roster: "every known peer and its participation",
261
+ roles: "each peer's flow roles, planner and reviewers", autonomy: "apply the autonomy preset", model: "select or inspect runtime models", settings: "list, read and change settings",
262
+ pause: "hold or release a peer's deliveries", title: "rename a Pi or local-worker session", queue: "inspect and resolve durable deliveries",
263
+ board: "show the task board, import open issues", task: "put tasks on the board and move them along", "Tasks and review/backlog": "plan, pull and return backlog cards", roadmap: "milestones and their computed progress",
264
+ release: "plan and ship releases", smoke: "live smoke test in a temporary project", broker: "run the ciphertext relay for rooms", room: "encrypted rooms between hubs (person only)",
265
+ source: "register inputs as content-hashed sources", schedule: "list and run machine-local schedules", intake: "turn a plain request into a draft backlog card",
266
+ capabilities: "list the skills each attached peer offers", learn: "review recurring-criterion candidates", study: "research campaign contracts",
267
+ deliverables: "what each task delivered and a reviewer approved", review: "give a review verdict on a task", route: "why a task went where it did",
268
+ ask: "answer from the board, memory and the log", remember: "save a note to shared memory", budget: "quota windows per peer and why one is paused",
269
+ guidance: "guidance declarations and the probe lifecycle", lineage: "execution metadata and evidence strengths", turns: "recent turns and the files each changed",
270
+ undo: "put back the files a turn changed", report: "turns, tokens, messages and task events", usage: "tokens per group from the roll-up", export: "events as JSON lines",
271
+ research: "success and rework rates per approved task", bench: "run a benchmark suite against attached peers", "History and reports/check-path": "other owners' open tasks that claim a file",
272
+ memory: "the hub's own project memory", goal: "long-term tasks and who holds them", "Hooks/check-path": "Claude PreToolUse hook for file claims", facts: "Claude hook for turn-free facts",
273
+ ui: "open the local dashboard", manager: "internal: the dashboard manager process",
274
+ };
275
+ /** The first clause of a description, cut at a word and ended with `...` when it is longer than the column: the whole text is `ahub help <command>`. */
276
+ function firstClause(description: string, max: number): string {
277
+ const clause = description.replace(/\s*\([^)]*\)/g, "").split(/;(?= )|\. /)[0]!.trim();
278
+ if (Bun.stringWidth(clause) <= max) return clause;
279
+ // A clause that is too long ends where its sentence first pauses (`:` or `, `) when that leaves a readable summary; otherwise it is cut at a word and ended with `...`.
280
+ const pause = clause.search(/: |, /);
281
+ if (pause >= 8 && Bun.stringWidth(clause.slice(0, pause)) <= max) return clause.slice(0, pause);
282
+ let out = "";
283
+ for (const word of clause.split(" ")) { if (Bun.stringWidth(`${out} ${word}`.trim()) > max - 3) break; out = `${out} ${word}`.trim(); }
284
+ return `${out.replace(/[,:;\s]+$/, "")}...`;
285
+ }
286
+ /** One overview row: the command words an entry documents (`pause|resume`), and its one-line summary. */
287
+ export interface OverviewRow { section: string; name: string; summary: string }
288
+ export function helpOverviewRows(entries: readonly HelpEntry[] = HELP): OverviewRow[] {
289
+ const shown = new Map<string, Set<string>>(), rows: OverviewRow[] = [];
290
+ for (const entry of entries) {
291
+ const seen = shown.get(entry.section) ?? shown.set(entry.section, new Set()).get(entry.section)!;
292
+ const fresh = helpCommands(entry).filter(word => !seen.has(word));
293
+ if (!fresh.length) continue;
294
+ fresh.forEach(word => seen.add(word));
295
+ const own = (word: string) => SUMMARIES[`${entry.section}/${word}`] ?? SUMMARIES[word];
296
+ const summary = own(fresh[0]!) ?? entry.summary ?? firstClause(entry.description, SUMMARY_MAX);
297
+ rows.push({ section: entry.section, name: fresh.join("|").replace(/^version\|--version$/, "version|--version"), summary: Bun.stringWidth(summary) > SUMMARY_MAX ? firstClause(summary, SUMMARY_MAX) : summary });
298
+ }
299
+ return rows;
300
+ }
301
+
302
+ /**
303
+ * #1504 T2, one example or more per command that takes arguments: complete, copyable, and only ever a form, subcommand and flag the command's own usage lists
304
+ * (`test/help.test.ts` runs each against the dispatch table and the usage). A native agent's example is derived from its definition's usage, never named here.
305
+ * Internal commands (`daemon`, `recovery-run`, `manager`, `facts`) have none: nobody types them.
306
+ */
307
+ export const EXAMPLES: Readonly<Record<string, readonly string[]>> = {
308
+ specs: ["ahub specs check --require-fresh", "ahub specs covers src/cli/help.ts"], worktrees: ["ahub worktrees tidy"], "--project": ["ahub --project ../other-repo status"],
309
+ projects: ["ahub projects --json"], "--live-test": ["ahub --live-test status"], setup: ["ahub setup --agents claude,codex"], init: ["ahub init --profile dev --sdlc advise --dry-run --json"],
310
+ help: ["ahub help task"], completion: ["ahub completion zsh"],
311
+ up: ["ahub up --no-console"], console: ["ahub console --panels"], pet: ["ahub pet --short"],
312
+ sdlc: ["ahub sdlc status 12", "ahub sdlc explain 12 --json"], backlog: ["ahub backlog list --full", "ahub backlog return 12 3 waiting on a spec"],
313
+ status: ["ahub status --verbose"], logs: ["ahub logs -f"], doctor: ["ahub doctor --json"], agents: ["ahub agents --json"],
314
+ reset: ["ahub reset"], restart: ["ahub restart --dry-run"], upgrade: ["ahub upgrade --dry-run"], recovery: ["ahub recovery status"],
315
+ role: ["ahub role list"], stop: ["ahub stop pi"], peer: ["ahub peer takeover codex"], models: ["ahub models status"],
316
+ say: ["ahub say @codex please rebase on main"], watch: ["ahub watch kimi"], permission: ["ahub permission codex ask-when-needed"],
317
+ permit: ["ahub permit 7 deny"], answer: ["ahub answer"], results: ["ahub results --unread"], roster: ["ahub roster --json"], roles: ["ahub roles --json"],
318
+ autonomy: ["ahub autonomy status"], model: ["ahub model list"], settings: ["ahub settings list"], pause: ["ahub pause codex"], resume: ["ahub resume codex"],
319
+ title: ["ahub title pi release review"], queue: ["ahub queue list --peer codex"], board: ["ahub board --ready"],
320
+ task: ["ahub task show 12", "ahub task propose implement Fix the flaky test --path test/a.test.ts"], roadmap: ["ahub roadmap show 3"], release: ["ahub release list"],
321
+ smoke: ["ahub smoke run qwen-dual-output --project-id 1f3a --receipt receipt.json"], broker: ["ahub broker serve --port 8787"], room: ["ahub room list"],
322
+ source: ["ahub source list"], schedule: ["ahub schedule list"], intake: ["ahub intake \"Add a dark mode toggle\""], capabilities: ["ahub capabilities --json"], learn: ["ahub learn list"],
323
+ study: ["ahub study show --json"], deliverables: ["ahub deliverables --task 12 --check"], review: ["ahub review 12 approved looks good", "ahub review brief 12"],
324
+ route: ["ahub route explain 12"], ask: ["ahub ask what blocks task 12"], remember: ["ahub remember Pi 1.5.2 is verified"], budget: ["ahub budget --full"],
325
+ guidance: ["ahub guidance list --task 12 --task-created 1760000000000"], lineage: ["ahub lineage show --task 12"], turns: ["ahub turns codex --limit 5"],
326
+ undo: ["ahub undo 42"], report: ["ahub report --since 7d"], usage: ["ahub usage --by peer --since 7d"], export: ["ahub export --since 7d"], research: ["ahub research --since 30d"],
327
+ bench: ["ahub bench list"], "check-path": ["ahub check-path src/cli/help.ts"], memory: ["ahub memory search sweep"], goal: ["ahub goal list"], ui: ["ahub ui --no-open"],
328
+ };
329
+ /** Commands nobody types: a process the hub starts, or a hook a tool calls. They have no example. */
330
+ export const INTERNAL_COMMANDS: readonly string[] = ["daemon", "recovery-run", "manager", "facts"];
331
+
332
+ /** One example per native agent, from its own definition: `ahub <kind> --print-command` when its usage has that flag (it prints the launch and starts nothing), else the bare command. */
333
+ function nativeExample(command: string, entries: readonly HelpEntry[]): string[] {
334
+ const own = entries.find(entry => entry.section === "Agents" && helpCommands(entry).includes(command) && entry.summary !== undefined);
335
+ return own ? [own.usage.includes("--print-command") ? `ahub ${command} --print-command` : `ahub ${command}`] : [];
336
+ }
337
+
338
+ /** A flag of a command's usages: its value shape as the usage writes it, and the subcommand forms it appears in (empty for the command's base form). */
339
+ export interface HelpFlag { flag: string; shape: string; /** `=` or a space: how the usage joins the flag and its value, kept so the Flags line reads as the usage does. */ joiner: "=" | " "; forms: string[] }
340
+ const FLAG = /(?<![\w-])(-{1,2}[A-Za-z][A-Za-z0-9-]*)(?:=([^\s\]()]+)| (<[^>]+>|[A-Z][A-Za-z]*\b|N\b|[a-z0-9_,.-]+(?:\|[a-z0-9_,.<>-]+)+))?/g;
341
+ /** Every flag the usages of `command` name, in the order they first appear, once each. */
342
+ export function helpFlags(command: string, entries: readonly HelpEntry[] = HELP): HelpFlag[] {
343
+ const found = new Map<string, HelpFlag>();
344
+ for (const entry of entries.filter(entry => helpCommands(entry).includes(command))) {
345
+ const prefix = COMMAND.exec(entry.usage)?.[0] ?? "";
346
+ let lead = "";
347
+ topLevelPieces(entry.usage).forEach((piece, index) => {
348
+ const body = index === 0 ? piece.slice(prefix.length).trim() : piece;
349
+ const token = body.split(/\s/)[0]!.replace(/[\[\]]/g, "");
350
+ const named = token.split("|").filter(word => /^[a-z][a-z0-9-]*$/.test(word)).join("|");
351
+ // #1504: a piece after ` | ` that starts with a flag or an argument (`task handoff --list | --sync | --project <root|id> ...`) is another way into the form the first piece named
352
+ if (index === 0) lead = named;
353
+ const form = named || lead;
354
+ for (const match of body.matchAll(FLAG)) {
355
+ const flag = match[1]!, shape = match[2] ?? match[3] ?? "", joiner = match[2] !== undefined ? "=" as const : " " as const;
356
+ const seen = found.get(flag) ?? found.set(flag, { flag, shape, joiner, forms: [] }).get(flag)!;
357
+ if (!seen.shape && shape) { seen.shape = shape; seen.joiner = joiner; }
358
+ if (form && !seen.forms.includes(form)) seen.forms.push(form);
359
+ }
360
+ });
361
+ }
362
+ return [...found.values()];
363
+ }
364
+ /**
365
+ * #1504 AC3: what each flag is for, one short line, kept beside the usage text it describes (never a second table keyed by peer). The two flags the standard itself defines
366
+ * (`--json`, `--color`, `docs/design/cli-output.md`) keep their longer text; every other line is at most `FLAG_LINE` cells, so it fits beside the longest label at 80 columns.
367
+ * A key is a flag, or `<command> <flag>` where one command's flag is for something other than the flag's own entry. A flag with no entry (one a definition outside this
368
+ * file adds) falls back to the forms that take it, and `test/help.test.ts` fails a flag of any command in this file that has no line.
369
+ */
370
+ export const FLAG_DESCRIPTIONS: Readonly<Record<string, string>> = {
371
+ "--json": "one JSON document on stdout, never colored",
372
+ "--color": "auto, always or never; auto follows NO_COLOR, FORCE_COLOR and the terminal",
373
+ // in many commands
374
+ "--yes": "confirm without asking", "--full": "whole titles and every detail", "--verbose": "print every detail", "--ascii": "use ASCII markers", "--dry-run": "report what would happen, change nothing",
375
+ "--preview": "show the change, save nothing", "--now": "apply now, not at the next start", "--apply": "write it; without this only a preview",
376
+ "--reason": "why, recorded with the change", "--revision": "revision acted on; a stale one is refused", "--limit": "at most this many rows", "--since": "start of the period: 7d or an ISO time",
377
+ "--task": "task number it concerns", "--issue": "GitHub issue number", "--pr": "pull request number", "--repo": "repository as owner/name", "--peer": "this peer only", "--project": "project path or id",
378
+ "--label": "label to use", "--model": "model alias or id to run with", "--class": "task class, such as implement", "--format": "jsonl or csv", "--list": "list instead of acting", "--confirm": "fingerprint that confirms this action",
379
+ "--action": "the resolution to apply", "--by": "how to group the rows", "--file": "JSON file to read", "--id": "id hash of the item", "--cursor": "continue from this page token", "--variant": "variant id",
380
+ "--attempt": "attempt id (ra-...)", "--task-created": "creation time of the task, in milliseconds", "--owner": "peer that owns the task", "--after": "wait for this task id (repeatable)", "--milestone": "milestone to use",
381
+ // setup, init and sdlc
382
+ "--require-fresh": "also fail on stale documents", "--base": "compare against this git ref", "--agents": "agents ahub up starts", "--research": "turn research records on", "--no-research": "turn research records off",
383
+ "--profile": "role profile or pack", "--sdlc": "SDLC mode: off, advise or enforce", "--required-checks": "CI check names that must pass", "--coordination": "advisory or turn-free", "--memory": "turn shared memory on",
384
+ "--no-memory": "turn shared memory off", "--snapshots": "turn per-turn snapshots on", "--no-snapshots": "turn per-turn snapshots off", "--pi": "turn the Pi peer on", "--no-pi": "turn the Pi peer off",
385
+ "--specs": "turn design specs on", "--no-specs": "turn design specs off", "--spec-review": "how covering specs are reviewed", "--conductor": "the peer that conducts, or none", "--planner": "peers that plan",
386
+ "--reviewer": "peers that review, or person", "--track-config": "share config.json through git", "--no-track-config": "keep config.json out of git", "--autonomy": "inherit the machine preset, or not",
387
+ "--shadow": "hub-owned snapshots for a non-git folder", "--release-guard": "install the tag pre-push hook", "--focus": "area the survey looks at", "--review": "review scope: full, delta or none",
388
+ "--reviewers": "number of reviewers", "--ci": "CI scope: full, focused or reuse", "--reserved": "reserve the card for this peer", "--unreserve": "clear the card's reservation", "--to": "version to upgrade to",
389
+ "--version": "print the installed version",
390
+ // daemon, agents and recovery
391
+ "--unattended": "no permission prompts; the agent acts alone", "--no-console": "do not enter the console", "--no-agents": "do not start the default agents", "--panels": "start in panels mode",
392
+ "--no-pet": "turn the attention pet off", "--short": "print ahub!N only when action is needed", "--palette": "retired: run acon ui and open Mini", "pet --window": "retired: run acon ui and open Mini", "--close": "retired: no window is opened", "-f": "follow new lines",
393
+ "--stale-anchors": "report stale memory symbol anchors", "--orphans": "inspect registrations whose root is gone", "--kill": "stop the selected orphan's hub", "--revoke": "withdraw a trusted version",
394
+ "--fresh-session": "restart the peer as a new session", "--stop-and-archive": "stop its targets and archive the snapshot", "--print-command": "print the launch command, start nothing", "--as": "name of the extra instance",
395
+ "--mode": "tui or headless", "--session-id": "session id to resume or pin", "--provider-profile": "Jcode provider profile to use", "--headless": "run without a terminal", "--backend": "Pi backend: auto, dgx or mlx",
396
+ "--session-file": "Pi session file to open", "--replace-session": "replace the saved session", "--route": "routing.toml route to use", "--group": "only this catalog group", "--no-thoughts": "hide the peer's reasoning lines",
397
+ // messages, approvals and settings
398
+ "--other": "answer in free text, not an option", "--instructed": "the person's quote the conductor acts on", "--unread": "only unread results", "--read": "mark one result read", "--read-all": "mark every result read",
399
+ "--unread-last": "mark the latest read one unread", "--all-projects": "apply to every registered project", "--state": "only deliveries in this state",
400
+ // tasks, roadmap, rooms and broker
401
+ "--ready": "only tasks with nothing left to wait for", "--columns": "show the tasks as board columns", "--release": "only this release, by name", "--release-id": "only this release, by id", "--handoffs": "show work handed to other projects",
402
+ "--path": "file the task touches (repeatable)", "--urgent": "mark the task urgent", "--needs-network": "keep it from a peer with no network", "--needs-worktree": "keep it from a sandboxed peer", "--backlog": "stage it in Backlog, unoffered",
403
+ "--detail": "longer text of the task", "--sync": "sync handoff states from the targets", "--duplicate-ok": "file despite an open task, with a reason", "--key": "idempotency key (a UUID) for the handoff",
404
+ "--role": "owner, reviewer or planner", "--model-said": "what the model said about the claim", "--manifest": "synthesis manifest the verdict binds to", "--disposition": "resolved or qualified",
405
+ "--superseded-by": "work that replaces this task", "--created": "when the label applies (person only)", "--title": "milestone title", "--outcome": "the outcome the milestone delivers", "--horizon": "now, next or later",
406
+ "--order": "position among its siblings", "--target": "target date (YYYY-MM-DD) or none", "--parent": "parent milestone id, or none", "--project-id": "id of the disposable project", "--receipt": "file to write the receipt to",
407
+ "--timeout-ms": "time limit, 100 to 120000 ms", "--hostname": "interface to listen on", "--port": "port to listen on", "--public-url": "public ws or wss URL", "--state-dir": "directory for the relay's state",
408
+ "--broker": "relay URL", "--accept": "request to accept", "--name": "name to join the room under", "--roster": "signed roster to join with", "--frame": "digest of the incoming frame", "--source": "registered src: id (repeatable)",
409
+ "--campaign": "campaign id", "--events-after": "continue its events after this number", "--plan": "plan hash to compare under", "--baseline": "baseline attempt id", "--approved": "only approved tasks",
410
+ "--check": "measure the files now, mark changed ones", "--unmet": "criterion not met (repeatable)", "--head": "head commit SHA the verdict is for", "--findings": "findings as JSON", "--security-pass": "security pass result as JSON",
411
+ // history, reports and memory
412
+ "--remember": "also save the answer to memory", "--resets-in": "when the window resets, such as 30m", "--window": "5h or week", "--root": "execution root reference as JSON", "--task-scope": "task the root is scoped to",
413
+ "--nodes": "at most this many nodes", "--edges": "at most this many edges", "--bytes": "at most this many bytes", "--ref": "execution reference as JSON", "--from": "reference the link comes from, as JSON",
414
+ "--context": "also drop a Codex turn from its conversation", "--dogfood": "print the dogfood scorecard", "--dataset": "directory for the per-project datasets", "--arm": "label of the arm being run", "--repeat": "attempts per task",
415
+ "--tasks": "run only these tasks (a,b)", "--addon": "declare an add-on: name=on or name=off", "--suite": "suite to compare", "--mixed": "compare across suites", "--tier": "short or long term", "--kind": "decision, contract, fail or finding",
416
+ "--machine": "only entries from this machine", "--hops": "graph depth: 1 or 2", "--history": "include superseded and expired entries", "--as-of": "memory as it stood at this time", "--remote": "private git remote to sync with",
417
+ "--db": "claude-mem database to read", "--restart": "revisit rows skipped under an earlier policy", "--days": "older than this many days (default 90)", "--depends": "goal it depends on (repeatable)", "--shared": "share the goal across machines",
418
+ "--force": "void other machines' claims", "--no-open": "print the link, do not open it", "--settings": "open with a settings session", "--stop": "stop the dashboard manager", "--hook": "run as a Claude Code hook; never blocks",
419
+ // a flag one command uses for something other than its own entry
420
+ "--all": "include everything, not the default subset", "status --all": "every registered project", "ui --all": "the unified project dashboard", "reset --all": "archive the state directory instead", "queue --all": "include rows already settled",
421
+ "learn --all": "include decided candidates", "research --all": "every registered project", "goal --all": "include completed goals", "sdlc --mode": "off or advise", "sdlc --profile": "audit depth: quick or standard",
422
+ "sdlc --since": "git ref, or a date for metrics", "memory --since": "only entries since this ISO time", "memory --label": "name for this machine", "bench --memory": "memory state: off, claude-mem, native or both",
423
+ "task --model": "model label the verdict was given under", "room --action": "accept or discard the application", "room --label": "label for your member", "room --confirm": "member fingerprint prefix",
424
+ "worktrees --confirm": "fingerprint of the preview to run", "board --label": "only issues with this label", "board --milestone": "only issues of this milestone", "board --repo": "repository to import from", "goal --milestone": "milestone of the goal (repeatable)",
425
+ "broker --owner": "owner fingerprint allowed (repeatable)", "study --after": "continue after this id", "--live-test --project": "project to run the command in", "task --project": "project to hand the work to",
426
+ "task --revision": "refuse if the task has moved on", "study --revision": "revision of the evidence to read", "usage --by": "peer, task, issue, pr, release, day or model", "report --by": "group by task", "check-path --peer": "the peer asking (default: this one)",
427
+ };
428
+ /** The widest a flag's line may be, except the standard's two flags: it sits beside the longest label (30 cells and a gap) within 80 columns. */
429
+ export const FLAG_LINE = 46;
430
+ /** What `command` says its `flag` is for: its own entry first, then the flag's. */
431
+ export function flagDescription(command: string, flag: string): string | undefined {
432
+ return FLAG_DESCRIPTIONS[`${command} ${flag}`] ?? FLAG_DESCRIPTIONS[flag];
433
+ }
434
+
232
435
  const DESCRIPTION = 34;
233
436
  /**
234
- * Usage at 2 spaces, description at one fixed column, wrapped at word boundaries to the terminal width
235
- * (80 to 100 columns). A usage too long for that column puts its description on the next line.
236
- * With a command, only its entries; an unknown command renders nothing.
437
+ * `ahub help <command>` in the standard's shape (#1504): the usage forms, a short description, each flag on one line, examples, then the long text unchanged
438
+ * (every usage form with its whole description) so nothing a form or flag says is lost. Lines are wrapped within `width`.
237
439
  */
238
- export function renderHelp(columns: number, color: boolean, command?: string, definitions?: readonly AdapterDefinition[]): string {
239
- const width = Math.min(100, Math.max(80, columns || 80));
240
- const model = definitions === undefined ? HELP : helpEntries(definitions);
241
- const entries = command === undefined ? model : model.filter(entry => helpCommands(entry).includes(command));
242
- const lines: Span[][] = command === undefined ? wrap(`agent-hub ${VERSION}: Claude Code, Codex and Kimi as peers in one project directory`, width, 0).map(text => [{ text }]) : [];
440
+ function renderCommandHelp(width: number, ascii: boolean, command: string, model: readonly HelpEntry[]): Span[][] {
441
+ const entries = model.filter(entry => helpCommands(entry).includes(command));
442
+ if (!entries.length) return [];
443
+ const report = new LayoutReport(width, ascii);
444
+ report.section("Usage");
445
+ for (const entry of entries) {
446
+ const prefix = COMMAND.exec(entry.usage)?.[0] ?? "";
447
+ const text = wrap(entry.usage, width - 2, 4);
448
+ report.append(text.map((line, index): Span[] => index === 0 ? [{ text: " " }, { text: prefix, role: "accent" }, { text: line.slice(prefix.length) }] : [{ text: " " + line }]));
449
+ }
450
+ const row = helpOverviewRows(model).find(item => item.name.split("|").includes(command));
451
+ if (row) report.section("Description").note(row.summary, "value");
452
+ const flags = helpFlags(command, model);
453
+ if (flags.length) {
454
+ report.section("Flags", String(flags.length));
455
+ const labels = flags.map(item => item.shape ? `${item.flag}${item.joiner}${item.shape}` : item.flag);
456
+ const column = Math.min(30, Math.max(...labels.map(label => Bun.stringWidth(label)))) + 2;
457
+ flags.forEach((item, index) => {
458
+ const label = labels[index]!, base = item.flag;
459
+ const meaning = flagDescription(command, base) ?? (item.forms.length ? `in ${item.forms.length > 3 ? `${item.forms.slice(0, 3).join(", ")} and ${item.forms.length - 3} more` : item.forms.join(", ")}` : "");
460
+ const room = width - 2 - column;
461
+ if (Bun.stringWidth(label) + 2 > column || !meaning) {
462
+ report.append([[{ text: " " }, { text: label, role: "accent" }]]);
463
+ if (meaning) for (const line of wrap(meaning, width - 2 - column, 0)) report.append([[{ text: " ".repeat(2 + column) + line }]]);
464
+ return;
465
+ }
466
+ const lines = wrap(meaning, room, 0);
467
+ report.append([[{ text: " " }, { text: label, role: "accent" }, { text: " ".repeat(column - Bun.stringWidth(label)) + lines[0]! }]]);
468
+ for (const line of lines.slice(1)) report.append([[{ text: " ".repeat(2 + column) + line }]]);
469
+ });
470
+ }
471
+ const examples = [...(EXAMPLES[command] ?? []), ...nativeExample(command, model)];
472
+ if (examples.length) {
473
+ report.section("Examples");
474
+ for (const example of examples) report.append(wrap(example, width - 2, 4).map((line, index): Span[] => [{ text: index === 0 ? " " : " " }, { text: line, role: index === 0 ? "accent" : "value" }]));
475
+ }
476
+ report.section("Details");
243
477
  let section = "";
244
478
  for (const entry of entries) {
245
- if (entry.section !== section) {
246
- if (lines.length) lines.push([]);
247
- lines.push([{ text: entry.section, tone: "strong" }]);
248
- section = entry.section;
249
- }
479
+ if (entry.section !== section) { section = entry.section; report.append([[{ text: ` ${entry.section}`, tone: "strong" }]]); }
250
480
  const prefix = COMMAND.exec(entry.usage)?.[0] ?? "";
251
481
  const usage = wrap(entry.usage, width - 4, 0);
252
482
  const description = wrap(entry.description, width - DESCRIPTION, 0);
253
483
  const first: Span[] = [{ text: " " }, { text: prefix, tone: "info" }, { text: usage[0]!.slice(prefix.length) }];
254
484
  if (usage.length === 1 && 2 + Bun.stringWidth(usage[0]!) + 2 <= DESCRIPTION) first.push({ text: " ".repeat(DESCRIPTION - 2 - Bun.stringWidth(usage[0]!)) + description.shift() });
255
- lines.push(first, ...usage.slice(1).map(text => [{ text: ` ${text}` }]), ...description.map(text => [{ text: " ".repeat(DESCRIPTION) + text }]));
485
+ report.append([first, ...usage.slice(1).map((text): Span[] => [{ text: ` ${text}` }]), ...description.map((text): Span[] => [{ text: " ".repeat(DESCRIPTION) + text }])]);
486
+ }
487
+ return report.lines();
488
+ }
489
+
490
+ /**
491
+ * Without a command, the overview. With one, `ahub help <command>` (renderCommandHelp), wrapped at word boundaries to the terminal width (80 to 100 columns);
492
+ * an unknown command renders nothing.
493
+ */
494
+ export function renderHelp(columns: number, color: boolean, command?: string, definitions?: readonly AdapterDefinition[], ascii = false): string {
495
+ const width = Math.min(100, Math.max(80, columns || 80));
496
+ const model = definitions === undefined ? HELP : helpEntries(definitions);
497
+ // The overview is a fixed 80 columns (standard v1, Help): its rows are short, so a wider terminal gains nothing and every terminal reads the same text.
498
+ if (command === undefined) return renderOverview(80, color, ascii, model);
499
+ // #1504: one command is the standard's shape (usage, description, flags, examples) with the long text below it; an unknown command renders nothing.
500
+ return renderCommandHelp(width, ascii, command, model).map(line => paint(line, color)).join("\n");
501
+ }
502
+
503
+ /**
504
+ * `ahub help`: the standard's overview. One intro line, then each group (`▸ Group`) with ` <name> <summary>` rows in two aligned columns, never wider than the
505
+ * terminal (80 to 100 cells), then where the long text lives. Every command still appears; every usage form and flag is in `ahub help <command>`.
506
+ */
507
+ function renderOverview(width: number, color: boolean, ascii: boolean, entries: readonly HelpEntry[]): string {
508
+ const rows = helpOverviewRows(entries), column = Math.max(...rows.map(row => Bun.stringWidth(row.name))) + 2;
509
+ const report = new LayoutReport(width, ascii);
510
+ const out: Span[][] = wrap(`agent-hub ${VERSION}: Claude Code, Codex and Kimi as peers in one project directory`, width, 0).map(text => [{ text }]);
511
+ out.push([{ text: "Usage: ahub <command> [args] Details: ahub help <command>", role: "hint" }]);
512
+ let section = "";
513
+ for (const row of rows) {
514
+ if (row.section !== section) { section = row.section; report.section(section); }
515
+ const pad = " ".repeat(column - Bun.stringWidth(row.name));
516
+ const summary = wrap(row.summary, width - 2 - column, 0);
517
+ report.append([[{ text: " " }, { text: row.name, role: "accent" }, { text: `${pad}${summary[0]!}` }]]);
518
+ for (const more of summary.slice(1)) report.append([[{ text: " ".repeat(2 + column) + more }]]);
256
519
  }
257
- return lines.map(line => paint(line, color)).join("\n");
520
+ report.section("More").note("ahub help <command> shows every usage form and flag of one command; ahub --help and ahub -h print this overview", "value");
521
+ // #1504 AC1: every section title, the first included, follows one blank line. The report only blanks between its own sections, so the gap after the intro lines is added here.
522
+ return [...out, [], ...report.lines()].map(line => paint(line, color)).join("\n");
258
523
  }
259
524
 
260
525
  /** Split a usage at its top-level " | " only: a pipe inside [...] or <...> belongs to one alternative (`[--class <c> | <class>]`). */
@@ -3,7 +3,7 @@ import { join } from "node:path";
3
3
  import { cliCommandLabel } from "./identity.ts";
4
4
 
5
5
  export interface CliAudit {
6
- v: 1; id: string; at: number; peer: string; command: string; outcome: "run" | "refused" | "invalid" | "delegated";
6
+ v: 1; id: string; at: number; peer: string; command: string; outcome: "run" | "refused" | "invalid" | "delegated"; instructed?: true;
7
7
  }
8
8
  const MAX_FILES = 256;
9
9
  const MAX_BYTES = 64 * 1024;
@@ -14,7 +14,8 @@ const valid = (row: any): row is CliAudit => row?.v === 1 && typeof row.id === "
14
14
  && typeof row.at === "number" && Number.isFinite(row.at) && row.at > 0
15
15
  && typeof row.peer === "string" && /^[a-z][a-z0-9-]{0,31}$/.test(row.peer) && !/\s/.test(row.peer)
16
16
  && typeof row.command === "string" && row.command.length <= 64 && row.command === cliCommandLabel(...splitLabel(row.command))
17
- && ["run", "refused", "invalid", "delegated"].includes(row.outcome);
17
+ && ["run", "refused", "invalid", "delegated"].includes(row.outcome)
18
+ && (row.instructed === undefined || row.instructed === true && row.command === "answer");
18
19
  const splitLabel = (label: string): [string, string[]] => { const [command = "unknown", ...args] = label.split(" "); return [command, args]; };
19
20
 
20
21
  /**
@@ -22,8 +23,8 @@ const splitLabel = (label: string): [string, string[]] => { const [command = "un
22
23
  * the checked 256-file / 64 KiB ceiling by at most one bounded row per concurrent writer.
23
24
  * Unpublished temp files count against the ceiling, so a crashed writer cannot grow the spool forever.
24
25
  */
25
- function reserveCliAudit(stateDir: string, peer: string, command: string, outcome: CliAudit["outcome"]) {
26
- const row: CliAudit = { v: 1, id: crypto.randomUUID(), at: Date.now(), peer, command, outcome };
26
+ function reserveCliAudit(stateDir: string, peer: string, command: string, outcome: CliAudit["outcome"], instructed = false) {
27
+ const row: CliAudit = { v: 1, id: crypto.randomUUID(), at: Date.now(), peer, command, outcome, ...(instructed ? { instructed: true } : {}) };
27
28
  if (!valid(row)) throw new Error("invalid CLI audit identifiers");
28
29
  const dir = join(stateDir, "cli-audit");
29
30
  mkdirSync(dir, { recursive: true, mode: 0o700 });
@@ -49,8 +50,8 @@ function reserveCliAudit(stateDir: string, peer: string, command: string, outcom
49
50
  };
50
51
  }
51
52
 
52
- export function recordCliAudit(stateDir: string, peer: string, command: string, outcome: CliAudit["outcome"]): void {
53
- const pending = reserveCliAudit(stateDir, peer, command, outcome);
53
+ export function recordCliAudit(stateDir: string, peer: string, command: string, outcome: CliAudit["outcome"], instructed = false): void {
54
+ const pending = reserveCliAudit(stateDir, peer, command, outcome, instructed);
54
55
  try { pending.commit(outcome); }
55
56
  finally { pending.close(); }
56
57
  }
@@ -83,7 +84,7 @@ export function drainCliAudits(stateDir: string): CliAudit[] {
83
84
  try {
84
85
  if (statSync(path).size <= MAX_ROW_BYTES) {
85
86
  const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
86
- if (valid(parsed) && `${parsed.id}.json` === name) rows.push({ v: 1, id: parsed.id, at: parsed.at, peer: parsed.peer, command: parsed.command, outcome: parsed.outcome });
87
+ if (valid(parsed) && `${parsed.id}.json` === name) rows.push({ v: 1, id: parsed.id, at: parsed.at, peer: parsed.peer, command: parsed.command, outcome: parsed.outcome, ...(parsed.instructed ? { instructed: true } : {}) });
87
88
  }
88
89
  } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT" && !(error instanceof SyntaxError)) throw error; }
89
90
  try { unlinkSync(path); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
@@ -15,10 +15,14 @@ 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 === "roadmap" && ![undefined, "list", "show", "--json"].includes(args[0])) return true;
19
+ if (command === "roadmap" && args[0] === "--json" && ![undefined, "list", "show"].includes(args[1])) return true;
18
20
  if (command === "sdlc" && args[0] === "configure") return true;
19
21
  if (command === "lineage" && args[0] === "link") return true;
20
22
  if (command === "guidance" && ["create", "withdraw"].includes(args[0] ?? "")) return true;
21
23
  if (command === "sdlc" && args[0] === "survey" && args[1] !== "show") return true;
24
+ // #1403 A4: starting a security audit files a task; only `show` stays a live-test read.
25
+ if (command === "sdlc" && args[0] === "audit" && args[1] !== "show") return true;
22
26
  if (command === "model") return true; // #1317: even listing runtime overrides is person-only, never live-test delegated.
23
27
  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;
24
28
  if (args.some(arg => arg === "--as-user" || arg.startsWith("--as-user="))) return true;
@@ -156,6 +160,14 @@ export function classifyPeerCommand(command: string, args: readonly string[], ca
156
160
  if (native?.cli.personOnlyFlags?.some(flag => args.includes(flag))) return "console";
157
161
  if (command === "permission" || command === "watch") return "console";
158
162
  if (args.some((arg) => arg === "--as-user" || arg.startsWith("--as-user="))) return "console";
163
+ if (command === "roadmap") {
164
+ const sub = args[0] === "--json" ? args[1] : args[0];
165
+ if (sub === "state" && ["done", "dropped"].includes(args[2] ?? "")) return "console";
166
+ // R3 (#1481): importing GitHub milestones is the person's alone, a dry run included; triage, accept and reject are the planner's own tools.
167
+ if (sub === "import-github") return "console";
168
+ return "allowed";
169
+ }
170
+ if (command === "answer" && args.includes("--instructed")) return "conductor";
159
171
  if (command === "pet" && (args.includes("--window") || args.includes("--palette"))) return "allowed";
160
172
  if (conductorOperation(command,args)) return "conductor";
161
173
  if (command === "stop") return "console";
@@ -205,8 +217,13 @@ export function classifyPeerCommand(command: string, args: readonly string[], ca
205
217
 
206
218
  /** No argument text is included: notices and refusal logs must not copy task text or credentials. */
207
219
  export function cliCommandLabel(command: string, args: readonly string[], catalog?: ProjectAdapterCatalog): string {
220
+ if (command === "roadmap") {
221
+ const sub = args[0] === "--json" ? args[1] : args[0];
222
+ return ["list", "show", "new", "edit", "link", "unlink", "order", "state", "unplaced", "triage", "accept", "reject", "import-github"].includes(sub ?? "") ? `roadmap ${sub}` : "roadmap";
223
+ }
208
224
  if (command === "sdlc" && args[0] === "configure") return "sdlc configure";
209
225
  if (command === "sdlc" && args[0] === "survey") return ["start", "show"].includes(args[1] ?? "") ? `sdlc survey ${args[1]}` : "sdlc survey";
226
+ if (command === "sdlc" && args[0] === "audit") return ["start", "show"].includes(args[1] ?? "") ? `sdlc audit ${args[1]}` : "sdlc audit";
210
227
  if (command === "lineage") return ["show", "link"].includes(args[0] ?? "") ? `lineage ${args[0]}` : "lineage";
211
228
  if (command === "guidance") return ["create", "list", "show", "withdraw"].includes(args[0] ?? "") ? `guidance ${args[0]}` : "guidance";
212
229
  if (command === "model") return ["list", "set", "clear"].includes(args[0] ?? "") ? `model ${args[0]}` : "model";