@staix/agent-hub 0.49.1 → 0.51.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 (99) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +1 -1
  3. package/docs/adding-an-ai-tool.md +2 -2
  4. package/docs/agent-notes/README.md +1 -0
  5. package/docs/agent-notes/adapters.md +3 -3
  6. package/docs/agent-notes/daemon.md +1 -1
  7. package/docs/agent-notes/local-worker.md +3 -3
  8. package/docs/agent-notes/tasks.md +5 -1
  9. package/docs/design/adapters.md +17 -0
  10. package/docs/design/agent-hub.md +1 -1
  11. package/docs/design/cli-output-inventory.md +24 -19
  12. package/docs/design/cli-output.md +1 -1
  13. package/docs/design/roadmap.md +2 -2
  14. package/docs/design/task-board.md +34 -0
  15. package/docs/dogfood.md +8 -3
  16. package/docs/operations.md +53 -4
  17. package/docs/quickstart.md +26 -2
  18. package/docs/roadmap.json +20 -20
  19. package/docs/roadmap.md +2 -2
  20. package/docs/sdlc.md +3 -2
  21. package/docs/specs/2026-09-19-agent-hub-design.md +1 -0
  22. package/docs/verification/2026-11-29-0.50.0.md +54 -0
  23. package/docs/verification/2026-11-29-agy-1.5.20.md +33 -0
  24. package/docs/verification/2026-11-29-claude-profile-hook.md +12 -0
  25. package/docs/verification/2026-11-29-idle-daemon-footprint.md +75 -0
  26. package/docs/verification/2026-11-29-kimi-281-reviewer-compat.md +38 -0
  27. package/docs/verification/2026-11-29-kimi-tui-281.md +12 -0
  28. package/docs/verification/2026-11-30-0.51.0.md +91 -0
  29. package/docs/verification/2026-11-30-account-switch-1806.md +445 -0
  30. package/docs/verified.json +31 -27
  31. package/package.json +1 -1
  32. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  33. package/plugins/agent-hub/kimi-hook.js +1329 -24629
  34. package/plugins/agent-hub/server.js +638 -414
  35. package/scripts/check-docs.mjs +1 -1
  36. package/src/adapters/acp.ts +13 -13
  37. package/src/adapters/agy/definition.ts +2 -2
  38. package/src/adapters/agy/entry.ts +2 -0
  39. package/src/adapters/claude-channel-evidence.ts +7 -3
  40. package/src/adapters/compat.ts +4 -3
  41. package/src/adapters/definitions/builtin-metadata.ts +2 -2
  42. package/src/adapters/definitions/native-cli-claude-launch.ts +3 -1
  43. package/src/adapters/definitions/native-cli-entry-claude.ts +17 -2
  44. package/src/adapters/definitions/native-cli-entry-codex.ts +2 -0
  45. package/src/adapters/definitions/native-cli-entry-jcode.ts +2 -0
  46. package/src/adapters/definitions/native-cli-entry-kimi.ts +2 -0
  47. package/src/adapters/definitions/native-cli-entry-pi.ts +2 -0
  48. package/src/adapters/definitions/native-cli-entry-qwen.ts +2 -0
  49. package/src/adapters/definitions/native-cli-entry-types.ts +3 -1
  50. package/src/adapters/definitions/native-cli-jcode-home-init.ts +1 -1
  51. package/src/adapters/definitions/native-cli-preview-common.ts +1 -1
  52. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  53. package/src/adapters/jcode.ts +16 -0
  54. package/src/adapters/native-facts-hooks.ts +12 -0
  55. package/src/cli/autonomy-offline.ts +1 -1
  56. package/src/cli/bench.ts +1 -1
  57. package/src/cli/claude-profile-hook.ts +31 -11
  58. package/src/cli/commands/releases.ts +82 -0
  59. package/src/cli/conductor-recovery.ts +1 -1
  60. package/src/cli/facts-hook.ts +11 -4
  61. package/src/cli/help.ts +12 -10
  62. package/src/cli/identity.ts +5 -1
  63. package/src/cli/init-prompt.ts +1 -1
  64. package/src/cli/init-settings.ts +4 -35
  65. package/src/cli/init.ts +1 -1
  66. package/src/cli/json-text-spans.ts +57 -0
  67. package/src/cli/launch-check.ts +157 -0
  68. package/src/cli/launch.ts +19 -1
  69. package/src/cli/main.ts +63 -10
  70. package/src/cli/memory.ts +1 -1
  71. package/src/cli/output.ts +14 -1
  72. package/src/cli/preview.ts +1 -1
  73. package/src/cli/recovery-launch.ts +1 -1
  74. package/src/cli/setup-homes.ts +2 -2
  75. package/src/cli/start-agents-run.ts +85 -7
  76. package/src/cli/start-check.ts +28 -0
  77. package/src/cli/upgrade-runtime.ts +1 -1
  78. package/src/cli/warn-line.ts +1 -1
  79. package/src/hub/ci-watch.ts +311 -79
  80. package/src/hub/config-apply.ts +1 -1
  81. package/src/hub/config.ts +518 -0
  82. package/src/hub/control-client.ts +1 -1
  83. package/src/hub/daemon.ts +76 -513
  84. package/src/hub/delivery-public.ts +11 -0
  85. package/src/hub/hub-check.ts +125 -0
  86. package/src/hub/path-policy.ts +1 -1
  87. package/src/hub/permission-mode.ts +3 -40
  88. package/src/hub/permission-paths.ts +41 -0
  89. package/src/hub/recovery-policy.ts +1 -1
  90. package/src/hub/releases-inventory.ts +198 -0
  91. package/src/hub/runtime-capture-prune.ts +25 -3
  92. package/src/hub/runtime-prune-health.ts +8 -1
  93. package/src/hub/sdlc-release-authorization.ts +42 -21
  94. package/src/hub/sdlc-release-diagnostics.ts +5 -0
  95. package/src/hub/sdlc-release-policy.ts +21 -7
  96. package/src/hub/sdlc-release.ts +80 -20
  97. package/src/hub/sdlc.ts +7 -3
  98. package/src/hub/tasks.ts +138 -36
  99. package/src/ui/plugin.ts +1 -1
@@ -0,0 +1,82 @@
1
+ import { Report, asciiMarkers, resolveColor, streamEnv, terminalText } from "../console-state.ts";
2
+ import { listReleases, pruneReleases, RELEASE_KINDS, type PruneResult, type ReleaseEntry, type ReleaseInventory, type ReleaseKind } from "../../hub/releases-inventory.ts";
3
+
4
+ /** #1781: `ahub releases list` and `ahub releases prune`. Console authority only: classifyPeerCommand has no entry, so an agent shell is refused before this runs. */
5
+ export const RELEASES_USAGE = "usage: ahub releases list [--json] | ahub releases prune [--kind <capture|coordinator-source|registry-install>] [--older-than <days>] [--apply] [--json]";
6
+ export interface ReleasesOutcome { code: number; error?: string; next?: string }
7
+ interface Parsed { op: "list" | "prune"; json: boolean; apply: boolean; kind?: ReleaseKind; olderThanDays?: number; color?: string; ascii: boolean }
8
+
9
+ export function parseReleasesArgs(args: readonly string[]): Parsed | string {
10
+ const op = args[0];
11
+ if (op !== "list" && op !== "prune") return RELEASES_USAGE;
12
+ const parsed: Parsed = { op, json: false, apply: false, ascii: false };
13
+ for (let i = 1; i < args.length; i++) {
14
+ const arg = args[i]!;
15
+ if (arg === "--json" && !parsed.json) parsed.json = true;
16
+ else if (arg === "--ascii") parsed.ascii = true;
17
+ else if (arg.startsWith("--color=") && parsed.color === undefined) parsed.color = arg.slice("--color=".length);
18
+ else if (op === "prune" && arg === "--apply" && !parsed.apply) parsed.apply = true;
19
+ else if (op === "prune" && arg === "--kind" && parsed.kind === undefined) {
20
+ const value = args[++i];
21
+ if (!value || !(RELEASE_KINDS as readonly string[]).includes(value)) return RELEASES_USAGE;
22
+ parsed.kind = value as ReleaseKind;
23
+ } else if (op === "prune" && arg === "--older-than" && parsed.olderThanDays === undefined) {
24
+ const value = args[++i];
25
+ if (!value || !/^(0|[1-9][0-9]{0,5})$/.test(value)) return RELEASES_USAGE;
26
+ parsed.olderThanDays = Number(value);
27
+ } else return RELEASES_USAGE;
28
+ }
29
+ return parsed;
30
+ }
31
+
32
+ const size = (bytes: number): string => bytes >= 1 << 30 ? `${(bytes / (1 << 30)).toFixed(1)} GiB` : bytes >= 1 << 20 ? `${(bytes / (1 << 20)).toFixed(1)} MiB` : `${Math.ceil(bytes / 1024)} KiB`;
33
+ /** Sum only leaf entries: a legacy install already measures the captures and registry/ listed beside it. */
34
+ const total = (entries: readonly ReleaseEntry[]) => size(entries.filter(entry => !entries.some(other => other !== entry && other.path.startsWith(`${entry.path}/`))).reduce((sum, entry) => sum + entry.bytes, 0));
35
+ const view = (entry: ReleaseEntry) => ({ name: entry.name, path: entry.path, kind: entry.kind, version: entry.version, digest: entry.digest, bytes: entry.bytes,
36
+ modified: new Date(entry.modified).toISOString(), referencedBy: entry.referencedBy, removable: !entry.kept, ...(entry.kept ? { kept: entry.kept } : {}) });
37
+
38
+ function renderInventory(inventory: ReleaseInventory, report: Report, title: string): Report {
39
+ report.titled("ahub", title, `${inventory.entries.length} entries, ${total(inventory.entries)}`);
40
+ if (!inventory.complete) report.section("Attention").bullet("warn", `${terminalText(inventory.cause ?? "references could not be read")}; every entry is kept`).next(inventory.next ?? "ahub doctor");
41
+ for (const kind of [...RELEASE_KINDS, "unknown"] as const) {
42
+ const rows = inventory.entries.filter(entry => entry.kind === kind);
43
+ if (!rows.length) continue;
44
+ report.section(kind, `${rows.length}, ${total(rows)}`);
45
+ for (const entry of rows) report.bullet(entry.kept ? "active" : "ok", `${terminalText(entry.name)} ${size(entry.bytes)} ${entry.kept ? terminalText(entry.kept) : "unreferenced"}`);
46
+ }
47
+ return report;
48
+ }
49
+
50
+ export async function runReleasesCommand(args: readonly string[], home: string, env: NodeJS.ProcessEnv = process.env, deps: Parameters<typeof listReleases>[1] = {}): Promise<ReleasesOutcome> {
51
+ const parsed = parseReleasesArgs(args);
52
+ if (typeof parsed === "string") return { code: 2, error: parsed };
53
+ const color = resolveColor(parsed.color, streamEnv(!!process.stdout.isTTY), "ahub");
54
+ if (color instanceof Error) return { code: 2, error: RELEASES_USAGE };
55
+ const out = (text: string) => { process.stdout.write(text.endsWith("\n") ? text : `${text}\n`); };
56
+ const report = () => new Report(undefined, asciiMarkers(env, parsed.ascii));
57
+ if (parsed.op === "list") {
58
+ const inventory = listReleases(home, deps);
59
+ if (parsed.json) out(JSON.stringify({ home: inventory.home, complete: inventory.complete, ...(inventory.cause ? { cause: inventory.cause, next: inventory.next } : {}), entries: inventory.entries.map(view) }, null, 2));
60
+ else out(renderInventory(inventory, report(), "Releases").render(color === true).join("\n"));
61
+ return { code: 0 };
62
+ }
63
+ const result: PruneResult = pruneReleases(home, { apply: parsed.apply, ...(parsed.kind ? { kinds: [parsed.kind] } : {}), ...(parsed.olderThanDays !== undefined ? { olderThanDays: parsed.olderThanDays } : {}) }, deps);
64
+ const failed = !result.complete || result.skipped.length > 0;
65
+ if (parsed.json) {
66
+ out(JSON.stringify({ home: result.home, applied: result.applied, complete: result.complete, ...(result.cause ? { cause: result.cause, next: result.next } : {}),
67
+ candidates: result.candidates, removed: result.removed, quarantined: result.quarantined, skipped: result.skipped, kept: result.entries.filter(entry => entry.kept).map(view) }, null, 2));
68
+ } else {
69
+ const r = renderInventory({ ...result, entries: result.entries.filter(entry => entry.kept) }, report(), "Releases prune");
70
+ const names = (paths: readonly string[]) => paths.map(path => result.entries.find(entry => entry.path === path)).filter((entry): entry is ReleaseEntry => !!entry);
71
+ r.section(result.applied ? "Removed" : "Would remove", `${result.applied ? result.removed.length : result.candidates.length}`);
72
+ for (const entry of names(result.applied ? result.removed : result.candidates)) r.bullet("ok", `${terminalText(entry.name)} ${size(entry.bytes)}`);
73
+ if (result.skipped.length) {
74
+ r.section("Skipped", `${result.skipped.length}`);
75
+ for (const item of result.skipped) r.bullet("warn", `${terminalText(item.path)}: ${terminalText(item.why)}`);
76
+ r.next("ahub doctor");
77
+ }
78
+ if (!result.applied) r.note(result.candidates.length ? "nothing was changed; add --apply to remove these" : "nothing to remove");
79
+ out(r.render(color === true).join("\n"));
80
+ }
81
+ return { code: failed && parsed.apply || !result.complete ? 1 : 0 };
82
+ }
@@ -1,7 +1,7 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { ControlClient, readControl } from "../hub/control-client.ts";
4
- import { loadConfig, type HubConfig } from "../hub/daemon.ts";
4
+ import { loadConfig, type HubConfig } from "../hub/config.ts";
5
5
  import { captureRecoveryPolicy, readRecoveryPolicyInputs, type RecoveryPolicyInputs } from "../hub/recovery-policy.ts";
6
6
  import { authorizeConductorRecovery, assertConductorRecovery, retireConductorRecovery, RecoveryAuthorityError, type ConductorRecoveryBinding } from "../hub/recovery-authority.ts";
7
7
  import { operationPath } from "../hub/recovery-store.ts";
@@ -1,14 +1,15 @@
1
1
  #!/usr/bin/env bun
2
2
  import { claudePeer as defaultChannelPeer } from "../hub/claude-state.ts";
3
- import { definitionOf } from "../adapters/registry.ts";
3
+ import { nativeFactsHook } from "../adapters/native-facts-hooks.ts";
4
4
  // Managed Claude hook transport for turn-free facts, native observations and runtime permissions.
5
5
  // PreToolUse preserves facts additionalContext and adds permission decisions; other phases observe only.
6
6
  // A failed or timed-out hub decides nothing, leaving Claude's native permission rules in effect.
7
7
  import { relative, resolve, isAbsolute } from "node:path";
8
8
  import { matchesPolicy } from "../hub/path-policy.ts";
9
9
  import { realPath } from "../hub/project.ts";
10
- import { isAgentConfigPath, isInstructionPath, isPermissionMode, hardLinked, isHubWritePath } from "../hub/permission-mode.ts";
10
+ import { isAgentConfigPath, isInstructionPath, isPermissionMode, hardLinked, isHubWritePath } from "../hub/permission-paths.ts";
11
11
  import { ControlClient } from "../hub/control-client.ts";
12
+ import { startCheck } from "./start-check.ts";
12
13
 
13
14
  /** A library call may target another hub; only the managed command hook inherits that target's native identity. */
14
15
  export function nativeHookIdentity(stateDir: string, peer: string, env: NodeJS.ProcessEnv = process.env): { nativeInstanceId?: string; nativeLaunchId?: string; hookPurpose?: string } {
@@ -62,7 +63,7 @@ export function scopedWriteBlocked(phase: string, permission: unknown, tool: unk
62
63
  export async function factsHook(stdin: string, stateDir: string, peer: string, timeoutMs = 2000, nativeEvent?: string): Promise<string | undefined> {
63
64
  if (nativeEvent !== undefined) {
64
65
  if (Buffer.byteLength(stdin, "utf8") > 1024 * 1024) return undefined;
65
- const port = definitionOf(peer)?.hooks?.factsHook;
66
+ const port = nativeFactsHook(peer);
66
67
  const payload: unknown = JSON.parse(stdin);
67
68
  const decoded = port?.decode(nativeEvent, payload);
68
69
  if (!port || !decoded) return undefined;
@@ -110,7 +111,13 @@ export async function factsHook(stdin: string, stateDir: string, peer: string, t
110
111
  if (import.meta.main) {
111
112
  try {
112
113
  const stateDir = process.env.AGENTHUB_STATE_DIR;
113
- const out = stateDir ? await factsHook(await Bun.stdin.text(), stateDir, process.env.AGENTHUB_PEER_ID ?? defaultChannelPeer(undefined), 2000, process.env.AGENTHUB_HOOK_EVENT) : undefined;
114
+ const peer = process.env.AGENTHUB_PEER_ID ?? defaultChannelPeer(undefined);
115
+ let out: string | undefined;
116
+ if (process.env.AGENTHUB_HOOK_PURPOSE === "start-check") {
117
+ // #1798 T3: this exact purpose runs the session-start Hub check and never reaches `factsHook`, even on an error: it sends no facts or native_facts request.
118
+ const document = stateDir ? await startCheck(await Bun.stdin.text(), stateDir, peer, process.env.AGENTHUB_LAUNCH_ID || undefined) : undefined; // display only: the daemon compares it with the attached socket's own launch id
119
+ out = document ? JSON.stringify(document) : undefined;
120
+ } else out = stateDir ? await factsHook(await Bun.stdin.text(), stateDir, peer, 2000, process.env.AGENTHUB_HOOK_EVENT) : undefined;
114
121
  if (out) console.log(out);
115
122
  } catch {
116
123
  // a hook that fails must not get in the way of the tool call
package/src/cli/help.ts CHANGED
@@ -40,7 +40,7 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
40
40
  ["ahub completion zsh|bash|fish", "print a shell completion script; its candidates come from these help entries"],
41
41
  ]],
42
42
  ["Daemon and runtime", [
43
- ["ahub up [--unattended] [--no-console] [--no-agents]", "start the daemon, then ask it to start this project's default agents (start.agents, claude and codex unless chosen at setup; one line each, a refusal names the manual command; --no-agents skips them), then enter console in an interactive terminal"],
43
+ ["ahub up [--unattended] [--no-console] [--no-agents] [--wait <seconds>] [--json]", "start the daemon, then ask it to start this project's default agents (start.agents, claude and codex unless chosen at setup; one line each, a refusal names the manual command; --no-agents skips them), wait up to --wait seconds (default 15, at most 600) for the started agents to attach and print a Hub check, one line per agent (a started agent still not attached is pending, a refused one shows its refusal and next step; --json prints one JSON document and does not enter the console), then enter console in an interactive terminal"],
44
44
  ["ahub console [--panels] [--color=auto|always|never]", "enter the human console; P cycles built-in pet characters/off; exiting leaves the daemon running"],
45
45
  ["ahub console --no-pet", "turn off attention for this session; combines with --panels and --color"],
46
46
  ["ahub pet [--short]", "read attention without connecting; --short prints ahub!N only when action is needed"],
@@ -140,6 +140,8 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
140
140
  ["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"],
141
141
  ["ahub backlog pull|return <id>", "person only: pull backlog into To Do or return ownerless proposed work; --backlog on task propose stages unoffered work"],
142
142
  ["ahub smoke run qwen-dual-output --project-id <id> --receipt <file.json> [--timeout-ms <100..120000>] [--json]", "requires the leading --live-test flag; disposable temporary project only: Q2 dual-file submit and queued second submit; isolated native HOME, owned-process cleanup and a counts/timings receipt; requires OPENAI_API_KEY, OPENAI_BASE_URL and OPENAI_MODEL; real-account live proof remains a separate person leg"],
143
+ ["ahub releases list [--json]", "person only: every entry under the hub home's releases directory with its kind (capture, coordinator-source, registry-install, unknown), version, digest, size and what refers to it"],
144
+ ["ahub releases prune [--kind <capture|coordinator-source|registry-install>] [--older-than <days>] [--apply] [--json]", "person only: preview what nothing refers to (no project runtime.json, recovery operation or live process); --apply removes it after rechecking each entry. An unreadable reference keeps the entry; unknown layouts and symlinks are never removed"],
143
145
  ["ahub broker serve [--hostname <host>] [--port <0..65535>] [--public-url <ws[s]://host/>] [--owner <fingerprint>]... [--state-dir <dir>]", "person only: standalone ciphertext relay; default loopback port 8788, public WSS needs owner allowlist and TLS termination"],
144
146
  ["ahub broker room drop <room> --yes [--state-dir <dir>]", "person only, broker stopped: forget one room's pins, floors and queued ciphertext; other rooms stay intact"],
145
147
  ["ahub room create <name> --broker <url> [--label <id>] | invite <name> [--accept <request>] | join <token> [--name <name>] [--label <id>] | join <name> --roster <signed-roster> | leave <name> | revoke <name> <fingerprint> | expose <name> [<peer>...] [--confirm <member-fingerprint-prefix>]", "person only, never --live-test: every mutation displays both fingerprints, then requires TTY y/N (default No) or --confirm matching 16..64 lowercase hex of the member fingerprint; exchange artifacts out of band, never invitation secrets through the broker"],
@@ -220,10 +222,10 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
220
222
  ["ahub facts --hook", "turn-free facts as a Claude Code PreToolUse, PostToolUse and Stop hook (issue #108); never blocks"],
221
223
  ]],
222
224
  ["Dashboard", [
223
- ["ahub ui [--no-open]", "open the local dashboard with configured attention character (or print its one-time link)"],
224
- ["ahub ui --settings [--no-open]", "human only: open it with a settings session, which for 15 minutes may change permission modes, routing, start settings and structural config"],
225
- ["ahub ui --all [--no-open]", "open the unified project dashboard"],
226
- ["ahub ui --all --stop", "stop only the dashboard manager"],
225
+ ["ahub ui [--no-open [--json]]", "open the local dashboard with configured attention character (or print its one-time link; --no-open --json prints readiness)"],
226
+ ["ahub ui --settings [--no-open [--json]]", "human only: open it with a settings session, which for 15 minutes may change permission modes, routing, start settings and structural config"],
227
+ ["ahub ui --all [--no-open [--json]]", "open the unified project dashboard; --no-open --json prints readiness"],
228
+ ["ahub ui --all --stop [--json]", "stop only the dashboard manager; --json prints a stop receipt"],
227
229
  ["ahub manager", "internal: the dashboard manager process that ahub ui --all starts"],
228
230
  ]],
229
231
  ];
@@ -269,7 +271,7 @@ const SUMMARIES: Readonly<Record<string, string>> = {
269
271
  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",
270
272
  pause: "hold or release a peer's deliveries", title: "rename a Pi or local-worker session", queue: "inspect and resolve durable deliveries",
271
273
  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",
272
- 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)",
274
+ release: "plan and ship releases", releases: "list and prune hub runtime copies", smoke: "live smoke test in a temporary project", broker: "run the ciphertext relay for rooms", room: "encrypted rooms between hubs (person only)",
273
275
  source: "register inputs as content-hashed sources", schedule: "list and run machine-local schedules", intake: "turn a plain request into a draft backlog card",
274
276
  capabilities: "list the skills each attached peer offers", learn: "review recurring-criterion candidates", study: "research campaign contracts",
275
277
  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",
@@ -328,7 +330,7 @@ export const EXAMPLES: Readonly<Record<string, readonly string[]>> = {
328
330
  autonomy: ["ahub autonomy status"], model: ["ahub model list"], settings: ["ahub settings list"], pause: ["ahub pause codex"], resume: ["ahub resume codex"],
329
331
  title: ["ahub title pi release review"], queue: ["ahub queue list --peer codex"], board: ["ahub board --ready"],
330
332
  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"],
331
- smoke: ["ahub smoke run qwen-dual-output --project-id 1f3a --receipt receipt.json"], broker: ["ahub broker serve --port 8787"], room: ["ahub room list"],
333
+ smoke: ["ahub smoke run qwen-dual-output --project-id 1f3a --receipt receipt.json"], broker: ["ahub broker serve --port 8787"], releases: ["ahub releases list"], room: ["ahub room list"],
332
334
  source: ["ahub source list"], schedule: ["ahub schedule list"], intake: ["ahub intake \"Add a dark mode toggle\""], capabilities: ["ahub capabilities --json"], learn: ["ahub learn list"],
333
335
  study: ["ahub study show --json"], deliverables: ["ahub deliverables --task 12 --check"], review: ["ahub review 12 approved looks good", "ahub review brief 12"],
334
336
  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"],
@@ -399,7 +401,7 @@ export const FLAG_DESCRIPTIONS: Readonly<Record<string, string>> = {
399
401
  "--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", "--all-stopped": "retarget every stopped project's runtime",
400
402
  "--version": "print the installed version",
401
403
  // daemon, agents and recovery
402
- "--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",
404
+ "--unattended": "no permission prompts; the agent acts alone", "--no-console": "do not enter the console", "--no-agents": "do not start the default agents", "--wait": "attach wait in seconds (default 15, max 600)", "--panels": "start in panels mode",
403
405
  "--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",
404
406
  "--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",
405
407
  "--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",
@@ -423,7 +425,7 @@ export const FLAG_DESCRIPTIONS: Readonly<Record<string, string>> = {
423
425
  "--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",
424
426
  "--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",
425
427
  "--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",
426
- "--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",
428
+ "--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", "--older-than": "only entries not changed for this many days",
427
429
  "--machine": "only entries from this machine", "--hops": "graph depth: 1 or 2", "--history": "include superseded and expired entries", "--ungrouped": "show individual same-task search hits", "--as-of": "memory as it stood at this time", "--remote": "private git remote to sync with",
428
430
  "--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",
429
431
  "--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",
@@ -433,7 +435,7 @@ export const FLAG_DESCRIPTIONS: Readonly<Record<string, string>> = {
433
435
  "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",
434
436
  "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",
435
437
  "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)",
436
- "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",
438
+ "broker --owner": "owner fingerprint allowed (repeatable)", "releases --kind": "capture, source or registry install", "study --after": "continue after this id", "--live-test --project": "project to run the command in", "task --project": "project to hand the work to",
437
439
  "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)",
438
440
  };
439
441
  /** 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. */
@@ -20,6 +20,8 @@ export function liveTestRefusal(command: string, args: readonly string[], contex
20
20
  if (command === "sdlc" && args[0] === "configure") return true;
21
21
  // #1540: retargeting a stopped project's runtime or every stopped one is the person's choice of which code runs next; an agent shell must not reach it through `--live-test`.
22
22
  if (command === "upgrade" && args.includes("--all-stopped")) return true;
23
+ // #1781: removing shared release entries across every project is the person's act; an agent shell must not reach `releases prune --apply` through `--live-test`. Preview and `releases list` stay delegable.
24
+ if (command === "releases" && args[0] === "prune" && args.includes("--apply")) return true;
23
25
  if (command === "lineage" && args[0] === "link") return true;
24
26
  if (command === "guidance" && ["create", "withdraw"].includes(args[0] ?? "")) return true;
25
27
  if (command === "sdlc" && args[0] === "survey" && args[1] !== "show") return true;
@@ -243,6 +245,8 @@ export function cliCommandLabel(command: string, args: readonly string[], catalo
243
245
  // #508: the registry's two forms are named in the audit and in a refusal, never their operands (a path or a URL can carry a secret).
244
246
  if (command === "smoke") return args[0] === "run" ? "smoke run" : "smoke";
245
247
  if (command === "broker") return args[0] === "serve" ? "broker serve" : args[0] === "room" && args[1] === "drop" ? "broker room drop" : "broker";
248
+ // #1781: the audit and a refusal name the subcommand only, never a flag value.
249
+ if (command === "releases") return ["list", "prune"].includes(args[0] ?? "") ? `releases ${args[0]}` : "releases";
246
250
  if (command === "room" && args[0] === "inbox") return ["show", "done", "discard"].includes(args[1] ?? "") && args[2] && args[2] !== "--json" ? `room inbox ${args[1]}` : "room inbox list";
247
251
  if (command === "room") return ["create", "invite", "join", "leave", "revoke", "expose", "resolve", "list", "status"].includes(args[0] ?? "") ? `room ${args[0]}` : "room";
248
252
  // #335: a schedule id is config text, so the audit names the subcommand only.
@@ -266,7 +270,7 @@ export function cliCommandLabel(command: string, args: readonly string[], catalo
266
270
  if (command === "specs") return ["list", "check", "covers", "stamp"].includes(args[0] ?? "") ? `specs ${args[0]}` : "specs";
267
271
  // #1057: the audit names the subcommand and whether it confirms, never a path, a branch or a fingerprint.
268
272
  if (command === "worktrees") return args[0] === "tidy" ? (args.some(arg => arg === "--confirm" || arg.startsWith("--confirm=")) ? "worktrees tidy confirm" : "worktrees tidy") : "worktrees";
269
- 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", "instruction-hook", "instructed", "check-path", "turns", "undo", "kill", "down", "reset", "doctor", "agents", "source", "broker", "schedule", "intake", "learn", "study"].includes(command)) return "unknown";
273
+ 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", "instruction-hook", "instructed", "check-path", "turns", "undo", "kill", "down", "reset", "doctor", "agents", "source", "releases", "broker", "schedule", "intake", "learn", "study"].includes(command)) return "unknown";
270
274
  if (["task", "queue", "budget", "route", "recovery", "models", "projects", "research", "memory", "goal", "bench", "agents", "roster", "settings"].includes(command)) {
271
275
  const sub = command === "bench" || command === "memory" || command === "goal" ? args.find((arg) => arg !== "--json") : args[0];
272
276
  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}`;
@@ -14,7 +14,7 @@ import { INIT_SETTINGS, TRACK_CONFIG, SDLC_MODES, SPEC_REVIEW_MODES, COORDINATIO
14
14
  import { readFileSync } from "node:fs";
15
15
  import { join } from "node:path";
16
16
  import { PROFILE_NAMES } from "../hub/profiles.ts";
17
- import { DEFAULT_CONFIG } from "../hub/daemon.ts";
17
+ import { DEFAULT_CONFIG } from "../hub/config.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
20
  import { NO_CONDUCTOR, PERSON_REVIEWS, ROLE_FLAGS, eligiblePeers, parseRoleFlag, roleKeyOf, type RoleFlag } from "./init-roles.ts";
@@ -1,3 +1,4 @@
1
+ import { objectSpan, skip, type ObjectSpan } from "./json-text-spans.ts";
1
2
  /**
2
3
  * #1065 T1: the settings `ahub init` can set, as one table. A row names the flag, the file and key it writes, the closed set of values it accepts and how
3
4
  * to read it back, so a new setting (the specs rows of #1064 T3) is one more row here and nothing else. Executables, secrets, models, providers, instances
@@ -43,6 +44,9 @@ const choice = <T extends string>(id: string, flag: string, values: readonly T[]
43
44
 
44
45
  /** #1645 T4: the commented `[risk]` example a newly created sdlc.toml carries, so the tier table is discoverable without a project being opted in. */
45
46
  const RISK_SCAFFOLD = [
47
+ "# Automatic reruns for one failed required shard on a ready PR (#1801). Default is 0 (off).",
48
+ "# ci_shard_retries = 0",
49
+ "",
46
50
  "# Minimum review by risk tier (#1645): globs that make a change high, or that keep it low. A path no pattern names is medium, and a",
47
51
  "# path under [security] is always high. With this table commented out no tier is derived and every review stays as it is today.",
48
52
  "# [risk]",
@@ -139,41 +143,6 @@ export function parseInitSettings(args: readonly string[]): { request: InitSetti
139
143
  const isObject = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
140
144
  const valueAt = (doc: Record<string, unknown>, path: readonly string[]): unknown => path.reduce<unknown>((at, key) => isObject(at) ? at[key] : undefined, doc);
141
145
 
142
- // ---- A text-level JSON editor: it changes one key and leaves every other byte of the file where it was (AC2: the formatting of untouched keys is preserved). ----
143
- // The input is always text JSON.parse already accepted, so the scanner only has to find where values start and end.
144
- const skip = (text: string, at: number): number => { while (at < text.length && /\s/.test(text[at]!)) at++; return at; };
145
- function stringEnd(text: string, at: number): number { at++; while (text[at] !== '"') { if (text[at] === "\\") at++; at++; } return at + 1; }
146
- interface Member { key: string; keyStart: number; valueStart: number; valueEnd: number }
147
- interface ObjectSpan { start: number; end: number; members: Member[] }
148
- function valueEnd(text: string, from: number): number {
149
- let at = skip(text, from);
150
- const c = text[at];
151
- if (c === '"') return stringEnd(text, at);
152
- if (c === "{") return objectSpan(text, at).end;
153
- if (c === "[") {
154
- at = skip(text, at + 1);
155
- if (text[at] === "]") return at + 1;
156
- for (;;) { at = skip(text, valueEnd(text, at)); if (text[at] === ",") { at = skip(text, at + 1); continue; } return at + 1; }
157
- }
158
- while (at < text.length && !/[\s,\]}]/.test(text[at]!)) at++;
159
- return at;
160
- }
161
- function objectSpan(text: string, start: number): ObjectSpan {
162
- const members: Member[] = [];
163
- let at = skip(text, start + 1);
164
- if (text[at] === "}") return { start, end: at + 1, members };
165
- for (;;) {
166
- at = skip(text, at);
167
- const keyStart = at, keyEnd = stringEnd(text, at);
168
- const key = JSON.parse(text.slice(keyStart, keyEnd)) as string;
169
- at = skip(text, skip(text, keyEnd) + 1);
170
- const end = valueEnd(text, at);
171
- members.push({ key, keyStart, valueStart: at, valueEnd: end });
172
- at = skip(text, end);
173
- if (text[at] === ",") { at++; continue; }
174
- return { start, end: at + 1, members };
175
- }
176
- }
177
146
  const indentOf = (text: string, at: number): string => { const lineStart = text.lastIndexOf("\n", at - 1) + 1; return /^[ \t]*/.exec(text.slice(lineStart))![0]; };
178
147
  /** A value as the project's own files write it: scalars as JSON, a list of scalars on one line, an object over lines (or one line when `inline`). */
179
148
  function render(value: unknown, indent: string, inline: boolean): string {
package/src/cli/init.ts CHANGED
@@ -12,7 +12,7 @@ import { realPath } from "../hub/project.ts";
12
12
  import { hubGitArgv, hubGitEnv, hubGitSync } from "../hub/git.ts";
13
13
  import { KIMI_MCP_FILE } from "./kimi-mcp.ts";
14
14
  import { AGY_PLUGIN_FILES } from "./agy-mcp.ts";
15
- import { DEFAULT_CONFIG, loadConfig } from "../hub/daemon.ts";
15
+ import { DEFAULT_CONFIG, loadConfig } from "../hub/config.ts";
16
16
  import { ALL_MACHINE_LOCAL } from "../hub/config-trust.ts";
17
17
  import { requiredChecksFor } from "../hub/sdlc-merge.ts";
18
18
  import { githubOriginRepository } from "../hub/task-repository.ts";
@@ -0,0 +1,57 @@
1
+ // The input is always text JSON.parse already accepted, so the scanner only has to find where values start and end.
2
+ export const skip = (text: string, at: number): number => { while (at < text.length && /\s/.test(text[at]!)) at++; return at; };
3
+ function stringEnd(text: string, at: number): number { at++; while (text[at] !== '"') { if (text[at] === "\\") at++; at++; } return at + 1; }
4
+ interface Member { key: string; keyStart: number; valueStart: number; valueEnd: number }
5
+ export interface ObjectSpan { start: number; end: number; members: Member[] }
6
+ function valueEnd(text: string, from: number): number {
7
+ let at = skip(text, from);
8
+ const c = text[at];
9
+ if (c === '"') return stringEnd(text, at);
10
+ if (c === "{") return objectSpan(text, at).end;
11
+ if (c === "[") {
12
+ at = skip(text, at + 1);
13
+ if (text[at] === "]") return at + 1;
14
+ for (;;) { at = skip(text, valueEnd(text, at)); if (text[at] === ",") { at = skip(text, at + 1); continue; } return at + 1; }
15
+ }
16
+ while (at < text.length && !/[\s,\]}]/.test(text[at]!)) at++;
17
+ return at;
18
+ }
19
+ export function objectSpan(text: string, start: number): ObjectSpan {
20
+ const members: Member[] = [];
21
+ let at = skip(text, start + 1);
22
+ if (text[at] === "}") return { start, end: at + 1, members };
23
+ for (;;) {
24
+ at = skip(text, at);
25
+ const keyStart = at, keyEnd = stringEnd(text, at);
26
+ const key = JSON.parse(text.slice(keyStart, keyEnd)) as string;
27
+ at = skip(text, skip(text, keyEnd) + 1);
28
+ const end = valueEnd(text, at);
29
+ members.push({ key, keyStart, valueStart: at, valueEnd: end });
30
+ at = skip(text, end);
31
+ if (text[at] === ",") { at++; continue; }
32
+ return { start, end: at + 1, members };
33
+ }
34
+ }
35
+ /** Replace one existing value in validated JSON without re-encoding the surrounding text. */
36
+ export function replaceJsonValue(text: string, path: readonly (string | number)[], value: string): string {
37
+ let start = skip(text, 0);
38
+ let end = valueEnd(text, start);
39
+ for (const key of path) {
40
+ if (typeof key === "number" && text[start] === "[") {
41
+ let at = skip(text, start + 1);
42
+ for (let index = 0; index < key && text[at] !== "]"; index++) {
43
+ const separator = skip(text, valueEnd(text, at));
44
+ at = text[separator] === "," ? skip(text, separator + 1) : separator;
45
+ }
46
+ if (text[at] === "]") throw new Error("JSON array value is missing");
47
+ start = at;
48
+ end = valueEnd(text, start);
49
+ continue;
50
+ }
51
+ const member = text[start] === "{" ? objectSpan(text, start).members.findLast(item => item.key === key) : undefined;
52
+ if (!member) throw new Error("JSON object member is missing");
53
+ start = member.valueStart;
54
+ end = member.valueEnd;
55
+ }
56
+ return text.slice(0, start) + JSON.stringify(value) + text.slice(end);
57
+ }
@@ -0,0 +1,157 @@
1
+ import type { HubCheck } from "../hub/hub-check.ts";
2
+ import { HUB_CHECK_UNAVAILABLE, expectedHubLink, renderHubCheck, renderHubCheckUnavailable } from "../hub/hub-check.ts";
3
+ import type { AdapterDefinition, StartForm } from "../adapters/registry-types.ts";
4
+ import { plain } from "./warn-line.ts";
5
+
6
+ /**
7
+ * #1798 T3: the pre-launch and in-session surfaces render the one hub check the daemon returned in its status reply. Nothing here
8
+ * recomputes a link state or the expected link (`expectedHubLink` stays the only rule). A row carries ids, states, counts and commands.
9
+ */
10
+
11
+ /** One total bound for a launch-time read: connect, request and any retry share it. A slow or silent hub costs at most this long. */
12
+ const LAUNCH_CHECK_TOTAL_MS = 3_000;
13
+
14
+ /** One connection attempt (no retry, no instance check, no retry message) that gives up after `timeoutMs`. */
15
+ interface LaunchCheckClient { request(msg: { t: "status" }, timeoutMs?: number): Promise<{ status?: { hubCheck?: HubCheck } } | undefined>; close(): void }
16
+ type LaunchCheckConnect = (timeoutMs: number) => Promise<LaunchCheckClient>;
17
+
18
+ /**
19
+ * Read the check once under one total deadline: connecting gets the time left, the status request gets what is left after that. At the
20
+ * deadline any open client is closed, and a connection that opens late is closed at once with no request sent. It never throws and leaves
21
+ * no timer or socket behind, so nothing of it can outlive the launch it precedes.
22
+ */
23
+ export async function readLaunchCheck(connectOnce: LaunchCheckConnect, totalMs = LAUNCH_CHECK_TOTAL_MS): Promise<HubCheck | undefined> {
24
+ const deadline = Date.now() + totalMs;
25
+ let expired = false;
26
+ let open: LaunchCheckClient | undefined;
27
+ let timer: ReturnType<typeof setTimeout> | undefined;
28
+ const closeOpen = () => { const client = open; open = undefined; try { client?.close(); } catch { /* already closed */ } };
29
+ const attempt = (async (): Promise<HubCheck | undefined> => {
30
+ const client = await connectOnce(Math.max(1, deadline - Date.now()));
31
+ if (expired) { try { client.close(); } catch { /* already closed */ } return undefined; }
32
+ open = client;
33
+ const reply = await client.request({ t: "status" }, Math.max(1, deadline - Date.now()));
34
+ const check = reply?.status?.hubCheck;
35
+ return check && Array.isArray(check.peers) ? check : undefined;
36
+ })().catch(() => undefined);
37
+ try {
38
+ return await Promise.race([attempt, new Promise<undefined>(resolve => { timer = setTimeout(() => { expired = true; closeOpen(); resolve(undefined); }, totalMs); })]);
39
+ } catch { return undefined; }
40
+ finally { if (timer) clearTimeout(timer); closeOpen(); }
41
+ }
42
+
43
+ /** A daemon-supplied line cleaned for a terminal or a hook document: no control codes, and no line break that could add a line. */
44
+ export function cleanLine(line: string): string { return plain(line.replace(/[\r\n]+/g, " ")); }
45
+
46
+ /**
47
+ * The lines to print for one peer before it launches. The agent has not started, so nothing here is an OK or a warning about it: one neutral line says it is
48
+ * starting, with its expected link (from its row, else the shared rule for this definition and form), its queued count and `ahub status` to check after it
49
+ * starts. A row that is not offline adds its state, labelled as the state before this launch, without its mark or next step. A check that could not be read
50
+ * is the only warning, with its next step.
51
+ */
52
+ function renderLaunchCheck(check: HubCheck | undefined, peer: string, definition: Pick<AdapterDefinition, "transport" | "attach"> | undefined, form: StartForm): string[] {
53
+ if (!check) return renderHubCheckUnavailable(HUB_CHECK_UNAVAILABLE);
54
+ const row = check.peers.find(item => item.id === peer);
55
+ const expected = row?.expected ?? expectedHubLink(definition, form);
56
+ const lines = [renderHubCheck(check, [])[0]!, ` ${peer}: starting, expected link ${expected}, ${row ? `${row.queued} queued` : "queue unknown"}; check again after it starts: ahub status`];
57
+ if (row && row.observed !== "offline") lines.push(` state before this launch: ${row.observed}${row.cause ? `, ${row.cause}` : ""}`);
58
+ return lines;
59
+ }
60
+
61
+ /** The words the classifier rejects exactly (`DISABLING` in claude-channel-evidence.ts), printed only by these fixed names. */
62
+ const FIXED_WORDS = new Set(["--background", "--detach", "--daemon", "daemon", "bg", "bg-spare"]);
63
+ /** A fixed name for a rejected token, never the token itself: a prompt word or the text after `=` must not reach the check line (AC5). */
64
+ function fixedName(token: string | undefined): string | undefined {
65
+ if (token === undefined) return undefined;
66
+ if (token.startsWith("-p")) return "-p";
67
+ for (const flag of ["--print", "--output-format", "--dangerously-load-development-channels"]) if (token.startsWith(flag)) return flag;
68
+ return FIXED_WORDS.has(token) ? token : undefined;
69
+ }
70
+
71
+ /**
72
+ * The next step for a Claude launch whose final argv the channel classifier refused. `command` is the same flattened command the classifier read
73
+ * (`[cmd, ...args].join(" ")`) and `position` the index it rejected, undefined when the command was too long or held control characters.
74
+ * The classifier itself is unchanged; this words the advice by the one rejected token and prints only a fixed name for it.
75
+ */
76
+ export function claudeArgvNextStep(command: string, position: number | undefined): string {
77
+ if (position === undefined) return "Shorten the arguments passed to ahub claude (long command lines and control characters are not attested), then run it again.";
78
+ if (position <= 2) return `Try ahub claude --session-id "$(uuidgen | tr 'A-Z' 'a-z')" and report it on #1798`;
79
+ const name = fixedName(command.trim().split(/\s+/)[position]);
80
+ if (name === undefined) return "Remove the argument at that position, or start ahub claude without your prompt and type it in the session; the channel is not attested while it is there.";
81
+ return `${name} runs Claude without its channel or changes which channels load, so no hub link can attach; start without ${name}, and if it is a word in your prompt, start ahub claude without the prompt and type it in the session.`;
82
+ }
83
+
84
+ /** The reply of one status read, as the hook sees it: the hub's check and, for a Claude tools connection, the display hint. */
85
+ export interface StartHookReading { hubCheck?: HubCheck; thisLaunch?: boolean }
86
+
87
+ /** A check that must stay clearly below the hook entry's own timeout, process start included. */
88
+ export const START_HOOK_TOTAL_MS = 2_500;
89
+ /** The timeout registered for the start entry; the total above must stay under it with room for the process to start. */
90
+ export const START_HOOK_TIMEOUT_S = 5;
91
+ const POLL_MS = 300;
92
+
93
+ export interface StartHookNotice {
94
+ /** One line for the person (`systemMessage`). */
95
+ line: string;
96
+ /** More lines for the model (`additionalContext`); the same facts, no more. */
97
+ lines: string[];
98
+ /** Whether the notice reports a healthy link. Only a verified, healthy Claude link is true. */
99
+ ok: boolean;
100
+ }
101
+
102
+ /** Startup and resume only: a clear or a compact is not a new session start. */
103
+ export function startHookShows(source: unknown): boolean {
104
+ return source === "startup" || source === "resume";
105
+ }
106
+
107
+ type Read = (timeoutMs: number) => Promise<StartHookReading | undefined>;
108
+ /**
109
+ * Read until this peer's link is judged, within one total deadline that covers every attempt. Claude: OK only when `thisLaunch` is true and the row is
110
+ * OK in the same reply; `thisLaunch` false keeps waiting, then ends `pending`; a missing field is "could not be verified", never OK. Nothing here computes a link state: it picks words for the row the daemon returned.
111
+ */
112
+ export async function startHookNotice(peer: string, read: Read, totalMs = START_HOOK_TOTAL_MS, now: () => number = Date.now, sleep: (ms: number) => Promise<unknown> = ms => Bun.sleep(ms)): Promise<StartHookNotice> {
113
+ const deadline = now() + totalMs;
114
+ let last: StartHookReading | undefined;
115
+ for (;;) {
116
+ const left = deadline - now();
117
+ if (left <= 0) break;
118
+ let timer: ReturnType<typeof setTimeout> | undefined;
119
+ try {
120
+ last = await Promise.race([read(left).catch(() => undefined), new Promise<undefined>(resolve => { timer = setTimeout(() => resolve(undefined), left); })]) ?? last;
121
+ } finally { if (timer) clearTimeout(timer); }
122
+ const row = last?.hubCheck?.peers.find(item => item.id === peer);
123
+ const settled = row !== undefined && row.observed !== "offline" && row.observed !== "pending" && last?.thisLaunch !== false;
124
+ if (settled) break;
125
+ if (deadline - now() <= POLL_MS) break;
126
+ await sleep(POLL_MS);
127
+ }
128
+ return startHookWords(peer, last);
129
+ }
130
+
131
+ function startHookWords(peer: string, reading: StartHookReading | undefined): StartHookNotice {
132
+ const check = reading?.hubCheck;
133
+ const row = check?.peers.find(item => item.id === peer);
134
+ const head = check ? `Hub check (agent-hub ${check.version})` : "Hub check";
135
+ const warn = (text: string): StartHookNotice => ({ line: `${head}: ⚠ ${text}`, lines: [`${head}: ⚠ ${text}`], ok: false });
136
+ if (!check || !row) return warn(`${peer}: the check could not be read from the hub; next: ahub status`);
137
+ const queued = row.queued ? `, ${row.queued} queued` : "";
138
+ if (!row.ok) return warn(`${peer}: ${row.observed}${row.cause ? `, ${row.cause}` : ""}${queued}${row.nextStep ? `; next: ${row.nextStep}` : ""}`);
139
+ if (row.observed === "offline" || row.observed === "pending") return warn(`${peer}: pending, not attached yet${queued}; next: ${row.nextStep ?? `ahub status`}`);
140
+ if (reading?.thisLaunch === undefined) return warn(`${peer}: this session's link could not be verified${queued}; next: ahub status`);
141
+ if (reading.thisLaunch === false) return warn(`${peer}: pending, this session has not attached yet${queued}; next: ahub status`);
142
+ const text = `✓ ${peer}: ${row.observed}${queued}`;
143
+ return { line: `${head}: ${text}`, lines: [`${head}: ${text}`], ok: true };
144
+ }
145
+
146
+ /**
147
+ * Pre-launch print from a status snapshot the wrapper already read for this launch (no second read). A snapshot without the check (an older hub), a failed
148
+ * read or a failed callback prints the unavailable warning. Stderr, so a wrapper's own stdout stays what it was.
149
+ */
150
+ export function printLaunchCheck(snapshot: { hubCheck?: HubCheck } | undefined, peer: string, definition?: Pick<AdapterDefinition, "transport" | "attach">, form: StartForm = "tui"): void {
151
+ // #1798 says the wrappers print the check to the terminal: with stderr redirected nothing prints (`ahub status` shows the same state).
152
+ if (process.stderr.isTTY !== true) return;
153
+ // A status snapshot has its own `peers` map: only its `hubCheck` field is the check.
154
+ const candidate = snapshot?.hubCheck;
155
+ const check = candidate && Array.isArray(candidate.peers) ? candidate : undefined;
156
+ for (const line of renderLaunchCheck(check, peer, definition, form)) console.error(cleanLine(line));
157
+ }
package/src/cli/launch.ts CHANGED
@@ -9,6 +9,7 @@ import { processLiveness, processSignature } from "../pi/process-signature.ts";
9
9
  import { realPath } from "../hub/project.ts";
10
10
  import { peerChildEnv, processTable } from "../hub/child-process.ts";
11
11
  import { definitionOf } from "../adapters/registry.ts";
12
+ import { START_HOOK_TIMEOUT_S } from "./launch-check.ts";
12
13
  import type { InstancesConfig } from "../hub/instances.ts";
13
14
  import { kimiAcpCommand } from "../adapters/definitions/native-daemon-kimi.ts";
14
15
  import { warnLine } from "./warn-line.ts";
@@ -256,7 +257,12 @@ function directNativeExecutable(command: string, cwd: string, env: NodeJS.Proces
256
257
  }
257
258
 
258
259
  /** Same native stdio/environment and exit result as spawnSync, with a live child identity before it exits. */
259
- export async function runClaudeLaunch(launch: Launch, options: { cwd: string; env: NodeJS.ProcessEnv; stateDir: string; record?: ClaudeLaunchRecord }): Promise<{ status: number | null; signal: NodeJS.Signals | null; error?: Error }> {
260
+ export async function runClaudeLaunch(launch: Launch, options: { cwd: string; env: NodeJS.ProcessEnv; stateDir: string; record?: ClaudeLaunchRecord; beforeSpawn?: () => Promise<void> | void }): Promise<{ status: number | null; signal: NodeJS.Signals | null; error?: Error }> {
261
+ // #1798 T3: the pre-launch Hub check runs here, at the spawn boundary, next to the executable check it must not outlive. Without the callback there is no added await.
262
+ if (options.beforeSpawn) {
263
+ try { await options.beforeSpawn(); }
264
+ catch { warnLine("the Hub check could not run before the launch", "ahub status"); }
265
+ }
260
266
  const direct = directNativeExecutable(launch.cmd, options.cwd, options.env);
261
267
  return new Promise(resolveResult => {
262
268
  let attestation: Promise<unknown> | undefined;
@@ -311,6 +317,11 @@ export interface FactsHook {
311
317
  purpose?: "facts" | "idle" | "facts-and-idle" | "permission";
312
318
  /** Observe native sessions/turns for every enabled facts, idle or conductor hook configuration. */
313
319
  observeNative?: boolean;
320
+ /**
321
+ * #1798 T3: add the session-start Hub check entry. Opt-in: only the interactive `ahub claude` entry and its preview set it.
322
+ * `claudeObservationHooks` never does, and the headless implementer and benchmarks call `sessionSettings` without it.
323
+ */
324
+ startCheck?: boolean;
314
325
  }
315
326
 
316
327
  /** Shared by actual launch and preview; permissions are always enabled, advisory facts remain disabled. */
@@ -333,6 +344,13 @@ export function sessionSettings(tee?: StatusLineTee, facts?: FactsHook): string
333
344
  settings.hooks = { PreToolUse: [{ matcher: "*", hooks }], ...(facts.purpose !== "permission" ? { PostToolUse: [{ matcher: "*", hooks }], Stop: [{ hooks }] } : {}) };
334
345
  if (facts.observeNative) Object.assign(settings.hooks as object, { SessionStart: [{ matcher: "*", hooks }], UserPromptSubmit: [{ hooks }] });
335
346
  }
347
+ if (facts?.startCheck) {
348
+ // Reads and prints only: its own command, so it records no native session or turn facts and turns on no idle, facts or sweep behavior. Where the
349
+ // observation entry also fires on SessionStart the notice is a second, separate entry in the same array (the check appears once per session start).
350
+ const check = { type: "command", command: `AGENTHUB_STATE_DIR=${sh(facts.stateDir)} AGENTHUB_HOOK_PURPOSE='start-check' bun ${sh(facts.script)}`, timeout: START_HOOK_TIMEOUT_S };
351
+ const hooks = (settings.hooks ?? (settings.hooks = {})) as Record<string, unknown[]>;
352
+ hooks.SessionStart = [...(hooks.SessionStart ?? []), { matcher: "startup|resume", hooks: [check] }];
353
+ }
336
354
  return JSON.stringify(settings);
337
355
  }
338
356