@staix/agent-hub 0.50.0 → 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 (96) hide show
  1. package/CHANGELOG.md +16 -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/cli-output-inventory.md +22 -17
  11. package/docs/design/roadmap.md +1 -1
  12. package/docs/design/task-board.md +34 -0
  13. package/docs/dogfood.md +7 -3
  14. package/docs/operations.md +49 -3
  15. package/docs/quickstart.md +18 -1
  16. package/docs/roadmap.json +20 -20
  17. package/docs/roadmap.md +2 -2
  18. package/docs/sdlc.md +3 -2
  19. package/docs/specs/2026-09-19-agent-hub-design.md +1 -0
  20. package/docs/verification/2026-11-29-agy-1.5.20.md +33 -0
  21. package/docs/verification/2026-11-29-claude-profile-hook.md +12 -0
  22. package/docs/verification/2026-11-29-idle-daemon-footprint.md +75 -0
  23. package/docs/verification/2026-11-29-kimi-281-reviewer-compat.md +38 -0
  24. package/docs/verification/2026-11-29-kimi-tui-281.md +12 -0
  25. package/docs/verification/2026-11-30-0.51.0.md +91 -0
  26. package/docs/verification/2026-11-30-account-switch-1806.md +445 -0
  27. package/docs/verified.json +31 -27
  28. package/package.json +1 -1
  29. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  30. package/plugins/agent-hub/kimi-hook.js +1329 -24654
  31. package/plugins/agent-hub/server.js +612 -413
  32. package/scripts/check-docs.mjs +1 -1
  33. package/src/adapters/acp.ts +13 -13
  34. package/src/adapters/agy/definition.ts +2 -2
  35. package/src/adapters/agy/entry.ts +2 -0
  36. package/src/adapters/claude-channel-evidence.ts +7 -3
  37. package/src/adapters/compat.ts +4 -3
  38. package/src/adapters/definitions/builtin-metadata.ts +2 -2
  39. package/src/adapters/definitions/native-cli-claude-launch.ts +3 -1
  40. package/src/adapters/definitions/native-cli-entry-claude.ts +17 -2
  41. package/src/adapters/definitions/native-cli-entry-codex.ts +2 -0
  42. package/src/adapters/definitions/native-cli-entry-jcode.ts +2 -0
  43. package/src/adapters/definitions/native-cli-entry-kimi.ts +2 -0
  44. package/src/adapters/definitions/native-cli-entry-pi.ts +2 -0
  45. package/src/adapters/definitions/native-cli-entry-qwen.ts +2 -0
  46. package/src/adapters/definitions/native-cli-entry-types.ts +3 -1
  47. package/src/adapters/definitions/native-cli-jcode-home-init.ts +1 -1
  48. package/src/adapters/definitions/native-cli-preview-common.ts +1 -1
  49. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  50. package/src/adapters/jcode.ts +16 -0
  51. package/src/adapters/native-facts-hooks.ts +12 -0
  52. package/src/cli/autonomy-offline.ts +1 -1
  53. package/src/cli/bench.ts +1 -1
  54. package/src/cli/claude-profile-hook.ts +31 -11
  55. package/src/cli/commands/releases.ts +82 -0
  56. package/src/cli/conductor-recovery.ts +1 -1
  57. package/src/cli/facts-hook.ts +11 -4
  58. package/src/cli/help.ts +8 -6
  59. package/src/cli/identity.ts +5 -1
  60. package/src/cli/init-prompt.ts +1 -1
  61. package/src/cli/init-settings.ts +4 -35
  62. package/src/cli/init.ts +1 -1
  63. package/src/cli/json-text-spans.ts +57 -0
  64. package/src/cli/launch-check.ts +157 -0
  65. package/src/cli/launch.ts +19 -1
  66. package/src/cli/main.ts +44 -3
  67. package/src/cli/memory.ts +1 -1
  68. package/src/cli/output.ts +14 -1
  69. package/src/cli/preview.ts +1 -1
  70. package/src/cli/recovery-launch.ts +1 -1
  71. package/src/cli/setup-homes.ts +2 -2
  72. package/src/cli/start-agents-run.ts +85 -7
  73. package/src/cli/start-check.ts +28 -0
  74. package/src/cli/upgrade-runtime.ts +1 -1
  75. package/src/cli/warn-line.ts +1 -1
  76. package/src/hub/ci-watch.ts +311 -79
  77. package/src/hub/config-apply.ts +1 -1
  78. package/src/hub/config.ts +518 -0
  79. package/src/hub/control-client.ts +1 -1
  80. package/src/hub/daemon.ts +76 -513
  81. package/src/hub/delivery-public.ts +11 -0
  82. package/src/hub/hub-check.ts +125 -0
  83. package/src/hub/path-policy.ts +1 -1
  84. package/src/hub/permission-mode.ts +3 -40
  85. package/src/hub/permission-paths.ts +41 -0
  86. package/src/hub/recovery-policy.ts +1 -1
  87. package/src/hub/releases-inventory.ts +198 -0
  88. package/src/hub/runtime-capture-prune.ts +25 -3
  89. package/src/hub/runtime-prune-health.ts +8 -1
  90. package/src/hub/sdlc-release-authorization.ts +42 -21
  91. package/src/hub/sdlc-release-diagnostics.ts +5 -0
  92. package/src/hub/sdlc-release-policy.ts +21 -7
  93. package/src/hub/sdlc-release.ts +80 -20
  94. package/src/hub/sdlc.ts +7 -3
  95. package/src/hub/tasks.ts +138 -36
  96. package/src/ui/plugin.ts +1 -1
package/src/cli/main.ts CHANGED
@@ -73,7 +73,7 @@ import { randomUUID } from "node:crypto";
73
73
  import { homedir } from "node:os";
74
74
  import { basename, dirname, join, relative, resolve } from "node:path";
75
75
  import { retryLaunchConnect, ControlClient, readControl } from "../hub/control-client.ts";
76
- import { loadConfig } from "../hub/daemon.ts";
76
+ import { loadConfig } from "../hub/config.ts";
77
77
  import { factsHook } from "./facts-hook.ts";
78
78
  import { parseInstructionHook } from "./instruction-hook.ts";
79
79
  import { hubHome, projectContext, projectRoot, realPath } from "../hub/project.ts";
@@ -115,7 +115,8 @@ import { readRecoveryPresentationFlags } from "./upgrade-presentation-flags.ts";
115
115
  import { renderOperation, renderBlocked, renderSummary, type RecoveryPresentationOptions } from "./upgrade-presentation.ts";
116
116
  import { renderBudgetResult, renderRecoveryStatus, renderStoppedPlan, renderStoppedResults, renderUpgradePlan } from "./upgrade-output.ts";
117
117
  import { recordTerminalLaunch, prepareTerminalLaunch, registerTerminalLaunch, type TerminalPeer } from "./terminal-recovery.ts";
118
- import { effectiveStartAgents, inheritMachineStart, setupStartAgents, startProjectAgents } from "./start-agents-run.ts";
118
+ import { effectiveStartAgents, hubCheckRequester, inheritMachineStart, setupStartAgents, startProjectAgents, takeStartResults, waitForHubCheck } from "./start-agents-run.ts";
119
+ import { HUB_CHECK_UNAVAILABLE, renderHubCheck, renderHubCheckUnavailable } from "../hub/hub-check.ts";
119
120
  import { ensureMlx, inspectMlx, stopMlx } from "../models/mlx.ts";
120
121
  import { setupOllamaModel } from "./models-setup.ts";
121
122
 
@@ -423,6 +424,13 @@ const connect = async (timeoutMs = 3000) => {
423
424
  };
424
425
 
425
426
  const connectLaunch = () => retryLaunchConnect(connect, () => warn("hub busy: retrying"));
427
+ /** #1798 T3: one attempt with the caller's normal identity: no retry, no retry message, and never the delegated audit connection (it is neither taken nor closed). */
428
+ const connectOnce = (timeoutMs: number) => {
429
+ assertDelegatedAuditConsumer();
430
+ return ControlClient.connect(stateDir, identity.role === "tools" ? { role: "tools", peer: identity.peer, projectRoot: cwd,
431
+ ...(process.env.CLAUDECODE === "1" && process.env.CLAUDE_CODE_SESSION_ID ? { claudeSessionId: process.env.CLAUDE_CODE_SESSION_ID } : {}) }
432
+ : { role: "console", projectRoot: cwd, ...(delegatedAuditHub ? { instanceId: delegatedAuditHub.instanceId } : {}) }, timeoutMs);
433
+ };
426
434
 
427
435
  /** #1627 A: what init does for the hub-owned jcode home, read-only. */
428
436
  function initJcodeHome() {
@@ -592,6 +600,21 @@ function startupDiagnostic(error: unknown): string {
592
600
 
593
601
  /** A stderr warning that does not end the command (standard v1, Messages). */
594
602
  function warn(message: string, next?: string): void { warnLine(message, next); }
603
+ /** The hub check after `ahub up` asked for its agents: the per-agent outcomes of that start, a bounded wait, then the printed block (text mode only). */
604
+ async function upHubCheck(agents: readonly string[], waitS: number, json: boolean): Promise<unknown> {
605
+ const results = takeStartResults();
606
+ if (!results.length) return undefined;
607
+ const check = await waitForHubCheck(hubCheckRequester(connect), results, waitS);
608
+ if (!json) for (const line of check ? renderHubCheck(check, agents) : renderHubCheckUnavailable()) console.log(terminalText(line));
609
+ return check ?? null;
610
+ }
611
+ /** `ahub up --json`: exactly one JSON document, read once when no agent was started. */
612
+ async function upJsonDocument(check: unknown): Promise<void> {
613
+ let value = check;
614
+ if (value === undefined) value = await waitForHubCheck(hubCheckRequester(connect), [], 0);
615
+ if (args.includes("--json")) console.log(JSON.stringify({ hubCheck: value ?? HUB_CHECK_UNAVAILABLE }, null, 2));
616
+ }
617
+
595
618
  /**
596
619
  * CLI output standard v1, Messages: `ahub: <what failed>: <why>` on stderr; with a terminal on stderr it leads with the fail marker, and a piped line
597
620
  * keeps the plain `ahub: ` form so a script or agent matching it still works. `next` is a complete, copyable command printed on a second line (ASCII
@@ -1410,19 +1433,30 @@ const commands: Record<string, (receiptOutput?: SdlcReceiptOutput) => Promise<vo
1410
1433
  },
1411
1434
 
1412
1435
  up: async () => {
1436
+ // #1798: --wait is checked before the hub or any agent starts, so a bad value costs nothing (`upWait` is the one place it is read).
1437
+ const waitIndex = args.indexOf("--wait"), waitText = waitIndex >= 0 ? args[waitIndex + 1] : undefined;
1438
+ const upWaitS = waitIndex < 0 ? 15 : waitText === undefined || !/^\d+$/.test(waitText) ? NaN : Number(waitText);
1439
+ if (!(upWaitS <= 600)) return fail(`--wait needs a whole number of seconds from 0 to 600, got ${waitText === undefined || waitText === "" ? "nothing" : `"${terminalText(waitText)}"`}; nothing was started. Next: ahub up --wait 15`);
1413
1440
  const unattended = unattendedEnv || args.includes("--unattended");
1414
1441
  if (unattended) console.error(UNATTENDED_WARNING);
1415
1442
  const status = await startProject(registeredProject(), { unattended, liveTest, starting: pid => console.error(`ahub: hub is still starting, pid ${pid}; waiting for readiness, run ahub status in another terminal to inspect progress`), ...(recoveryLauncherCurrent ? { current: recoveryLauncherCurrent, env: { ...personEnv(process.env), AGENTHUB_RECOVERY_OPERATION: continuationId, AGENTHUB_PEER_ID: continuationPeer, AGENTHUB_RECOVERY_CONDUCTOR: continuationPeer, AGENTHUB_RECOVERY_CONTINUATION: continuationId } } : {}) });
1443
+ // #1798: under --json stdout holds exactly one JSON document, so the banner and the start lines go to stderr; their text is unchanged.
1444
+ const upJson = args.includes("--json") && !recoveryLauncherCurrent, stdoutLog = console.log;
1445
+ if (upJson) console.log = (...parts: unknown[]) => { process.stderr.write(`${parts.join(" ")}\n`); };
1416
1446
  console.log(`ahub up (ws://127.0.0.1:${status.controlPort}), state in ${stateDir}`);
1417
1447
  if (recoveryLauncherCurrent) { recoveryLauncherCurrent(); return; }
1418
1448
  // #608: the default agent set, only for a person's own `ahub up` (never an agent's, a live test's, or an upgrade or recovery relaunch, which set AGENTHUB_RECOVERY_OPERATION).
1449
+ let upAgents: readonly string[] | undefined;
1419
1450
  if (!args.includes("--no-agents") && !liveTest && caller.role === "console" && identity.role === "console" && !process.env.AGENTHUB_RECOVERY_OPERATION) {
1420
1451
  try {
1421
1452
  const chosen = effectiveStartAgents(cwd, loadConfig(cwd).start.agents, hubHome(), [cwd]);
1422
1453
  if (chosen.notice) warn(chosen.notice);
1423
1454
  for (const line of await startProjectAgents({ root: cwd, stateDir }, chosen.agents)) console.log(terminalText(line));
1455
+ upAgents = chosen.agents;
1424
1456
  } catch (error) { warn(`default agents were not started: ${terminalText((error as Error).message)}`); }
1425
1457
  }
1458
+ const upCheck = upAgents && await upHubCheck(upAgents, upWaitS, upJson);
1459
+ if (upJson) { console.log = stdoutLog; await upJsonDocument(upCheck); return; }
1426
1460
  if (process.stdin.isTTY && process.stdout.isTTY && !args.includes("--no-console")) await runConsole({ client: await connect(), cwd, stateDir, liveTest, installed: consoleInstalled() });
1427
1461
  },
1428
1462
 
@@ -1439,7 +1473,7 @@ const commands: Record<string, (receiptOutput?: SdlcReceiptOutput) => Promise<vo
1439
1473
  }
1440
1474
  const context: NativeCliEntryContext = { args, cwd, stateDir, cliDir: import.meta.dir, unattendedEnv, person: caller.role === "console", definition: entry.definition,
1441
1475
  ...(selectedInstance ? { instance: selectedInstance } : {}), ...(nativeSelection.hubStarted ? { hubStarted: true as const } : {}),
1442
- projectConfig, connect: nativeConnect, fail,
1476
+ projectConfig, connect: nativeConnect, connectOnce, fail,
1443
1477
  exec: (bin, argv, tool) => exec(bin, argv, tool, context.executionCwd),
1444
1478
  execWithEnv: (bin, argv, env) => execWithEnv(bin, argv, env, selectedInstance ?? entry.command, context.executionCwd), takeFlags,
1445
1479
  helpers: { resolveExecutionCwd: peer => {
@@ -1906,6 +1940,13 @@ const commands: Record<string, (receiptOutput?: SdlcReceiptOutput) => Promise<vo
1906
1940
  finally { hub.close(); }
1907
1941
  },
1908
1942
 
1943
+ releases: async () => {
1944
+ const { runReleasesCommand } = await import("./commands/releases.ts");
1945
+ const outcome = await runReleasesCommand(args, hubHome());
1946
+ if (outcome.error) fail("usage: ahub releases list [--json] | ahub releases prune [--kind <capture|coordinator-source|registry-install>] [--older-than <days>] [--apply] [--json]");
1947
+ if (outcome.code) process.exit(outcome.code);
1948
+ },
1949
+
1909
1950
  broker: async () => {
1910
1951
  const { runBrokerCommand, brokerCommandError } = await import("./broker.ts");
1911
1952
  try { await runBrokerCommand(args, stateDir); }
package/src/cli/memory.ts CHANGED
@@ -24,7 +24,7 @@ import { memoryUsage, goalUsage, rawMemoryCommand, rawGoalCommand } from "@staix
24
24
  const AHUB_NAMES = { memory: "ahub memory", goal: "ahub goal" };
25
25
  import { mentionsPrivatePath, promotionScreen, withoutPii } from "../hub/memory-policy.ts";
26
26
  import { currentRouting, detectSignals } from "../hub/routing.ts";
27
- import { loadConfig } from "../hub/daemon.ts";
27
+ import { loadConfig } from "../hub/config.ts";
28
28
  import { bindProfileMemory, memoryProjectFor, memoryProjectForStore, openProfileMemory, MemoryProfileBinding, MEMORY_PROFILE_UNAVAILABLE, MEMORY_SPLIT_INCOMPLETE, type MemoryProfileReceipt, type ProfileMemoryOptions } from "../hub/memory-profile.ts";
29
29
  import { createMemorySyncPolicy, inspectDeclinedMemoryRows, projectMemorySyncText } from "../hub/memory-sync-policy.ts";
30
30
 
package/src/cli/output.ts CHANGED
@@ -20,6 +20,8 @@ import { queueResolveChoices, queueResolveCommand } from "../hub/person-command.
20
20
 
21
21
  export interface DoctorCheck { section: "Tools" | "Hub" | "Config" | "Models" | "Memory"; level: "ok" | "warn" | "fail" | "unknown"; name: string; detail: string }
22
22
  export interface StatusOutput {
23
+ /** #1798: the daemon's one hub check; every surface renders it and none recomputes it. */
24
+ hubCheck?: import("../hub/hub-check.ts").HubCheck;
23
25
  runtimeModels?: RuntimeModelStatus[];
24
26
  runtimeModelsUnavailable?: boolean;
25
27
  roomsUnavailable?: unknown;
@@ -392,6 +394,7 @@ export function renderStatus(data: StatusOutput, columns?: number, now = Date.no
392
394
  if (p.ownerIsolationNote) out.push(...detail("owner isolation", p.ownerIsolationNote, columns, "attention"));
393
395
  if (p.permissionNote) out.push(...detail("permission", p.permissionNote, columns, "muted"));
394
396
  if (typeof p.statusNotice?.message === "string" && p.statusNotice.message) out.push(...detail("status notice", p.statusNotice.message, columns, "attention"));
397
+ if (p.refusedHello && typeof p.refusedHello.at === "number") out.push(...detail("refused hello", `${refusedHelloText(p.refusedHello)}; the owned launch is serving, so ${id} is not detached`, columns, "attention")); // #1795
395
398
  if (typeof p.detached?.cause === "string" && p.detached.cause) out.push(...detail("detached", `${p.detached.cause}${typeof p.detached.command === "string" && p.detached.command ? `; relaunch it with ${p.detached.command}` : ""}`, columns, "attention"));
396
399
  if (p.requestedModel && p.servedBy && p.requestedModel !== p.servedBy) out.push(...detail("requested model", p.requestedModel, columns));
397
400
  if (p.reviewScope === "code" || p.reviewScope === "full") out.push(...detail("review scope", p.reviewScope === "code" ? "code only (cannot run tests or read CI; the merger gates on exact-head CI)" : "full", columns, "muted")); // #852
@@ -471,7 +474,13 @@ export function statusAttention(data: StatusOutput, now = Date.now()): Attention
471
474
  if (p.ownerIsolationNote) add("warn", `${id} owner isolation: ${p.ownerIsolationNote}`);
472
475
  if (typeof p.statusNotice?.message === "string" && p.statusNotice.message) add("warn", `${id}: ${p.statusNotice.message}`);
473
476
  // #1668: the hub refused a hub-tools hello because a server the hub did not start is serving that peer's socket; the hub already knows the launch that ends it.
474
- if (typeof p.detached?.cause === "string" && p.detached.cause) add("warn", `${id} is detached: ${p.detached.cause}`, typeof p.detached.command === "string" ? p.detached.command : undefined);
477
+ // #1795: a stray process, not a detached peer. #1798: a read-only next step, the process row when its pid is known.
478
+ if (p.refusedHello && typeof p.refusedHello.at === "number") add("warn", `${id}: ${refusedHelloText(p.refusedHello)}`, typeof p.refusedHello.pid === "number" && Number.isSafeInteger(p.refusedHello.pid) ? `ps -p ${p.refusedHello.pid} -o pid,command` : "ahub status");
479
+ const hubPeer = data.hubCheck?.peers?.find((row: { id: string }) => row.id === id);
480
+ const queuedText = hubPeer && Number(hubPeer.queued) > 0 ? `; ${hubPeer.queued} queued` : "";
481
+ if (typeof p.detached?.cause === "string" && p.detached.cause) add("warn", `${id} is detached: ${p.detached.cause}${queuedText}`, typeof p.detached.command === "string" ? p.detached.command : undefined);
482
+ // #1798: a link weaker than expected is Attention, with its evidence value, the queued count and the full next step (detached has its own item above).
483
+ else if (hubPeer && hubPeer.ok === false && hubPeer.observed !== "pending" && hubPeer.observed !== "detached") add("warn", `${id}: ${flat(String(hubPeer.observed))} link (evidence: ${flat(String(hubPeer.evidence))})${queuedText}`, typeof hubPeer.nextStep === "string" ? hubPeer.nextStep : undefined);
475
484
  if (typeof p.importantWaitingSince === "number" && p.importantWaitingNote) add("warn", `${id}: ${String(p.importantWaitingNote)}`, `ahub queue list --peer ${id}`);
476
485
  const actionPolicy = data.actionPolicyInfo?.[id];
477
486
  if (actionPolicy?.note && !actionPolicy.enforceable) add("warn", `${id} action policy: ${actionPolicy.note}`);
@@ -808,6 +817,10 @@ function fields(value: unknown, columns: number | undefined, now: number, prefix
808
817
  visit(value, prefix, prefix);
809
818
  return rows(["FIELD", "VALUE"], leaves, columns);
810
819
  }
820
+ /** #1795: what a refused hub-tools hello names. The pid and command are display text from the hello and one bounded process read. */
821
+ function refusedHelloText(hello: { at: number; pid?: number; command?: string }): string {
822
+ return `a process that is not this peer's owned launch was refused${typeof hello.pid === "number" ? ` (pid ${hello.pid}${hello.command ? `: ${flat(hello.command)}` : ""})` : ""}`;
823
+ }
811
824
  export function renderQueueShow(delivery: any, columns?: number, now = Date.now(), project?: string): Span[][] {
812
825
  // #1399: the resolve line runs as printed: id, revision, a suggested action, a prefilled reason and the project that hosts the hub.
813
826
  const messages: any[] = Array.isArray(delivery?.messages) ? delivery.messages : [];
@@ -1,5 +1,5 @@
1
1
  import { definitionOf, builtinPreviewOf } from "../adapters/registry.ts";
2
- import { loadConfig } from "../hub/daemon.ts";
2
+ import { loadConfig } from "../hub/config.ts";
3
3
  import { childEnv } from "../hub/child-process.ts";
4
4
  import { startModeOf } from "../hub/start-mode.ts";
5
5
  import { instanceLaunchArguments, buildLaunch, buildKimiLaunch, buildKimiTuiLaunch, nativeLaunchEnv, claudeObservationHooks } from "./launch.ts";
@@ -4,7 +4,7 @@ import { format } from "node:util";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { looksSecret } from "@staix/agent-mem";
7
- import { loadConfig } from "../hub/daemon.ts";
7
+ import { loadConfig } from "../hub/config.ts";
8
8
  import { loadRouting, detectSignals } from "../hub/routing.ts";
9
9
  import { mentionsPrivatePath } from "../hub/memory-policy.ts";
10
10
  import { sanitize } from "../hub/envelope.ts";
@@ -25,13 +25,13 @@ export async function setupClaudeHomes(ports: SetupHomesPorts): Promise<void> {
25
25
  const initial = [];
26
26
  for (const home of ports.homes) initial.push(await checkClaudeHome(home, ports.packageRoot, ports.env, ports.probe, undefined, true, ports.hook));
27
27
  for (const check of initial) {
28
- ports.print(`Claude home ${check.home.path}: plugin ${check.plugin.state}; hook ${check.hook.state}.`);
28
+ ports.print(`Claude home ${check.home.path}: plugin ${check.plugin.state}; hook ${check.hook.state}${check.hook.outdated ? " (outdated)" : ""}.`);
29
29
  for (const notice of ("notices" in check.plugin ? check.plugin.notices : undefined) ?? []) ports.print(`${check.home.path}: ${notice}.`);
30
30
  if (check.plugin.state === "unknown" || check.hook.state === "refused") throw new Error(`Claude setup cannot safely inspect ${check.home.path}; nothing was changed`);
31
31
  if (check.next?.blocked) throw marketplaceRemovalRefusal(check.home.path, check.next.why);
32
32
  }
33
33
  for (const check of initial) if (check.next) ports.print(`${check.home.path}: ${check.next.blocked ? "setup blocked" : check.next.argv.join(" ")} (${check.next.why})`);
34
- if (initial.every(check => !check.next && check.hook.state === "installed")) return;
34
+ if (initial.every(check => !check.next && check.hook.state === "installed" && !check.hook.outdated)) return;
35
35
  if (ports.hook?.instruction && initial.some(check => check.hook.state !== "installed")) ports.print("The Claude UserPromptSubmit and Stop hooks record and close hash-only pending instruction evidence; they grant no command authority.");
36
36
  if (!ports.yes && ports.interactive === false) throw new Error("not a terminal: nothing was changed; rerun with --yes to apply");
37
37
  if (!ports.yes && !["y", "yes"].includes((await ports.ask("Install the hub plugin and project-neutral hook in these Claude homes? [y/N] "))?.trim().toLowerCase() ?? "")) { ports.print("Claude setup was not changed."); return; }
@@ -5,6 +5,8 @@ import { readAutonomyDefaults, writeMachineStartAgents } from "../hub/autonomy-d
5
5
  import { configRefusal } from "../hub/config-trust.ts";
6
6
  import { START_AGENTS_DEFAULT, parseStartAgents } from "../hub/start-agents.ts";
7
7
  import { MAX_COMMAND_MS } from "./terminal-recovery.ts";
8
+ import { definitionOf } from "../adapters/registry.ts";
9
+ import { expectedHubLink, markStarted, type ExpectedLink, type HubCheck } from "../hub/hub-check.ts";
8
10
 
9
11
  /**
10
12
  * #608 (agent-hub#1040): the default agent set `ahub up` starts. Every start goes through the console `peer_start`, so it is
@@ -22,11 +24,21 @@ export function startLine(id: string, reply: Record<string, any>): string {
22
24
  return `${id}: not started: ${String(reply.error ?? "the hub refused")}`;
23
25
  }
24
26
 
25
- /** Asks for every listed peer at once and returns the lines in list order. A refusal or a failed request never stops the others. */
26
- export async function startDefaultAgents(client: StartRequester, agents: readonly string[]): Promise<string[]> {
27
- return Promise.all(agents.map(async id => {
28
- try { return startLine(id, await client.request({ t: "peer_start", peer: id }, MAX_COMMAND_MS + 5_000)); }
29
- catch (error) { return `${id}: not started: ${(error as Error).message}`; }
27
+ /** One agent's start outcome, kept as data so the hub check never parses a printed line. */
28
+ interface StartResult { id: string; line: string; started: boolean; expected?: ExpectedLink; /** The hub's own refusal text and manual command, when the start was refused. */ refusal?: { cause: string; nextStep?: string } }
29
+
30
+ /** Asks for every listed peer at once; each outcome keeps its `ok` and its refusal (#1798). `startLine` stays the one place a line is worded. */
31
+ async function startDefaultAgentResults(client: StartRequester, agents: readonly string[]): Promise<StartResult[]> {
32
+ return Promise.all(agents.map(async (id): Promise<StartResult> => {
33
+ try {
34
+ const reply = await client.request({ t: "peer_start", peer: id }, MAX_COMMAND_MS + 5_000);
35
+ // A successful TUI start (including an already-attached TUI) names its form in peer_start's reply.
36
+ // A headless start may omit mode. Only the TUI form can change a transport's expected link.
37
+ const form = reply.mode === "headless" || reply.mode === "tui" ? reply.mode : undefined;
38
+ const expected = expectedHubLink(definitionOf(id), form);
39
+ if (reply.ok === true) return { id, line: startLine(id, reply), started: true, expected };
40
+ return { id, line: startLine(id, reply), started: false, expected, refusal: { cause: String(reply.error ?? "the hub refused the start"), ...(typeof reply.command === "string" ? { nextStep: reply.command } : {}) } };
41
+ } catch (error) { return { id, line: `${id}: not started: ${(error as Error).message}`, started: false, refusal: { cause: `not started: ${(error as Error).message}` } }; }
30
42
  }));
31
43
  }
32
44
 
@@ -45,11 +57,24 @@ export function effectiveStartAgents(projectRoot: string, projectValue: readonly
45
57
 
46
58
  /** The dashboard manager's and `ahub up`'s common path: a console connection to the running hub, then the set. */
47
59
  export async function startProjectAgents(project: { root: string; stateDir: string }, agents: readonly string[], connect?: () => Promise<ControlClient>): Promise<string[]> {
60
+ const results = await startProjectAgentResults(project, agents, connect);
61
+ lastStartResults = results;
62
+ return results.map(result => result.line);
63
+ }
64
+
65
+ // ponytail: `ahub up` reads the per-agent outcomes of the start it just made through this one module slot, because its printing call is a baselined raw-output
66
+ // line that cannot change shape (#1654). One CLI process runs one `ahub up`; the upgrade is to return the results from the call and re-baseline that line.
67
+ let lastStartResults: StartResult[] = [];
68
+ /** The per-agent outcomes of the last `startProjectAgents` call in this process, once. */
69
+ export function takeStartResults(): StartResult[] { const taken = lastStartResults; lastStartResults = []; return taken; }
70
+
71
+ /** `startProjectAgents` with per-agent results: the same console connection and the same `peer_start` per agent. */
72
+ async function startProjectAgentResults(project: { root: string; stateDir: string }, agents: readonly string[], connect?: () => Promise<ControlClient>): Promise<StartResult[]> {
48
73
  if (!agents.length) return [];
49
74
  let client: ControlClient;
50
75
  try { client = await (connect ?? (() => ControlClient.connect(project.stateDir, { role: "console", projectRoot: project.root }, 5_000)))(); }
51
- catch (error) { return agents.map(id => `${id}: not started: the hub did not answer (${(error as Error).message})`); }
52
- try { return await startDefaultAgents(client, agents); }
76
+ catch (error) { return agents.map(id => ({ id, line: `${id}: not started: the hub did not answer (${(error as Error).message})`, started: false, refusal: { cause: `not started: the hub did not answer (${(error as Error).message})` } })); }
77
+ try { return await startDefaultAgentResults(client, agents); }
53
78
  finally { client.close(); }
54
79
  }
55
80
 
@@ -123,3 +148,56 @@ export function inheritMachineStart(projectRoot: string, home: string, roots: re
123
148
  catch (error) { try { unlinkSync(temporary); } catch { /* nothing was written */ } return [`start.agents not copied: ${(error as NodeJS.ErrnoException).code ?? "write failed"}`]; }
124
149
  return [`Inherited the machine's agent set for ahub up: ${show(machine.startAgents)}.`];
125
150
  }
151
+
152
+ /** Make connection and status share one attempt's time budget. */
153
+ export function hubCheckRequester(connect: (timeoutMs: number) => Promise<StartRequester & { close(): void }>, now: () => number = Date.now): StartRequester {
154
+ return {
155
+ async request(message, timeoutMs = HUB_CHECK_READ_MS) {
156
+ const deadline = now() + timeoutMs;
157
+ const hub = await connect(Math.min(timeoutMs, HUB_CHECK_CONNECT_MS));
158
+ try {
159
+ const left = deadline - now();
160
+ if (left <= 0) throw new Error("hub check connection timed out");
161
+ return await hub.request(message, left);
162
+ } finally { hub.close(); }
163
+ },
164
+ };
165
+ }
166
+
167
+ const HUB_CHECK_CONNECT_MS = 3_000;
168
+ const HUB_CHECK_READ_MS = 5_000;
169
+
170
+ /** Bound the first usable check separately from attachment polling. Retain the last good check through transient failures. */
171
+ export async function waitForHubCheck(client: StartRequester, results: readonly Pick<StartResult, "id" | "started" | "expected" | "refusal">[], waitS: number, now: () => number = Date.now, sleep: (ms: number) => Promise<void> = ms => new Promise(r => setTimeout(r, ms))): Promise<HubCheck | undefined> {
172
+ const start = now(), attachDeadline = start + Math.max(0, waitS) * 1000, readDeadline = start + HUB_CHECK_READ_MS;
173
+ const started = results.filter(result => result.started).map(result => result.id);
174
+ const refused = Object.fromEntries(results.filter(result => !result.started && result.refusal).map(result => [result.id, result.refusal!]));
175
+ let check: HubCheck | undefined;
176
+ for (;;) {
177
+ const deadline = check ? attachDeadline : readDeadline;
178
+ const timeout = Math.min(HUB_CHECK_READ_MS, deadline - now());
179
+ if (timeout <= 0) break;
180
+ let cancelTimeout: (() => void) | undefined;
181
+ try {
182
+ const reply = await Promise.race([
183
+ client.request({ t: "status" }, timeout),
184
+ new Promise<undefined>(resolve => {
185
+ const timer = setTimeout(resolve, timeout);
186
+ cancelTimeout = () => clearTimeout(timer);
187
+ }),
188
+ ]);
189
+ if (reply?.status?.hubCheck && now() <= deadline) check = reply.status.hubCheck;
190
+ } catch { /* retry within the applicable deadline */ }
191
+ finally { cancelTimeout?.(); }
192
+ if (check) {
193
+ const rows = check.peers;
194
+ if (started.every(id => rows.some(peer => peer.id === id && peer.observed !== "offline" && peer.observed !== "pending"))) break;
195
+ }
196
+ const left = (check ? attachDeadline : readDeadline) - now();
197
+ if (left <= 0) break;
198
+ await sleep(Math.min(500, left));
199
+ }
200
+ if (!check) return undefined;
201
+ const expected = Object.fromEntries(results.flatMap(result => result.expected ? [[result.id, result.expected]] : []));
202
+ return markStarted(check, started, refused, expected);
203
+ }
@@ -0,0 +1,28 @@
1
+ import { ControlClient } from "../hub/control-client.ts";
2
+ import { START_HOOK_TOTAL_MS, cleanLine, startHookNotice, startHookShows, type StartHookNotice, type StartHookReading } from "./launch-check.ts";
3
+
4
+ /**
5
+ * #1798 T3: Claude's SessionStart notice, run by `facts-hook.ts` when `AGENTHUB_HOOK_PURPOSE` is exactly `start-check`. It only reads the hub's check and
6
+ * returns the document to print: it sends no facts request, so it records no native session or turn and turns on no idle, facts or sweep behavior. It has no
7
+ * main block and does not import `facts-hook.ts`. Its total time is bounded by START_HOOK_TOTAL_MS, clearly below the 5 s timeout of its settings entry. A
8
+ * failure or a timeout is the warning payload itself (the caller's outer catch prints nothing), never an OK.
9
+ */
10
+ function startCheckPayload(notice: StartHookNotice): object {
11
+ // Each line is cleaned before it is joined, so a control code or a line break from the daemon cannot add a line or move the cursor.
12
+ return { systemMessage: cleanLine(notice.line), hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: notice.lines.map(cleanLine).join("\n") } };
13
+ }
14
+
15
+ /** The hook's stdout document for one SessionStart input, or undefined for a source that is not a start (clear, compact) or unreadable input. */
16
+ export async function startCheck(stdin: string, stateDir: string, peer: string, launchId: string | undefined, totalMs = START_HOOK_TOTAL_MS): Promise<object | undefined> {
17
+ let source: unknown;
18
+ try { source = (JSON.parse(stdin) as { source?: unknown }).source; } catch { return undefined; }
19
+ if (!startHookShows(source)) return undefined;
20
+ const read = async (timeoutMs: number): Promise<StartHookReading | undefined> => {
21
+ const hub = await ControlClient.connect(stateDir, { role: "tools", peer, ...(launchId ? { launchId } : {}) }, Math.min(timeoutMs, 1_500));
22
+ try {
23
+ const status = (await hub.request({ t: "status" }, timeoutMs)).status as { hubCheck?: StartHookReading["hubCheck"]; thisLaunch?: unknown } | undefined;
24
+ return { ...(status?.hubCheck ? { hubCheck: status.hubCheck } : {}), ...(typeof status?.thisLaunch === "boolean" ? { thisLaunch: status.thisLaunch } : {}) };
25
+ } finally { hub.close(); }
26
+ };
27
+ return startCheckPayload(await startHookNotice(peer, read, totalMs));
28
+ }
@@ -1,6 +1,6 @@
1
1
  import { prepareRecoveryLaunch, RecoveryLaunchError } from "./recovery-launch.ts";
2
2
  import { recoveryCommand } from "../hub/recovery-store.ts";
3
- import { loadConfig } from "../hub/daemon.ts";
3
+ import { loadConfig } from "../hub/config.ts";
4
4
  import { configuredCommands } from "../adapters/compat.ts";
5
5
  import { recoveryVersionGates, readRecoveryVersionPreflight } from "./recovery-version-preflight.ts";
6
6
  import { authorizeConductorOperation, conductorRecoveryBinding } from "./conductor-recovery.ts";
@@ -3,7 +3,7 @@ import { MARKERS, asciiMarkers } from "./output-standard.ts";
3
3
  // Deliberately imports only the light output-standard module: launch.ts, bench.ts and the other modules that warn reach this file early, and
4
4
  // console-state.ts (through error-format.ts) would close an import cycle through the adapter registry.
5
5
  /** Control characters out of a message or next step, so a daemon-supplied string cannot move the cursor. */
6
- const plain = (text: string) => text.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|$)/g, "").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, "");
6
+ export const plain = (text: string) => text.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|$)/g, "").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, "");
7
7
 
8
8
  /** The one warning format (standard v1, Messages): `ahub: warning: <what>: <why>`, a marker only on a terminal, and an optional `→ next` line. Pure; `error-format.ts` re-exports it. */
9
9
  export function warningLines(message: string, next: string | undefined, terminal: boolean, ascii: boolean): string[] {