@staix/agent-hub 0.48.3 → 0.49.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 (58) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +1 -1
  3. package/docs/agent-notes/daemon.md +2 -2
  4. package/docs/agent-notes/tasks.md +1 -1
  5. package/docs/design/adapters.md +4 -7
  6. package/docs/design/agent-hub-architecture.md +1 -1
  7. package/docs/design/agent-hub.md +1 -1
  8. package/docs/design/bus.md +2 -2
  9. package/docs/design/cli-output-inventory.md +39 -38
  10. package/docs/design/cli-output.md +7 -3
  11. package/docs/design/guidance-experiments.md +3 -1
  12. package/docs/design/guidance-probes.md +33 -31
  13. package/docs/design/model-routes.md +11 -14
  14. package/docs/design/roadmap.md +10 -9
  15. package/docs/design/supervision.md +6 -6
  16. package/docs/design/task-board.md +2 -2
  17. package/docs/dogfood.md +1 -1
  18. package/docs/operations.md +12 -7
  19. package/docs/quickstart.md +19 -1
  20. package/docs/roadmap.json +519 -1
  21. package/docs/roadmap.md +94 -0
  22. package/docs/security.md +3 -1
  23. package/docs/verification/2026-11-26-compat-pi-1.6.1.md +28 -0
  24. package/docs/verification/2026-11-27-0.48.4.md +37 -0
  25. package/docs/verification/2026-11-28-0.49.0.md +53 -0
  26. package/docs/verified.json +19 -19
  27. package/package.json +1 -1
  28. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  29. package/plugins/agent-hub/kimi-hook.js +29 -4
  30. package/plugins/agent-hub/server.js +34 -5
  31. package/src/adapters/channel-peer.ts +5 -2
  32. package/src/adapters/claude-channel.ts +1 -0
  33. package/src/adapters/compat.ts +4 -4
  34. package/src/adapters/definitions/native-cli-entry-claude.ts +22 -1
  35. package/src/cli/agents-output.ts +13 -0
  36. package/src/cli/agents.ts +16 -7
  37. package/src/cli/answer-output.ts +67 -0
  38. package/src/cli/broker.ts +9 -2
  39. package/src/cli/launch.ts +1 -1
  40. package/src/cli/main.ts +96 -127
  41. package/src/cli/recovery-package.ts +78 -26
  42. package/src/cli/reset-output.ts +50 -0
  43. package/src/cli/sdlc-output.ts +57 -0
  44. package/src/cli/settings-output.ts +80 -0
  45. package/src/hub/check-runner.ts +7 -3
  46. package/src/hub/claude-launch-proof.ts +12 -2
  47. package/src/hub/claude-state.ts +3 -0
  48. package/src/hub/control-client.ts +2 -0
  49. package/src/hub/daemon.ts +102 -40
  50. package/src/hub/memory-profile.ts +12 -1
  51. package/src/hub/roadmap-export.ts +12 -9
  52. package/src/hub/roadmap-issue-states.ts +35 -0
  53. package/src/hub/runtime-capture-prune.ts +21 -6
  54. package/src/hub/runtime-package-assets.ts +6 -0
  55. package/src/hub/supervision-proposals.ts +3 -3
  56. package/src/hub/supervision-rules.ts +2 -2
  57. package/src/hub/task-sweep.ts +1 -1
  58. package/src/hub/tasks.ts +37 -20
@@ -6,6 +6,7 @@ import { createRequire } from "node:module";
6
6
  import { hubHome, realPath } from "../hub/project.ts";
7
7
  import { Registry } from "../hub/registry.ts";
8
8
  import { AGENT_MEM_HOST_API_RANGE, agentMemHostApiOk, agentMemVersionInRange, isAgentMemFloorRange, readHostApiConstants } from "../hub/agent-mem-range.ts";
9
+ import { MEMORY_RUNTIME_LAYOUTS } from "../hub/runtime-package-assets.ts";
9
10
 
10
11
  export type CommandResult = { code: number; stdout: string; stderr: string };
11
12
  export type RunCommand = (args: string[], options?: { cwd?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number; input?: string; pipeExitGraceMs?: number }) => Promise<CommandResult>;
@@ -43,13 +44,57 @@ export function exactVersion(version: string): string {
43
44
  }
44
45
 
45
46
  const MEMORY_ASSETS = ["src", "bin", "package.json", "README.md", "LICENSE"] as const;
46
- const OUTPUT_ASSETS = ["src", "package.json", "README.md", "LICENSE"] as const;
47
+ function memoryRuntimeAssets(name: keyof typeof MEMORY_RUNTIME_LAYOUTS): readonly string[] {
48
+ const { directories, files } = MEMORY_RUNTIME_LAYOUTS[name];
49
+ return [...directories, ...files];
50
+ }
51
+ type RuntimePackage = { source: string; name: string; assets: readonly string[] };
52
+
53
+ function memoryPinError(name: string, pin: unknown, reason: string): Error {
54
+ const shown = (value: unknown) => JSON.stringify(typeof value === "string" ? value.slice(0, 256) : "<invalid pin>");
55
+ return new Error(`memory runtime dependency identity/version mismatch: ${shown(name)} pin ${shown(pin)}: ${reason}; upgrade to an agent-hub release that accepts it`);
56
+ }
57
+
58
+ function memoryPinnedRuntime(memory: string, name: string, pin: unknown, outputPin: unknown): RuntimePackage {
59
+ if (!Object.hasOwn(MEMORY_RUNTIME_LAYOUTS, name) || typeof pin !== "string" || !/^\d+\.\d+\.\d+$/.test(pin)
60
+ || name === "@staix/cli-output" && pin !== outputPin) throw memoryPinError(name, pin, "unsupported dependency or exact pin");
61
+ const scope = dirname(memory), modules = dirname(scope), source = join(scope, basename(name));
62
+ try {
63
+ if (basename(scope) !== "@staix" || basename(modules) !== "node_modules"
64
+ || [modules, scope, source].some(path => !lstatSync(path).isDirectory())) throw new Error("layout");
65
+ } catch {
66
+ const reason = name === "@staix/cli-output" ? "output runtime dependency is unavailable or is not a real sibling directory"
67
+ : "installed package must be a real sibling directory beside agent-mem";
68
+ throw memoryPinError(name, pin, reason);
69
+ }
70
+ let installed;
71
+ try {
72
+ const manifest = join(source, "package.json");
73
+ if (!lstatSync(manifest).isFile()) throw new Error("manifest");
74
+ installed = JSON.parse(readFileSync(manifest, "utf8"));
75
+ } catch { throw memoryPinError(name, pin, "installed package manifest is unavailable"); }
76
+ if (installed?.name !== name || installed.version !== pin
77
+ || [installed.dependencies, installed.optionalDependencies, installed.peerDependencies].some(dependencies =>
78
+ dependencies !== undefined && (!dependencies || typeof dependencies !== "object" || Array.isArray(dependencies) || Object.keys(dependencies).length)))
79
+ throw memoryPinError(name, pin, "installed package name, version or declared dependencies do not match the reviewed layout");
80
+ const inspect = (dir: string): void => {
81
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
82
+ if (entry.name === "node_modules" || entry.isSymbolicLink() || !entry.isDirectory() && !entry.isFile())
83
+ throw memoryPinError(name, pin, "installed package must not contain symlinks, special files or nested node_modules");
84
+ if (entry.isDirectory()) inspect(join(dir, entry.name));
85
+ }
86
+ };
87
+ inspect(source);
88
+ const assets = memoryRuntimeAssets(name as keyof typeof MEMORY_RUNTIME_LAYOUTS);
89
+ if (assets.some(asset => !existsSync(join(source, asset)))) throw memoryPinError(name, pin, "installed package lacks a reviewed runtime asset");
90
+ return { source, name, assets };
91
+ }
47
92
 
48
93
  /** Runtime dependencies are limited to the reviewed first-party packages, never an arbitrary dependency tree. */
49
- function memoryRuntime(root: string, dependencyRoot?: string): string | undefined {
94
+ function memoryRuntime(root: string, dependencyRoot?: string): RuntimePackage[] {
50
95
  const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
51
96
  const deps = pkg.dependencies ?? {};
52
- if (!Object.keys(deps).length) return undefined;
97
+ if (!Object.keys(deps).length) return [];
53
98
  const declared = deps["@staix/agent-mem"];
54
99
  // #1611: a current package declares a floor range `>=X.Y.Z <M.0.0`; a package staged under #1605 declares `~X.Y.Z` and one before it an exact
55
100
  // version, so a cached release still verifies (legacy forms need no host API); compound ranges, `^`, `*` and prereleases stay refused.
@@ -75,13 +120,13 @@ function memoryRuntime(root: string, dependencyRoot?: string): string | undefine
75
120
  if (!agentMemHostApiOk(host.min, host.version))
76
121
  throw new Error(`memory runtime host API ${host.min ?? "missing"}..${host.version ?? "missing"} does not intersect the supported ${AGENT_MEM_HOST_API_RANGE[0]}..${AGENT_MEM_HOST_API_RANGE[1]}`);
77
122
  }
78
- // #1664: agent-mem 0.37.0+ declares exactly the hub's own pinned @staix/cli-output (hashed once by outputRuntime); nothing else, and no nested node_modules the digest would not cover.
79
123
  const memoryDeps = Object.entries(memory.dependencies ?? {}), outputPin = deps["@staix/cli-output"];
80
- // A ranged hub pin is the output package's refusal to make, not a memory mismatch (outputRuntime says the same).
124
+ // The output package owns the refusal for a ranged hub pin.
81
125
  if (memoryDeps.length && typeof outputPin === "string" && !/^\d+\.\d+\.\d+$/.test(outputPin)) throw new Error("output runtime dependency must be an exact version");
82
- const depsOk = memoryDeps.length === 0 || (memoryDeps.length === 1 && typeof outputPin === "string" && memoryDeps[0]?.[0] === "@staix/cli-output" && memoryDeps[0][1] === outputPin);
83
- if (!accepted || !depsOk || (memoryDeps.length > 0 && existsSync(join(dir, "node_modules")))) throw new Error("memory runtime dependency identity/version mismatch");
84
- return realPath(dir);
126
+ if (!accepted || (memoryDeps.length > 0 && readdirSync(dir).includes("node_modules"))) throw new Error("memory runtime dependency identity/version mismatch");
127
+ const source = realPath(dir);
128
+ return [{ source, name: "@staix/agent-mem", assets: MEMORY_ASSETS },
129
+ ...memoryDeps.sort(([a], [b]) => a.localeCompare(b)).map(([name, pin]) => memoryPinnedRuntime(source, name, pin, outputPin))];
85
130
  }
86
131
  }
87
132
  const parent = dirname(dir);
@@ -117,15 +162,27 @@ function outputRuntime(root: string, dependencyRoot?: string): string | undefine
117
162
  }
118
163
  }
119
164
 
165
+ /** Preserve the historical digest order, hashing shared cli-output only once. */
166
+ function runtimeDependencies(root: string, dependencyRoot?: string): RuntimePackage[] {
167
+ const [memory, ...pinned] = memoryRuntime(root, dependencyRoot);
168
+ const output = outputRuntime(root, dependencyRoot);
169
+ const shared = pinned.find(pkg => pkg.name === "@staix/cli-output");
170
+ if (shared && shared.source !== output) {
171
+ const pin = JSON.parse(readFileSync(join(shared.source, "package.json"), "utf8")).version;
172
+ throw memoryPinError(shared.name, pin, "agent-mem and the hub must resolve the same cli-output package");
173
+ }
174
+ const packages = memory ? [memory] : [];
175
+ if (output) packages.push({ source: output, name: "@staix/cli-output", assets: memoryRuntimeAssets("@staix/cli-output") });
176
+ return packages.concat(pinned.filter(pkg => pkg.name !== "@staix/cli-output"));
177
+ }
178
+
120
179
  export function preserveRuntimeDependencies(root: string, destination: string): void {
121
- const memory = memoryRuntime(root), output = outputRuntime(root);
122
- for (const [source, packageName, assets] of [[memory, "agent-mem", MEMORY_ASSETS], [output, "cli-output", OUTPUT_ASSETS]] as const) {
123
- if (!source) continue;
124
- const target = join(destination, "node_modules/@staix", packageName);
180
+ for (const { source, name, assets } of runtimeDependencies(root)) {
181
+ const target = join(destination, "node_modules", name);
125
182
  mkdirSync(target, { recursive: true });
126
- for (const name of assets) {
127
- if (lstatSync(join(source, name)).isSymbolicLink()) throw new Error("runtime package must not contain symlinks");
128
- cpSync(join(source, name), join(target, name), { recursive: true, dereference: false });
183
+ for (const asset of assets) {
184
+ if (lstatSync(join(source, asset)).isSymbolicLink()) throw new Error("runtime package must not contain symlinks");
185
+ cpSync(join(source, asset), join(target, asset), { recursive: true, dereference: false });
129
186
  }
130
187
  }
131
188
  }
@@ -144,17 +201,12 @@ export function packageDigest(root: string, options: { ownDependencies?: boolean
144
201
  // Only runtime assets and the resolved first-party packages; never private state or unrelated dependencies.
145
202
  for (const name of ["src", "plugins", "templates", ".claude-plugin"]) visit(join(root, name), `${name}/`);
146
203
  hash.update(readFileSync(join(root, "package.json")));
147
- const memory = memoryRuntime(root, options.ownDependencies ? root : options.dependencyRoot);
148
- if (memory) for (const name of MEMORY_ASSETS) {
149
- const path = join(memory, name), stat = lstatSync(path), prefix = `node_modules/@staix/agent-mem/${name}`;
150
- if (stat.isSymbolicLink()) throw new Error("runtime package must not contain symlinks");
151
- if (stat.isDirectory()) visit(path, `${prefix}/`); else file(path, prefix);
152
- }
153
- const output = outputRuntime(root, options.ownDependencies ? root : options.dependencyRoot);
154
- if (output) for (const name of OUTPUT_ASSETS) {
155
- const path = join(output, name), stat = lstatSync(path), prefix = `node_modules/@staix/cli-output/${name}`;
156
- if (stat.isSymbolicLink()) throw new Error("runtime package must not contain symlinks");
157
- if (stat.isDirectory()) visit(path, `${prefix}/`); else file(path, prefix);
204
+ for (const { source, name, assets } of runtimeDependencies(root, options.ownDependencies ? root : options.dependencyRoot)) {
205
+ for (const asset of assets) {
206
+ const path = join(source, asset), stat = lstatSync(path), prefix = `node_modules/${name}/${asset}`;
207
+ if (stat.isSymbolicLink()) throw new Error("runtime package must not contain symlinks");
208
+ if (stat.isDirectory()) visit(path, `${prefix}/`); else file(path, prefix);
209
+ }
158
210
  }
159
211
  return hash.digest("hex");
160
212
  }
@@ -0,0 +1,50 @@
1
+ import { Report, terminalText, type Span } from "./console-state.ts";
2
+ import { resetLines, type ResetPlan } from "./reset.ts";
3
+
4
+ export const RESET_KEPT = "kept: the board, logs and audit, recovery records, execution budgets, configuration and pi-sessions/";
5
+ export const RESET_MEMORY = "claude-mem is not touched: notes saved with hub_remember stay in shared memory";
6
+
7
+ const exactLines = (lines: readonly string[]): Span[][] =>
8
+ lines.flatMap(line => line.split("\n").map(text => [{ text }]));
9
+
10
+ /** Paths and instructions keep their line breaks so the dry run can be read or copied verbatim. */
11
+ export function renderResetPlan(view: {
12
+ all: boolean; state: string; stateDir: string; archive: string; projectId: string;
13
+ plan?: ResetPlan; unread?: string; stale: readonly string[];
14
+ }, _columns?: number, _now = Date.now(), ascii = false): Span[][] {
15
+ const report = new Report(undefined, ascii)
16
+ .titled("ahub", `reset${view.all ? " --all" : ""}, dry run: the hub is ${view.state}${view.state === "stopped" ? "" : "; --yes stops it first, as ahub kill does"}`)
17
+ .section("What --yes does");
18
+ if (view.all) {
19
+ report.note(`move ${view.stateDir}${view.plan ? ` (${view.plan.entries} entries)` : ""} to ${view.archive}/state-<UTC time>/ (0700), then start an empty state directory holding only project.json; project ${view.projectId} keeps its id and registration`, "value");
20
+ report.note(view.unread ? `could not read the state (${view.unread}); it is archived as it is` : "archived as they are:", "value");
21
+ } else report.note('settle as discard with reason "reset", clear and drop:', "value");
22
+ if (view.plan) report.append(exactLines(resetLines(view.plan).map(line => ` ${line}`)));
23
+ if (view.stale.length) report.note(`remove the manifest a hub left when it did not stop cleanly: ${view.stale.join(", ")}`, "value");
24
+ report.note(view.all ? ".agenthub/config.json, config.local.json and routing.toml are outside the state directory and stay" : RESET_KEPT);
25
+ report.note(RESET_MEMORY);
26
+ return report.append(exactLines(["nothing was changed; add --yes to apply"])).lines();
27
+ }
28
+
29
+ export function renderUndoPlan(view: { id: string; restore: readonly string[]; unobserved: readonly string[]; undone: boolean },
30
+ _columns?: number, _now = Date.now(), ascii = false): Span[][] {
31
+ const { id, restore, unobserved, undone } = view;
32
+ const report = new Report(undefined, ascii).titled("ahub", "Undo", terminalText(id)).section("Changes");
33
+ if (undone && !unobserved.length) return report.note(`turn ${id} is already undone: its files are as they were before it started`, "value").lines();
34
+ if (undone) report.note(`turn ${id}: its files are as they were before it started`, "value");
35
+ else if (restore.length) report.note(`turn ${id} changed:`, "value").append(exactLines(restore.map(path => ` ${path}`)));
36
+ else report.note(`turn ${id} changed no files${unobserved.length ? " the hub can restore" : ""}`, "value");
37
+ if (unobserved.length) {
38
+ report.note("these submodules were changed during the turn and their contents cannot be restored (the hub does not observe inside a submodule); undo them in the submodule itself:");
39
+ report.append(exactLines(unobserved.map(path => ` ${path}`)));
40
+ }
41
+ if (!undone) report.note("(every change made in the project during the turn counts as its own, including any by Claude or by you)");
42
+ return report.lines();
43
+ }
44
+
45
+ /** Stream status and effect receipts in their original order. Continuations keep their exact line boundaries. */
46
+ export function renderLifecycleReceipt(view: { title?: string; lines: readonly string[] }, _columns?: number, _now = Date.now(), ascii = false): Span[][] {
47
+ const report = new Report(undefined, ascii);
48
+ if (view.title) report.titled("ahub", view.title).section("Result");
49
+ return report.append(exactLines(view.lines)).lines();
50
+ }
@@ -375,3 +375,60 @@ export function renderSdlcMerge(view: unknown, columns?: number, _now = Date.now
375
375
  }
376
376
  return report.lines();
377
377
  }
378
+
379
+ /** Short operator receipts use the same wrapping and terminal sanitation as the SDLC reports. */
380
+ export function renderSdlcReceipt(value: { title: string; lines: readonly string[] }, columns?: number, _now = Date.now(), ascii = false): Span[][] {
381
+ const out = new LayoutReport(columns, ascii).titled("ahub", value.title).section("Receipt");
382
+ for (const line of value.lines) out.note(line, "value");
383
+ return out.lines();
384
+ }
385
+
386
+ /** Authorization and privacy are already resolved by the host. Only render report fields on the reported path. */
387
+ export function renderSdlcReadback(value: { task: number; op: "start" | "show"; reply: Record<string, any> }, columns?: number, _now = Date.now(), ascii = false): Span[][] {
388
+ const { task, op, reply } = value;
389
+ const view = reply.readback;
390
+ const out = new LayoutReport(columns, ascii).titled("ahub", "Spec read-back", `task #${task}`).section("Read-back");
391
+ if (op === "start") {
392
+ if (reply.state !== "requested" && reply.state !== "reported") return out.note(`spec read-back unavailable: ${reply.reason ?? "no eligible reader"}`).lines();
393
+ return out.kv([["read-back", view], ["state", reply.state === "reported" ? "already reported" : "requested"],
394
+ ["issue", `${reply.repo}#${reply.issue}`], ...(reply.state === "requested" ? [["reader", reply.reader] as const] : [])]).lines();
395
+ }
396
+ if (!view || view.status === "none") return out.note(`no spec read-back; start one with ahub sdlc readback start ${task}`).lines();
397
+ if (view.status === "private") return out.note(`read-back ${view.readback} belongs to a private task; its report is not printed here`).lines();
398
+ if (view.status === "requested") return out.note(`read-back ${view.readback} requested from ${view.reader}; the reader has not reported yet`).lines();
399
+ out.kv([["read-back", view.readback], ["issue", `${view.repo}#${view.issue}`], ["reader", view.reader]]);
400
+ const report = view.report;
401
+ out.section("Report").kv(report.cannot_paraphrase ? [["cannot paraphrase", report.cannot_paraphrase]] : [["proposes", report.proposes], ["existing", report.existing]]);
402
+ for (const item of list(report.undefined)) out.note(`undefined: ${item.term} (${item.where})`);
403
+ for (const item of list(report.open_decisions)) out.note(`open decision: ${item.decision} (${item.where})`);
404
+ for (const path of list(report.refs)) out.note(`ref: ${path}`);
405
+ for (const path of list(view.missing_refs)) out.bullet("warn", `missing ref: ${path}`);
406
+ return out.lines();
407
+ }
408
+
409
+ /** The report adds readiness and metrics to the release returned by configure and cut. */
410
+ export function renderSdlcTrain(value: unknown, columns?: number, now = Date.now(), ascii = false): Span[][] {
411
+ const row = value as any;
412
+ const release = row?.release ?? row;
413
+ const out = new LayoutReport(columns, ascii).titled("ahub", "Release train", release?.name)
414
+ .section("Release").kv([["id", release?.id], ["state", release?.state], ["revision", release?.revision], ["goal", release?.goal]]);
415
+ if (release?.cut != null) out.kv([["planned cut", moment(release.cut, now)]]);
416
+ if (release?.frozenAt != null) out.kv([["frozen at", moment(release.frozenAt, now)]]);
417
+ if (release?.train?.scope?.length) out.kv([["frozen scope", release.train.scope.map((id: number) => `#${id}`).join(", ")]]);
418
+ if (release?.train?.hotfix) out.kv([["hotfix", release.train.hotfix.cause], ["reason", release.train.hotfix.reason]]);
419
+ if (row?.readiness) {
420
+ out.section("Readiness").kv([["trigger", row.readiness.trigger], ["native", row.native]]);
421
+ for (const task of list(row.readiness.tasks)) out.note(`task #${task.id}: ${task.state}`, "value");
422
+ for (const blocker of list(row.readiness.blockers)) out.bullet("warn", String(blocker));
423
+ }
424
+ if (row?.metrics) {
425
+ const metrics = row.metrics;
426
+ out.section("Metrics").kv([["hotfixes", metrics.hotfixCount ?? "unknown"],
427
+ ["hotfix rate", percent(metrics.hotfixRate)],
428
+ ["CI runs", metrics.ciRuns ?? "unknown"], ["reviews", metrics.reviews ?? "unknown"]]);
429
+ for (const entry of list(metrics.intervals)) out.note(`release #${entry.from} to #${entry.to}: ${span(entry.ms)}`);
430
+ for (const entry of list(metrics.approvalToReleaseMs)) out.note(`task #${entry.task} to release #${entry.release}: ${span(entry.ms)}`);
431
+ if (metrics.unknown?.length) out.bullet("warn", `unknown evidence for releases ${metrics.unknown.map((id: number) => `#${id}`).join(", ")}`);
432
+ }
433
+ return out.lines();
434
+ }
@@ -0,0 +1,80 @@
1
+ import { settingText, type SettingRow } from "../hub/settings.ts";
2
+ import { Report, terminalText, type Span } from "./console-state.ts";
3
+
4
+ function acceptedValues(row: SettingRow): string {
5
+ if (row.type === "boolean") return "true, false";
6
+ const range = `from ${row.min ?? 0} to ${row.max ?? "the configured bound"}`;
7
+ if (row.type === "number-or-off") return `off or a number ${range}`;
8
+ if (row.type === "integer" || row.type === "number") return `a number ${range}`;
9
+ if (row.type === "peers") return "a comma list of peer ids";
10
+ if (row.type === "roles") return "up to two comma-separated catalog ids";
11
+ return (row.values ?? []).join(", ");
12
+ }
13
+
14
+ export function renderSettingsRows(view: { rows: readonly SettingRow[]; detail?: boolean; pendingRestart?: readonly { key: string }[]; undo?: string }, columns?: number, _now = Date.now(), ascii = false): Span[][] {
15
+ const report = new Report(columns, ascii).titled("ahub", "Settings");
16
+ let group: string | undefined;
17
+ for (const row of view.rows) {
18
+ if (row.group !== group) report.section(group = row.group);
19
+ report.kv([[row.key, settingText(row.value)]]);
20
+ const applies = row.applies === "live" ? "applies at once" : row.applies === "next use" ? "applies at next use" : "pending restart";
21
+ const file = settingText(row.fileValue === undefined ? row.pending ?? row.value : row.fileValue);
22
+ report.note([`from ${row.source}`, `file: ${file}`, applies, row.restartReason, row.note].filter(Boolean).join("; "));
23
+ if (view.detail) {
24
+ const inherit = row.file === "this hub run" || row.key === "instructed.mode" ? "" : ", or inherit to remove the machine-local value";
25
+ report.note(`${row.label}; written to ${row.file}; takes ${acceptedValues(row)}${inherit}`);
26
+ if (row.risk === "raises") report.note("a dashboard needs a settings session (ahub ui --settings) to raise it");
27
+ }
28
+ }
29
+ if (!view.rows.length) report.section("Settings").note("no settings found");
30
+ if (view.pendingRestart?.length) report.section("Pending restart").note(view.pendingRestart.map(row => row.key).join(", "));
31
+ if (view.undo) report.section("Undo").note(`ahub settings undo puts back the last write (${view.undo})`);
32
+ return report.lines();
33
+ }
34
+
35
+ export function renderSdlcSetting(view: { key: string; value: unknown; fileValue: unknown; problem?: unknown }, columns?: number, _now = Date.now(), ascii = false): Span[][] {
36
+ const report = new Report(columns, ascii).titled("ahub", "Settings", terminalText(view.key))
37
+ .section("Values").kv([["running", JSON.stringify(view.value)], ["file", JSON.stringify(view.fileValue)]]);
38
+ if (view.problem) report.bullet("warn", "file unavailable");
39
+ return report.lines();
40
+ }
41
+
42
+ export function renderSettingsConfirmation(changes: readonly { key: string; before: string; after: string; effect?: string }[], columns?: number, _now = Date.now(), ascii = false): Span[][] {
43
+ const report = new Report(columns, ascii).titled("ahub", "Guarded settings");
44
+ for (const change of changes) {
45
+ // The key can be longer than the section width. Keep it in a wrapped value.
46
+ report.section("Change").kv([["setting", terminalText(change.key)], ["before", terminalText(change.before)], ["after", terminalText(change.after)]]);
47
+ if (change.effect !== undefined) report.note(terminalText(change.effect));
48
+ }
49
+ return report.lines();
50
+ }
51
+
52
+ export function renderSettingsPreview(view: { lines?: readonly string[]; tasks?: readonly { before: readonly string[]; after: readonly string[] }[]; hidden?: number }, columns?: number, _now = Date.now(), ascii = false): Span[][] {
53
+ const report = new Report(columns, ascii).titled("ahub", "Settings preview");
54
+ if (view.lines?.length) {
55
+ report.section("Changes");
56
+ for (const line of view.lines) report.note(line, "value");
57
+ }
58
+ // Route explain contributes a task title, a heading, then its trace.
59
+ for (const task of view.tasks ?? []) {
60
+ report.section("Routing").note(task.before[0] ?? "", "value").note("before:");
61
+ for (const line of task.before.slice(2)) report.note(line);
62
+ report.note("after:");
63
+ for (const line of task.after.slice(2)) report.note(line);
64
+ }
65
+ report.section("Result");
66
+ if (view.hidden) report.note(`${view.hidden} more open tasks are not shown`);
67
+ return report.note("preview only; nothing was changed").lines();
68
+ }
69
+
70
+ export function renderSettingsReceipt(view: { title: string; lines: readonly string[] }, columns?: number, _now = Date.now(), ascii = false): Span[][] {
71
+ const report = new Report(columns, ascii).titled("ahub", view.title).section("Result");
72
+ for (const line of view.lines) report.note(line, "value");
73
+ return report.lines();
74
+ }
75
+
76
+ export function renderSettingsRejected(rows: readonly { key: unknown; reason: unknown }[], columns?: number, _now = Date.now(), ascii = false): Span[][] {
77
+ const report = new Report(columns, ascii).titled("ahub", "Settings reload").section("Rejected");
78
+ for (const row of rows.slice(0, 100)) report.bullet("warn", terminalText(`${String(row.key).slice(0, 160)}: ${String(row.reason).slice(0, 1000)}`));
79
+ return report.lines();
80
+ }
@@ -552,14 +552,16 @@ export class ContainerRunner {
552
552
  await Promise.allSettled([...this.probes.values()]);
553
553
  while (this.entries.size) await new Promise(r => setTimeout(r, 5));
554
554
  }
555
- async sweep(): Promise<string[]> {
555
+ async sweep(signal?: AbortSignal): Promise<string[]> {
556
556
  const unknown: string[] = [];
557
+ if (this.closing || signal?.aborted) return unknown;
557
558
  if (!this.enabled()) { await this.maintain(); return unknown; }
558
559
  try {
559
560
  let containers: unknown;
560
- try { const list = await this.command(this.transport?.listArgs ?? ["list", "--all", "--format", "json"]); if (list.code !== 0) return unknown; containers = this.transport?.list(list.stdout) ?? JSON.parse(list.stdout); } catch { return unknown; }
561
+ try { const list = await this.command(this.transport?.listArgs ?? ["list", "--all", "--format", "json"], { signal }); if (list.code !== 0) return unknown; containers = this.transport?.list(list.stdout) ?? JSON.parse(list.stdout); } catch { return unknown; }
561
562
  if (!Array.isArray(containers)) return unknown;
562
563
  for (const container of containers) {
564
+ if (this.closing || signal?.aborted) break;
563
565
  const c = container as { id?: string; configuration?: { id?: string; labels?: Record<string, string> }; labels?: Record<string, string> };
564
566
  const labels = c.configuration?.labels ?? c.labels;
565
567
  if (labels?.["agenthub.project"] !== this.options.projectKey) continue;
@@ -578,12 +580,14 @@ export class ContainerRunner {
578
580
  const liveness = (this.options.liveness ?? processLiveness)(r.hub_pid, r.hub_signature);
579
581
  if (liveness === "live") continue;
580
582
  if (liveness !== "gone") { unknown.push(`orphan check ${name}: unknown owner`); continue; }
583
+ if (this.closing || signal?.aborted) break;
584
+ // Once cleanup starts, finish its receipt update before shutdown returns.
581
585
  if (!await this.cleanup(name)) { unknown.push(`orphan check ${name}: cleanup unconfirmed`); continue; }
582
586
  r.interrupted = true; if (r.status !== "stale") r.status = "finished"; r.exit = null; r.tail = "";
583
587
  await rm(join(this.root, run, "src"), { recursive: true, force: true }); await this.save(r);
584
588
  }
585
589
  return unknown;
586
- } finally { await this.maintain(); }
590
+ } finally { if (!this.closing && !signal?.aborted) await this.maintain(); }
587
591
  }
588
592
  private async maintain(): Promise<void> {
589
593
  try { await this.retain(); this.maintenanceFailed = false; }
@@ -1,6 +1,7 @@
1
1
  import { closeSync, fstatSync, openSync, readSync, constants } from "node:fs";
2
2
  import { isAbsolute, join } from "node:path";
3
- import { claudeStateFile } from "./claude-state.ts";
3
+ import { processLiveness } from "../pi/process-signature.ts";
4
+ import { claudeStateFile, isClaudeSessionUuid } from "./claude-state.ts";
4
5
  import { readFileSync } from "node:fs";
5
6
  import { isWsPeer, type WsPeer } from "../adapters/channel-peer.ts";
6
7
  import { isFixedBuiltinDefinition, type AdapterDefinition } from "../adapters/registry.ts";
@@ -8,6 +9,7 @@ import type { PeerAdapter } from "./peers.ts";
8
9
 
9
10
  export interface ClaudeLaunchRecordProof {
10
11
  launchId: string;
12
+ nativeSessionId?: string;
11
13
  launcherPid?: number;
12
14
  launcherSignature?: string;
13
15
  executionCwd?: string;
@@ -17,7 +19,7 @@ export interface ClaudeLaunchRecordProof {
17
19
  hookPurpose?: string;
18
20
  }
19
21
 
20
- /** One bounded reader for current managed launch metadata; no native identity or payload escapes. */
22
+ /** One bounded reader for current managed launch metadata, including an optional validated session UUID. */
21
23
  export function readClaudeLaunchProof(stateDir: string, peer: string, instanceId: string): ClaudeLaunchRecordProof | undefined {
22
24
  let fd: number | undefined;
23
25
  try {
@@ -31,6 +33,7 @@ export function readClaudeLaunchProof(stateDir: string, peer: string, instanceId
31
33
  const row = JSON.parse(bytes.subarray(0, count).toString("utf8"));
32
34
  if (row?.instanceId !== instanceId || typeof row.launchId !== "string" || !row.launchId || row.launchId.length > 128) return;
33
35
  return { launchId: row.launchId,
36
+ ...(isClaudeSessionUuid(row.nativeSessionId) ? { nativeSessionId: row.nativeSessionId } : {}),
34
37
  ...(Number.isSafeInteger(row.launcherPid) && row.launcherPid > 0 ? { launcherPid: row.launcherPid } : {}),
35
38
  ...(typeof row.launcherSignature === "string" && row.launcherSignature.length > 0 && row.launcherSignature.length <= 256 && !/[\p{Cc}\p{Cf}]/u.test(row.launcherSignature) ? { launcherSignature: row.launcherSignature } : {}), privateRecord: stat.nlink === 1 && (stat.mode & 0o777) === 0o600 && !!process.getuid && stat.uid === process.getuid(),
36
39
  ...(typeof row.executionCwd === "string" && row.executionCwd.length <= 4096 && isAbsolute(row.executionCwd) ? { executionCwd: row.executionCwd } : {}),
@@ -44,6 +47,7 @@ export function readClaudeLaunchProof(stateDir: string, peer: string, instanceId
44
47
  export interface ClaudeLaunchProof {
45
48
  permissionLaunch(peer: string): { launchId: string; unattended: boolean; hookPurpose?: string } | undefined;
46
49
  helloLaunch(peer: string, launchId: unknown): "admit" | "refuse";
50
+ attestedSession(peer: string, launchId: string | undefined, reported: string | undefined): string | undefined;
47
51
  expectedLaunch(peer: string): string | undefined;
48
52
  owner(peer: string): WsPeer | undefined;
49
53
  bindGeneration(peer: string, generation: string): void;
@@ -96,6 +100,12 @@ export function createClaudeLaunchProof(opts: {
96
100
  }
97
101
  return {
98
102
  permissionLaunch, helloLaunch, expectedLaunch, owner,
103
+ attestedSession(peer, launchId, reported) {
104
+ if (!channel(peer) || !launchId || !isClaudeSessionUuid(reported)) return;
105
+ const launch = readClaudeLaunchProof(opts.stateDir, peer, opts.instanceId);
106
+ if (launch?.privateRecord && launch.launchId === launchId && launch.nativeSessionId === reported
107
+ && launch.launcherPid && launch.launcherSignature && processLiveness(launch.launcherPid, launch.launcherSignature) === "live") return reported;
108
+ },
99
109
  bindGeneration(peer, generation) { if (owner(peer)) generations.set(peer, generation); },
100
110
  verified(peer) { const current = owner(peer); return !!current && generations.get(peer) === current.sessionGeneration; },
101
111
  };
@@ -1,2 +1,5 @@
1
+ export const isClaudeSessionUuid = (value: unknown): value is string => typeof value === "string"
2
+ && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
3
+
1
4
  // Stable leaf import for released statusline/CLI callers. Native policy belongs to the adapter.
2
5
  export { claudePeer, claudeStateFile, ownTerminalRow, transcriptPersisted, pathEvidence } from "../adapters/definitions/native-channel-state.ts";
@@ -64,6 +64,8 @@ export interface Hello {
64
64
  channelEvidence?: "development-channel-launch" | "inherited-marker" | "launch-unverified" | "unknown" | "unreported";
65
65
  /** Managed Claude launch identity; absent for plain or pre-daemon sessions. */
66
66
  launchId?: string;
67
+ /** Claude Code marker; the daemon compares it against host-owned launch evidence. */
68
+ claudeSessionId?: string;
67
69
  /** Optional canonical native execution cwd; ownership requires independent host proof. */
68
70
  cwd?: string;
69
71
  /**