@staix/agent-hub 0.38.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +17 -7
  3. package/docs/adding-an-ai-tool.md +6 -4
  4. package/docs/agent-notes/README.md +16 -0
  5. package/docs/agent-notes/adapters.md +4 -2
  6. package/docs/agent-notes/budget.md +8 -0
  7. package/docs/agent-notes/daemon.md +15 -8
  8. package/docs/agent-notes/local-worker.md +1 -1
  9. package/docs/agent-notes/security-review.md +55 -0
  10. package/docs/agent-notes/tasks.md +15 -4
  11. package/docs/agent-notes/tests.md +3 -2
  12. package/docs/design/adapters.md +51 -0
  13. package/docs/design/agent-hub-architecture.md +29 -1
  14. package/docs/design/task-board.md +151 -5
  15. package/docs/dogfood.md +20 -6
  16. package/docs/events.md +3 -3
  17. package/docs/memory.md +5 -5
  18. package/docs/operations.md +177 -28
  19. package/docs/profiles.md +100 -8
  20. package/docs/quickstart.md +32 -4
  21. package/docs/research.md +6 -3
  22. package/docs/roles.md +52 -0
  23. package/docs/sdlc.md +187 -1
  24. package/docs/security.md +50 -11
  25. package/docs/text-projection.md +1 -0
  26. package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
  27. package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
  28. package/docs/verification/2026-11-14-0.39.0.md +51 -0
  29. package/docs/verified.json +48 -25
  30. package/package.json +3 -3
  31. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  32. package/plugins/agent-hub/kimi-hook.js +1953 -460
  33. package/plugins/agent-hub/server.js +2019 -498
  34. package/src/adapters/acp-model-policy.ts +1 -1
  35. package/src/adapters/acp-session-model.ts +35 -0
  36. package/src/adapters/acp.ts +14 -0
  37. package/src/adapters/agy/definition.ts +1 -1
  38. package/src/adapters/agy/hooks.ts +7 -0
  39. package/src/adapters/claude-channel.ts +1 -1
  40. package/src/adapters/claude-implementer.ts +8 -0
  41. package/src/adapters/claude-print-child.ts +26 -2
  42. package/src/adapters/claude-print.ts +4 -0
  43. package/src/adapters/codex-appserver.ts +90 -16
  44. package/src/adapters/codex-review-isolation.ts +2 -0
  45. package/src/adapters/compat.ts +4 -4
  46. package/src/adapters/conformance/fakes/acp-server.ts +11 -2
  47. package/src/adapters/conformance/fakes/app-server.ts +5 -1
  48. package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
  49. package/src/adapters/definitions/builtin-metadata.ts +6 -6
  50. package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
  51. package/src/adapters/definitions/native-quota.ts +122 -0
  52. package/src/adapters/definitions/native-recovery.ts +3 -0
  53. package/src/adapters/definitions/qwen.ts +1 -1
  54. package/src/adapters/kimi-review.ts +23 -0
  55. package/src/adapters/kimi-wire-usage.ts +39 -16
  56. package/src/adapters/local-worker.ts +6 -3
  57. package/src/adapters/pi-state-model.ts +12 -0
  58. package/src/adapters/pi.ts +22 -0
  59. package/src/adapters/print-result-model.ts +24 -0
  60. package/src/adapters/registry-types.ts +10 -1
  61. package/src/adapters/registry.ts +19 -2
  62. package/src/adapters/reviewer-print.ts +130 -15
  63. package/src/adapters/role-eligibility.ts +99 -0
  64. package/src/adapters/same-directory.ts +16 -0
  65. package/src/cli/agy-mcp.ts +18 -7
  66. package/src/cli/console-state.ts +3 -1
  67. package/src/cli/free-text.ts +20 -0
  68. package/src/cli/handoff-args.ts +1 -1
  69. package/src/cli/help.ts +61 -6
  70. package/src/cli/identity.ts +10 -4
  71. package/src/cli/init-prompt.ts +31 -2
  72. package/src/cli/init-roles.ts +156 -0
  73. package/src/cli/init-settings.ts +24 -2
  74. package/src/cli/init.ts +139 -17
  75. package/src/cli/main.ts +194 -49
  76. package/src/cli/model.ts +1 -1
  77. package/src/cli/output.ts +56 -1
  78. package/src/cli/preview.ts +1 -1
  79. package/src/cli/recovery-launch.ts +114 -0
  80. package/src/cli/recovery-package.ts +14 -7
  81. package/src/cli/recovery-version-preflight.ts +104 -0
  82. package/src/cli/role-doctor.ts +39 -0
  83. package/src/cli/sdlc-output.ts +66 -1
  84. package/src/cli/study-output.ts +54 -0
  85. package/src/cli/study.ts +14 -1
  86. package/src/cli/terminal-recovery.ts +14 -0
  87. package/src/cli/upgrade-presentation.ts +4 -0
  88. package/src/cli/upgrade-restore-state.ts +12 -3
  89. package/src/cli/upgrade-runtime.ts +40 -2
  90. package/src/cli/upgrade.ts +8 -4
  91. package/src/hub/advisor-survey.ts +139 -0
  92. package/src/hub/audit-source.ts +66 -0
  93. package/src/hub/board.ts +479 -14
  94. package/src/hub/budget.ts +54 -4
  95. package/src/hub/conductor.ts +14 -8
  96. package/src/hub/config-apply.ts +2 -1
  97. package/src/hub/config-edit-host.ts +77 -5
  98. package/src/hub/considered-findings.ts +47 -0
  99. package/src/hub/control-client.ts +1 -1
  100. package/src/hub/daemon.ts +343 -58
  101. package/src/hub/deliverable-files.ts +17 -1
  102. package/src/hub/dogfood-profile.ts +3 -2
  103. package/src/hub/events.ts +23 -2
  104. package/src/hub/folder-trigger.ts +11 -4
  105. package/src/hub/hub-tools.ts +88 -16
  106. package/src/hub/kimi-usage.ts +34 -2
  107. package/src/hub/lifecycle-schema.ts +3 -3
  108. package/src/hub/memory-profile.ts +9 -1
  109. package/src/hub/memory-sync-state.ts +1 -0
  110. package/src/hub/model-overrides.ts +2 -1
  111. package/src/hub/no-writes.ts +2 -0
  112. package/src/hub/operational-authority.ts +6 -1
  113. package/src/hub/operational-view.ts +5 -1
  114. package/src/hub/peers.ts +2 -0
  115. package/src/hub/plan-conformance.ts +20 -2
  116. package/src/hub/quota-account.ts +34 -0
  117. package/src/hub/recovery-policy.ts +18 -4
  118. package/src/hub/research-evidence.ts +51 -3
  119. package/src/hub/research.ts +77 -13
  120. package/src/hub/restart.ts +14 -0
  121. package/src/hub/review-budget.ts +88 -0
  122. package/src/hub/review-findings.ts +93 -12
  123. package/src/hub/reviewer-pool-config.ts +6 -2
  124. package/src/hub/reviewer-pool.ts +39 -6
  125. package/src/hub/routing.ts +7 -3
  126. package/src/hub/sdlc-merge.ts +1 -1
  127. package/src/hub/sdlc-queue.ts +14 -4
  128. package/src/hub/sdlc-release.ts +1 -1
  129. package/src/hub/sdlc.ts +10 -6
  130. package/src/hub/security-audit.ts +178 -0
  131. package/src/hub/security-pass.ts +115 -0
  132. package/src/hub/settings.ts +11 -5
  133. package/src/hub/source-read.ts +80 -2
  134. package/src/hub/sources.ts +57 -9
  135. package/src/hub/startup-event-seeds.ts +5 -3
  136. package/src/hub/startup-timing.ts +1 -0
  137. package/src/hub/synthesis-readiness.ts +279 -0
  138. package/src/hub/tasks.ts +1083 -69
  139. package/src/hub/text-projection.ts +11 -1
  140. package/src/memory/capture.ts +2 -1
  141. package/src/ui/index.html +3 -0
  142. package/src/ui/office-model.ts +11 -3
  143. package/src/ui/office-space.ts +50 -30
  144. package/src/ui/plugin.ts +21 -11
@@ -0,0 +1,114 @@
1
+ import { constants, closeSync, fstatSync, linkSync, mkdtempSync, openSync, readSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { format } from "node:util";
4
+ import { randomUUID } from "node:crypto";
5
+ import { fileURLToPath } from "node:url";
6
+ import { looksSecret } from "@staix/agent-mem";
7
+ import { loadConfig } from "../hub/daemon.ts";
8
+ import { loadRouting, detectSignals } from "../hub/routing.ts";
9
+ import { mentionsPrivatePath } from "../hub/memory-policy.ts";
10
+ import { sanitize } from "../hub/envelope.ts";
11
+ import { terminalText } from "./console-state.ts";
12
+ import { shellQuote } from "./shell-quote.ts";
13
+
14
+ export class RecoveryLaunchError extends Error {
15
+ constructor(readonly peer: string, readonly failure: RecoveryLaunchFailure, resume: string) { super(`${peer}: restoration launch ${failure.code} (exit ${failure.exitCode}): ${failure.firstLine}; fix the cause, then ${resume}`); }
16
+ }
17
+
18
+ export interface RecoveryLaunchFailure {
19
+ code: "version_refused" | "launch_exit";
20
+ exitCode: number;
21
+ firstLine: string;
22
+ }
23
+ interface Capture { file: string; nonce: string; peer: string }
24
+ const CAPTURE_BYTES = 2048;
25
+ const OUTCOME_BYTES = 8192;
26
+ const LINE_POINTS = 512;
27
+
28
+ /** Existing private attempt directory only: never recreate it after the reader has disposed it. */
29
+ function publish(capture: Capture, exitCode: number, firstLine: string, complete: boolean): void {
30
+ if (!Number.isInteger(exitCode) || exitCode <= 0 || exitCode > 255) return;
31
+ const temp = `${capture.file}.${process.pid}.tmp`;
32
+ try {
33
+ writeFileSync(temp, JSON.stringify({ schemaVersion: 1, nonce: capture.nonce, peer: capture.peer, exitCode, firstLine, complete }), { flag: "wx", mode: 0o600 });
34
+ linkSync(temp, capture.file); // first complete producer wins, without replacing any existing inode
35
+ } catch { /* Capture is optional; a closed/ready attempt must not create new files. */ }
36
+ finally { try { unlinkSync(temp); } catch { /* absent or already disposed */ } }
37
+ }
38
+
39
+ /** Preloaded only in the hub CLI child, not its native child. TTY descriptors/properties stay unchanged. */
40
+ export function captureLaunchExit(capture: Capture): void {
41
+ let first = Buffer.alloc(0), complete = false;
42
+ const collect = (bytes: Buffer) => {
43
+ if (complete || first.length >= CAPTURE_BYTES) return;
44
+ const newline = bytes.indexOf(10), end = newline < 0 ? bytes.length : newline;
45
+ const remaining = CAPTURE_BYTES - first.length;
46
+ first = Buffer.concat([first, bytes.subarray(0, Math.min(end, remaining))]);
47
+ complete = newline >= 0 && end <= remaining;
48
+ };
49
+ // Bun's console writes directly to the descriptor, bypassing stderr.write.
50
+ const error = console.error.bind(console);
51
+ console.error = (...args: any[]) => { try { collect(Buffer.from(format(...args) + "\n")); } catch { /* original console behavior below */ } error(...args); };
52
+ const write = process.stderr.write.bind(process.stderr);
53
+ process.stderr.write = function(chunk: any, ...args: any[]) {
54
+ collect(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk instanceof Uint8Array ? chunk : String(chunk)));
55
+ return (write as (...parts: any[]) => boolean)(chunk, ...args);
56
+ } as typeof process.stderr.write;
57
+ process.once("exit", code => publish(capture, code, first.toString("utf8"), complete));
58
+ }
59
+
60
+ function screenedLine(raw: string, complete: boolean, cwd: string): string {
61
+ const withheld = "launch diagnostic unavailable or withheld by privacy policy; inspect the launch terminal";
62
+ if (!complete || raw.includes("�")) return withheld;
63
+ try {
64
+ const routing = loadRouting(cwd), config = loadConfig(cwd);
65
+ if (routing.signals.pii_screen !== "off" || looksSecret(raw)
66
+ || detectSignals({ title: raw, detail: "", refs: {} }, routing, cwd).includes("pii")
67
+ || mentionsPrivatePath(raw, [], config.pii?.paths ?? [], cwd)) return withheld;
68
+ return Array.from(sanitize(terminalText(raw)).replace(/[\p{Cc}\p{Cf}]/gu, " ").trim()).slice(0, LINE_POINTS).join("") || withheld;
69
+ } catch { return withheld; }
70
+ }
71
+
72
+ /** Bounded no-follow read; an outcome is diagnostic only, never proof of ownership or readiness. */
73
+ function readOutcome(capture: Capture, cwd: string): RecoveryLaunchFailure | undefined {
74
+ let fd: number | undefined;
75
+ try {
76
+ fd = openSync(capture.file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
77
+ const stat = fstatSync(fd);
78
+ if (!stat.isFile() || stat.size > OUTCOME_BYTES) return;
79
+ const bytes = Buffer.alloc(OUTCOME_BYTES + 1), count = readSync(fd, bytes);
80
+ if (count > OUTCOME_BYTES) return;
81
+ const row = JSON.parse(bytes.subarray(0, count).toString("utf8"));
82
+ if (row?.schemaVersion !== 1 || row.nonce !== capture.nonce || row.peer !== capture.peer
83
+ || !Number.isInteger(row.exitCode) || row.exitCode <= 0 || row.exitCode > 255
84
+ || typeof row.firstLine !== "string" || Buffer.byteLength(row.firstLine) > CAPTURE_BYTES || typeof row.complete !== "boolean"
85
+ || Object.keys(row).some(key => !["schemaVersion", "nonce", "peer", "exitCode", "firstLine", "complete"].includes(key))) return;
86
+ const firstLine = screenedLine(row.firstLine, row.complete, cwd);
87
+ const version = row.complete && /^(?:ahub: )?Version not verified: /.test(row.firstLine);
88
+ return { code: version ? "version_refused" : "launch_exit", exitCode: row.exitCode, firstLine };
89
+ } catch { return; }
90
+ finally { if (fd !== undefined) closeSync(fd); }
91
+ }
92
+
93
+ export function prepareRecoveryLaunch(stateDir: string, peer: string, argv: readonly string[], env: Record<string, string>, cwd: string) {
94
+ if (argv.length < 2) throw new Error("restoration launch argv is missing; inspect the operation before resuming");
95
+ const dir = mkdtempSync(join(stateDir, "restore-launch-"));
96
+ const capture: Capture = { file: join(dir, "outcome.json"), nonce: randomUUID(), peer };
97
+ const module = fileURLToPath(import.meta.url), preload = join(dir, "capture.ts");
98
+ try {
99
+ writeFileSync(preload, `import { captureLaunchExit } from ${JSON.stringify(module)}; captureLaunchExit(${JSON.stringify(capture)});\n`, { flag: "wx", mode: 0o600 });
100
+ const prefix = ["env", ...Object.entries(env).map(([key, value]) => `${key}=${value}`)];
101
+ const launch = [...prefix, argv[0]!, "--preload", preload, ...argv.slice(1)].map(shellQuote).join(" ");
102
+ const record = [...prefix, process.execPath, module, JSON.stringify(capture), "--exit-code"].map(shellQuote).join(" ");
103
+ // A shell status observation adds no long-lived proxy or pipe to the native TTY.
104
+ const invoke = `ahub_restore_launch_${capture.nonce.replaceAll("-", "")}`;
105
+ const command = `${invoke}() { "$@"; ahub_restore_exit=$?; if [ "$ahub_restore_exit" -ne 0 ]; then ${record} "$ahub_restore_exit"; fi; return "$ahub_restore_exit"; }; ${invoke} ${launch}`;
106
+ return { command, read: () => readOutcome(capture, cwd), dispose: () => rmSync(dir, { recursive: true, force: true }) };
107
+ } catch (error) { rmSync(dir, { recursive: true, force: true }); throw error; }
108
+ }
109
+
110
+ if (import.meta.main) {
111
+ const [raw, marker, status] = process.argv.slice(2);
112
+ if (!raw || marker !== "--exit-code" || !status || !/^[0-9]+$/.test(status)) throw new Error("invalid private restoration launch outcome");
113
+ publish(JSON.parse(raw) as Capture, Number(status), "", false);
114
+ }
@@ -7,23 +7,30 @@ import { hubHome, realPath } from "../hub/project.ts";
7
7
  import { Registry } from "../hub/registry.ts";
8
8
 
9
9
  export type CommandResult = { code: number; stdout: string; stderr: string };
10
- export type RunCommand = (args: string[], options?: { cwd?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number }) => Promise<CommandResult>;
10
+ export type RunCommand = (args: string[], options?: { cwd?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number; input?: string; pipeExitGraceMs?: number }) => Promise<CommandResult>;
11
11
  export const runCommand: RunCommand = (args, options = {}) => new Promise((resolve, reject) => {
12
- const child = spawn(args[0]!, args.slice(1), { cwd: options.cwd, env: options.env, stdio: ["ignore", "pipe", "pipe"] });
12
+ const child = spawn(args[0]!, args.slice(1), { cwd: options.cwd, env: options.env, stdio: [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"] });
13
+ if (options.input !== undefined) { child.stdin?.on("error", () => {}); child.stdin?.end(options.input); }
13
14
  let stdout = "", stderr = "", exceeded = false;
14
15
  const append = (old: string, value: unknown) => {
15
16
  const next = old + String(value);
16
17
  if (next.length > 2_000_000) { exceeded = true; child.kill("SIGTERM"); }
17
18
  return next.slice(-2_000_000);
18
19
  };
19
- child.stdout.on("data", (v) => { stdout = append(stdout, v); });
20
- child.stderr.on("data", (v) => { stderr = append(stderr, v); });
21
- let timedOut = false;
20
+ child.stdout!.on("data", (v) => { stdout = append(stdout, v); });
21
+ child.stderr!.on("data", (v) => { stderr = append(stderr, v); });
22
+ let timedOut = false, incomplete = false;
23
+ let exitGrace: ReturnType<typeof setTimeout> | undefined;
24
+ // ponytail: a probe descendant may retain a pipe after exit; close bounded readers without signaling an unproven descendant. Upgrade: owned process-group proof, as for native probes.
25
+ if (options.pipeExitGraceMs !== undefined) child.once("exit", () => {
26
+ exitGrace = setTimeout(() => { incomplete = true; child.stdout?.destroy(); child.stderr?.destroy(); }, options.pipeExitGraceMs);
27
+ });
22
28
  const timer = setTimeout(() => { timedOut = true; child.kill("SIGTERM"); }, options.timeoutMs ?? 60_000);
23
29
  const hardTimer = setTimeout(() => child.kill("SIGKILL"), (options.timeoutMs ?? 60_000) + 3000);
24
- child.on("error", (e) => { clearTimeout(timer); clearTimeout(hardTimer); reject(e); });
30
+ child.on("error", (e) => { clearTimeout(timer); clearTimeout(hardTimer); clearTimeout(exitGrace); reject(e); });
25
31
  child.on("close", (code) => {
26
- clearTimeout(timer); clearTimeout(hardTimer);
32
+ clearTimeout(timer); clearTimeout(hardTimer); clearTimeout(exitGrace);
33
+ if (incomplete) return reject(new Error("command output remained open after its process exited; inspect the executable before retrying"));
27
34
  if (timedOut || exceeded) reject(new Error(`command ${args[0]} ${timedOut ? "timed out" : "exceeded output limit"}; inspect state before retrying`));
28
35
  else resolve({ code: code ?? 1, stdout, stderr });
29
36
  });
@@ -0,0 +1,104 @@
1
+ import { isAbsolute, join } from "node:path";
2
+ import type { CompatId } from "../adapters/compat.ts";
3
+ import type { AdapterDefinition } from "../adapters/registry-types.ts";
4
+ import { childEnv } from "../hub/child-process.ts";
5
+ import { withoutOrcaEnv } from "../hub/orca-env.ts";
6
+ import type { RunCommand } from "./recovery-package.ts";
7
+ import type { PlannedProject } from "./upgrade.ts";
8
+
9
+ /** Host-selected native launch gates, never inferred from a peer's spelling or a reviewer policy. */
10
+ export interface RecoveryVersionGate { peer: string; compatId: CompatId; command?: readonly string[] }
11
+ export interface RecoveryVersionObservation {
12
+ peer: string;
13
+ compatId: CompatId;
14
+ state: "accepted" | "refused" | "unknown";
15
+ version?: string;
16
+ /** Fixed guidance only: never native output, executable paths or target exception text. */
17
+ message: string;
18
+ }
19
+ export interface RecoveryVersionPorts {
20
+ run: RunCommand;
21
+ /** The caller revalidates the verified target root/digest and its own authority across awaits. */
22
+ current(): boolean;
23
+ }
24
+ const MAX_GATES = 64;
25
+ const MAX_OUTPUT_BYTES = 64 * 1024;
26
+ const PROBE_TIMEOUT_MS = 10_000;
27
+ const PROBE_EXIT_GRACE_MS = 250;
28
+ const PEER = /^[a-z][a-z0-9_-]{0,63}$/;
29
+ const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
30
+
31
+ /** The caller supplies its startup-bound project resolver and current configured executable argv. */
32
+ export function recoveryVersionGates(
33
+ planned: PlannedProject,
34
+ definition: (peer: string) => AdapterDefinition | undefined,
35
+ commands: Partial<Record<CompatId, readonly string[]>> = {},
36
+ ): RecoveryVersionGate[] {
37
+ const gates: RecoveryVersionGate[] = [], seen = new Set<string>();
38
+ for (const peer of planned.source.peers) {
39
+ if (peer.state === "offline" || planned.reconnectOnly?.includes(peer.id) || seen.has(peer.id)) continue;
40
+ seen.add(peer.id);
41
+ const adapter = definition(peer.id), compatId = adapter?.session.restoreVersionGate;
42
+ if (!adapter || !compatId || adapter.session.recoveryRefusal?.(peer, "plan")) continue;
43
+ if (gates.length >= MAX_GATES) throw new Error("recovery version preflight has too many native gates");
44
+ gates.push({ peer: peer.id, compatId, ...(commands[compatId] ? { command: [...commands[compatId]!] } : {}) });
45
+ }
46
+ return gates;
47
+ }
48
+
49
+ const plain = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
50
+ const words = (value: unknown): value is string[] => Array.isArray(value) && value.length > 0 && value.length <= 32
51
+ && value.every(word => typeof word === "string" && word.length > 0 && word.length <= 4096 && !/[\p{Cc}\p{Cf}]/u.test(word));
52
+ const unknown = (gate: RecoveryVersionGate): RecoveryVersionObservation => ({ peer: gate.peer, compatId: gate.compatId, state: "unknown",
53
+ message: `${gate.peer}: target version acceptance is unknown; check its configured executable and the target's ahub agents policy before restoring it` });
54
+
55
+ /**
56
+ * Read an already verified target's own policy, probe only the selected executable, then assess with that target's current machine trust.
57
+ * No result is cached or grants startup authority. The caller must run this again before pre-commit effects, including cached staging.
58
+ * Every command crosses the injected port; synthetic tests never execute a native CLI or import an arbitrary target in this process.
59
+ */
60
+ export async function readRecoveryVersionPreflight(
61
+ targetRoot: string,
62
+ projectRoot: string,
63
+ gates: readonly RecoveryVersionGate[],
64
+ ports: RecoveryVersionPorts,
65
+ ): Promise<RecoveryVersionObservation[]> {
66
+ if (!isAbsolute(targetRoot) || !isAbsolute(projectRoot) || !Array.isArray(gates) || gates.length > MAX_GATES
67
+ || gates.some(gate => !PEER.test(gate.peer) || !/^[a-z][a-z0-9-]{0,63}$/.test(gate.compatId)
68
+ || gate.command !== undefined && !words(gate.command))) throw new Error("invalid recovery version preflight scope");
69
+ const module = JSON.stringify(join(targetRoot, "src/adapters/compat.ts"));
70
+ const env = withoutOrcaEnv(childEnv({ ...process.env, JCODE_NO_TELEMETRY: "1", JCODE_DISABLE_CLAUDE_MCP: "1", AGY_CLI_DISABLE_AUTO_UPDATE: "1" }));
71
+ const run = async (argv: string[], input?: string) => {
72
+ if (!ports.current()) throw new Error("recovery version preflight authority changed");
73
+ const result = await ports.run(argv, { cwd: projectRoot, env, timeoutMs: PROBE_TIMEOUT_MS, pipeExitGraceMs: PROBE_EXIT_GRACE_MS, ...(input === undefined ? {} : { input }) });
74
+ if (!ports.current()) throw new Error("recovery version preflight authority changed");
75
+ if (result.code !== 0 || typeof result.stdout !== "string" || Buffer.byteLength(result.stdout) > MAX_OUTPUT_BYTES) return undefined;
76
+ return result.stdout;
77
+ };
78
+ const results: RecoveryVersionObservation[] = [];
79
+ for (const gate of gates) {
80
+ let observation = unknown(gate);
81
+ try {
82
+ // This target import is allowed only after the caller verified the package's retained root and digest.
83
+ const policyText = await run([process.execPath, "-e", `// recovery-version-policy\nimport { COMPAT } from ${module}; const id = ${JSON.stringify(gate.compatId)}; const p = Object.hasOwn(COMPAT, id) ? COMPAT[id] : undefined; console.log(JSON.stringify(p ? { probe: p.probe } : null));`]);
84
+ const policy: unknown = policyText === undefined ? undefined : JSON.parse(policyText);
85
+ if (!plain(policy) || !words(policy.probe)) { results.push(observation); continue; }
86
+ const [executable, ...prefix] = gate.command ?? [policy.probe[0]!];
87
+ const native = await run([executable!, ...prefix, ...policy.probe.slice(1)]);
88
+ if (native === undefined) { results.push(observation); continue; }
89
+ const assessment = await run([process.execPath, "-e", `// recovery-version-assess\nimport { COMPAT, assessVersion, readTrust } from ${module}; const id = ${JSON.stringify(gate.compatId)}; const p = Object.hasOwn(COMPAT, id) ? COMPAT[id] : undefined; const observed = await Bun.stdin.text(); const v = p ? assessVersion(id, p.parse(observed), readTrust()) : undefined; console.log(JSON.stringify(v ? { ok: v.ok, state: v.state, version: v.version } : null));`], native);
90
+ const verdict: unknown = assessment === undefined ? undefined : JSON.parse(assessment);
91
+ if (plain(verdict) && typeof verdict.version === "string" && verdict.version.length <= 64 && SEMVER.test(verdict.version)) {
92
+ const version = verdict.version;
93
+ if (verdict.ok === true && ["verified", "trusted", "in-line"].includes(String(verdict.state))) observation = { ...observation, state: "accepted", version,
94
+ message: `${gate.peer}: target accepts installed version ${version}` };
95
+ else if (verdict.ok === false && verdict.state === "refused") observation = { ...observation, state: "refused", version,
96
+ message: `${gate.peer}: target refuses installed version ${version}; install a verified version, or accept this exact version on this machine with: ahub agents trust ${gate.compatId} ${version}` };
97
+ }
98
+ } catch { /* A failed policy/probe is unknown, never accepted or a leaked native exception. */ }
99
+ // A changed target or authority invalidates all earlier observations, not merely the final gate.
100
+ if (!ports.current()) return gates.map(unknown);
101
+ results.push(observation);
102
+ }
103
+ return ports.current() ? results : gates.map(unknown);
104
+ }
@@ -0,0 +1,39 @@
1
+ import { roleEligibility } from "../adapters/role-eligibility.ts";
2
+ import { conductorPeer } from "../hub/conductor.ts";
3
+ import type { StartMode } from "../hub/start-mode.ts";
4
+
5
+ /**
6
+ * #1408 R2: `ahub doctor`'s `roles` row. Pure: the caller passes what the loader settled (`roles`, after every ceiling), what the config declared before the ceilings, each peer's effective
7
+ * start mode and the roster. A warning, never a failure, like the other advisory rows: doctor's exit code stays what it was for a project that has not looked at this yet.
8
+ */
9
+ export interface RolesRowInput {
10
+ /** `roles` after the loader's ceilings (what the hub holds). */
11
+ roles: Readonly<Record<string, readonly string[]>>;
12
+ /** The raw `roles` block of the config layers merged, before any ceiling, or undefined when none is declared. */
13
+ declared?: Readonly<Record<string, readonly string[]>>;
14
+ startMode: (peer: string) => StartMode | undefined;
15
+ rostered: (peer: string) => boolean;
16
+ }
17
+ export interface RolesRow { ok: boolean | undefined; detail: string }
18
+
19
+ const holders = (roles: RolesRowInput["roles"], role: string, rostered: (peer: string) => boolean) => Object.keys(roles).filter(peer => roles[peer]!.includes(role) && rostered(peer)).sort();
20
+
21
+ export function rolesRow(input: RolesRowInput): RolesRow {
22
+ const conductor = conductorPeer(input.roles), planners = holders(input.roles, "planner", input.rostered), reviewers = holders(input.roles, "reviewer", input.rostered);
23
+ const warnings: string[] = [];
24
+ // A declared conductor that the loader dropped is the case the person most needs to hear about: nobody else holds the role.
25
+ let ignored: string | null = null;
26
+ try { ignored = input.declared ? conductorPeer(input.declared) : null; } catch { ignored = null; }
27
+ if (ignored && ignored !== conductor) {
28
+ const verdict = roleEligibility(ignored, "conductor", input.startMode(ignored));
29
+ warnings.push(`conductor ${ignored} is ignored${verdict.reason ? `: ${verdict.reason}` : ""}${verdict.fix ? `; ${verdict.fix}` : ""}`);
30
+ }
31
+ if (!planners.length) warnings.push("no rostered planner is eligible (the hub falls back to the first eligible rostered kind, or has none)");
32
+ if (!reviewers.length) warnings.push("no rostered reviewer can run: reviews go to the person");
33
+ else {
34
+ const unfit = reviewers.filter(peer => !roleEligibility(peer, "reviewer").eligible);
35
+ if (unfit.length) warnings.push(`${unfit.join(", ")} cannot receive hub_review`);
36
+ }
37
+ const text = `conductor ${conductor ?? "none (the person conducts from ahub console)"}; planner ${planners.join(", ") || "none"}; reviewer ${reviewers.join(", ") || "the person"}`;
38
+ return warnings.length ? { ok: undefined, detail: `${text}. ${warnings.join(". ")}` } : { ok: true, detail: text };
39
+ }
@@ -5,6 +5,44 @@
5
5
  import { duration, plural, relative, table, terminalText, wrap, type Span, type Tone } from "./console-state.ts";
6
6
 
7
7
  type Line = Span[];
8
+ /** Configuration remains restart-bound; the claim is caller provenance, not inferred release consent. */
9
+ export function renderSdlcConfiguration(value: unknown, columns?: number): Span[][] {
10
+ const row = value as any;
11
+ const out = heading(list(row?.restartPending).length ? "SDLC configuration saved; restart pending" : "SDLC configuration saved", columns);
12
+ out.push(...pair("actor", row?.by ?? "unknown", columns, 12));
13
+ out.push(...pair("instruction", "person's explicit instruction claimed for this session", columns, 12));
14
+ for (const line of list(row?.lines)) out.push(...para(String(line), columns));
15
+ if (row?.backup) out.push(...pair("backup", row.backup, columns, 12));
16
+ return out;
17
+ }
18
+ /** Survey fields already passed the host's task and security disclosure policy. */
19
+ export function renderSdlcSurvey(value: unknown, columns?: number): Span[][] {
20
+ const row = value as any;
21
+ if (!row) return [[s("no advisor survey", "muted")]];
22
+ const out: Span[][] = [...heading(`Advisor survey, task ${row.task ?? "unknown"}`, columns)];
23
+ for (const field of ["survey", "ref", "focus"]) if (row[field] !== undefined) out.push(...pair(field, row[field], columns, 12));
24
+ if (row.withheld || row.status === "private") return [...out, [s("report withheld by current privacy", "attention")]];
25
+ for (const item of list(row.items)) {
26
+ const finding = item.finding ?? item;
27
+ out.push(...pair("finding", finding.id, columns, 12));
28
+ if (finding.withheld || item.withheld) { out.push(...pair("details", "withheld", columns, 12)); continue; }
29
+ for (const field of ["evidence", "impact", "effort", "risk", "confidence", "fix_sketch"]) if (finding[field] !== undefined) out.push(...pair(field, finding[field], columns, 12));
30
+ if (item.decision) out.push(...pair("decision", item.decision.verdict, columns, 12));
31
+ else if (item.verdict) out.push(...pair("decision", item.verdict, columns, 12));
32
+ if (item.rejectedBefore?.rejectedBefore || item.rejectedBefore === true) out.push(...pair("history", "rejected before", columns, 12, "attention"));
33
+ for (const rejected of list(item.rejected)) {
34
+ out.push(...pair("rejected before", rejected.id, columns, 16));
35
+ if (rejected.change === "unknown") out.push(...pair("change", "unknown (suppression retained)", columns, 16, "attention"));
36
+ if (!rejected.withheld && rejected.reason) out.push(...pair("reason", rejected.reason, columns, 16));
37
+ }
38
+ }
39
+ for (const rejected of list(row.rejected)) {
40
+ out.push(...pair("rejected before", rejected.id, columns, 16));
41
+ if (rejected.status === "unknown" || rejected.change === "unknown") out.push(...pair("change", "unknown (suppression retained)", columns, 16, "attention"));
42
+ if (!rejected.withheld && rejected.reason) out.push(...pair("reason", rejected.reason, columns, 16));
43
+ }
44
+ return out;
45
+ }
8
46
  export const s = (value: unknown, tone?: Tone): Span => ({ text: terminalText(value).replace(/[\n\t]/g, " "), ...(tone ? { tone } : {}) });
9
47
  const room = (columns?: number) => columns ?? Infinity;
10
48
  const list = (value: unknown): any[] => Array.isArray(value) ? value : [];
@@ -104,7 +142,7 @@ function taskBlock(row: any, columns: number | undefined, detail: boolean): Line
104
142
  if (row.definition?.name || row.definition?.id) out.push(...pair("stage", row.definition.name ?? row.definition.id, columns, 11, undefined, " "));
105
143
  out.push(...bullets("entry", list(row.entry), columns, undefined, " "), ...bullets("exit", list(row.exit), columns, undefined, " "));
106
144
  const f = row.findings;
107
- if (f) out.push(...pair("findings", `${plural(f.important ?? 0, "important")} (${f.openImportant ?? 0} open), ${plural(f.nit ?? 0, "nit")} (${f.openNit ?? 0} open), ${f.fixed ?? 0} fixed, ${f.falsePositive ?? 0} false positive, ${f.accepted ?? 0} accepted`, columns, 11, f.openImportant ? "attention" : undefined, " "));
145
+ if (f) out.push(...pair("findings", `${plural(f.important ?? 0, "important")} (${f.openImportant ?? 0} open), ${plural(f.nit ?? 0, "nit")} (${f.openNit ?? 0} open), ${f.fixed ?? 0} fixed, ${f.falsePositive ?? 0} false positive, ${f.accepted ?? 0} accepted${f.needsValidation ? `, ${f.needsValidation} needs validation (not blocking)` : ""}${f.preExisting ? `, ${f.preExisting} pre-existing (not blocking)` : ""}`, columns, 11, f.openImportant ? "attention" : undefined, " "));
108
146
  const p = row.planConformance;
109
147
  if (p) {
110
148
  out.push(...pair("plan files", `${p.state}${p.accepted ? ", departure accepted" : ""}, ${list(p.outside).length} outside the plan, ${list(p.untouched).length} planned and untouched`, columns, 11, p.state === "departure" && !p.accepted ? "attention" : undefined, " "));
@@ -115,6 +153,13 @@ function taskBlock(row: any, columns: number | undefined, detail: boolean): Line
115
153
  out.push(...pair("tests", `${t.applicability === "bug" ? "bug fix" : t.applicability === "not_bug" ? "not a bug fix" : "bug status unknown"}, red-first ${String(t.redFirst).replace("_", " ")}, files ${t.fileState}`, columns, 11, undefined, " "));
116
154
  out.push(...bullets("modified tests", list(t.modifiedTests), columns, undefined, " "), ...bullets("test blockers", list(t.blockers), columns, "attention", " "));
117
155
  }
156
+ const sp = row.securityPass;
157
+ if (sp) {
158
+ const shown = sp.state === "required" ? `required (${sp.matched} sensitive path${sp.matched === 1 ? "" : "s"} changed), none recorded at this head`
159
+ : sp.state === "recorded" ? `recorded at this head (${sp.recorded?.covered ?? 0} covered, ${sp.recorded?.notCovered ?? 0} not covered)`
160
+ : sp.state === "unknown" ? "unknown (PR file inventory incomplete or unreadable)" : "not required";
161
+ out.push(...pair("security pass", `${shown}${list(sp.companions).length ? `; companions ${list(sp.companions).join(", ")}` : ""}`, columns, 11, sp.state === "required" || sp.state === "unknown" ? "attention" : undefined, " "));
162
+ }
118
163
  const e = row.evalGate;
119
164
  if (e) {
120
165
  const shown = e.state === "not_configured" ? "eval check not configured (suite choice pending the person)" : e.state === "coverage_unknown" ? "PR file coverage unknown" : `${e.check} ${String(e.state)}${e.passRate !== undefined ? `, pass rate ${e.passRate}` : ""}${e.suite !== undefined ? `, suite ${e.suite}` : ""}`;
@@ -164,6 +209,24 @@ export function renderSdlcQueue(reply: unknown, columns?: number, _now = Date.no
164
209
  if (list(report.conflicts).length) out.push(blank, ...bullets("file conflicts", list(report.conflicts).map((c: any) => `#${c.left} and #${c.right} share ${plural(c.files ?? 0, "file")} (${c.order === "person_required" ? "the person orders them" : "dependency order"})`), columns, "attention"));
165
210
  return out;
166
211
  }
212
+ /** One line for the audit's unit states, shared by `audit show` and the release readback. */
213
+ function auditStates(a: any): string {
214
+ const c = a?.counts ?? {};
215
+ return `${c.covered ?? 0} covered${a?.prior ? ` (${a.prior} prior)` : ""}, ${c.deferred ?? 0} deferred, ${c.out_of_scope ?? 0} out of scope, ${c.planned ?? 0} planned`;
216
+ }
217
+ /** `ahub sdlc audit show`: the ledger's counts first, then each unit, then the findings. An open important finding shows its id and status only, unless the caller is the person. */
218
+ export function renderSdlcAudit(reply: unknown, columns?: number, _now = Date.now()): Span[][] {
219
+ const a = (reply as any)?.audit;
220
+ if (!a) return [...heading("Security audit", columns), ...pair("audits", "none started: run ahub sdlc audit start", columns, 10, "muted")];
221
+ const out: Line[] = [...heading(`Security audit ${a.audit} (task #${a.task})`, columns)];
222
+ out.push(...pair("source", `${short(a.ref)}, profile ${a.profile}${a.scoped ? ", scoped" : ""}`, columns, 10), ...pair("coverage", `${a.partial ? "partial: " : ""}${auditStates(a)}`, columns, 10, a.partial || a.counts?.planned ? "attention" : undefined));
223
+ const f = a.findings ?? {};
224
+ out.push(...pair("findings", `${f.verified ?? 0} verified, ${f.candidate ?? 0} candidate (unverified), ${f.needsValidation ?? 0} needs validation, ${f.rejected ?? 0} rejected, ${f.settled ?? 0} settled, ${f.other ?? 0} other`, columns, 10, f.candidate ? "attention" : undefined));
225
+ for (const u of list(a.units)) out.push(...pair(String(u.state).replace("_", " "), `${u.unit}${u.prior ? ` (prior audit ${u.prior.audit})` : ""}${u.reason ? `: ${u.reason}` : ""}`, columns, 14, u.state === "planned" ? "attention" : undefined, " "));
226
+ for (const item of list(a.items)) out.push(...pair(String(item.status), `${item.id} (${item.severity}, ${item.disposition})${item.withheld ? ", details withheld" : item.path ? ` ${item.path}` : ""}`, columns, 14, item.status === "candidate" ? "attention" : undefined, " "));
227
+ if (a.withheld) out.push(...pair("withheld", `${a.withheld} open important finding${a.withheld === 1 ? "" : "s"}: boundary text is shown to the person only`, columns, 10, "muted"));
228
+ return out;
229
+ }
167
230
  /** `ahub sdlc release <repo> [live-issue...]`: source, document, issue and authorization evidence, then what blocks the release. */
168
231
  export function renderSdlcRelease(reply: unknown, columns?: number, now = Date.now()): Span[][] {
169
232
  const r = (reply as any)?.report ?? {};
@@ -185,6 +248,8 @@ export function renderSdlcRelease(reply: unknown, columns?: number, now = Date.n
185
248
  if (a) out.push(blank, ...pair("authorization", `${a.state}: version ${a.receipt?.version ?? "unknown"} at ${short(a.receipt?.commit)}, approved ${moment(a.receipt?.at, now)}`, columns, w, a.state === "matched" ? "success" : "attention"));
186
249
  else out.push(blank, ...pair("authorization", r.releasePolicy ? `none recorded for ${r.releasePolicy.versionSource}: run ahub sdlc authorize-release <version>` : "none recorded: run ahub sdlc authorize-release <version>", columns, w, "muted"));
187
250
  for (const t of list(r.trains)) out.push(...pair(`train #${t.release?.id ?? "?"}`, `${t.readiness?.trigger ?? "unknown"}${list(t.readiness?.blockers).length ? `, ${list(t.readiness.blockers).join("; ")}` : ""}`, columns, w, list(t.readiness?.blockers).length ? "attention" : undefined));
251
+ const sa = r.securityAudit;
252
+ if (sa) out.push(blank, ...pair("security audit", `${short(sa.ref)} ${sa.profile}${sa.partial ? " (partial)" : ""}: ${auditStates(sa)}${sa.findings?.candidate ? `, ${sa.findings.candidate} unverified candidate${sa.findings.candidate === 1 ? "" : "s"}` : ""}`, columns, w, sa.partial || sa.counts?.planned ? "attention" : undefined));
188
253
  const rm = r.releaseMetrics;
189
254
  if (rm) {
190
255
  const mean = (values: unknown[]) => { const known = values.filter((v): v is number => typeof v === "number" && Number.isFinite(v)); return known.length ? span(known.reduce((a, b) => a + b, 0) / known.length) : "unknown"; };
@@ -125,3 +125,57 @@ export function renderExperiments(view: unknown, columns?: number): Span[][] {
125
125
  for (const row of attempts) if (row.eventsComplete === false && row.nextEventCursor !== undefined) out.push([s(`more events of ${row.id}: ahub study experiments --attempt ${row.id} --events-after ${row.nextEventCursor}; the values above come from the events shown so far`, "attention")]);
126
126
  return out;
127
127
  }
128
+
129
+
130
+ /** Screened passage or declared manifest-authoring metadata, never an entailment/quality claim. */
131
+ export function renderStudyEvidence(value: unknown, columns?: number): Span[][] {
132
+ const v = value as any;
133
+ if (v?.status !== "resolved" && v?.status !== "available") return [[s(`Evidence ${v?.status ?? "unavailable"}; use a visible research task and current public evidence`, "attention")]];
134
+ const out: Span[][] = [...heading(v.status === "resolved" ? `Evidence ${v.id} r${v.revision}` : `Declared evidence inventory, task ${v.taskId}`, columns)];
135
+ if (v.status === "resolved") {
136
+ out.push(...pair("status", "resolved provenance only; no entailment or source-quality certification", columns, 12));
137
+ out.push(...pair("source", v.link?.sourceId, columns, 12));
138
+ out.push(...pair("scalars", `${v.locator?.start}..${v.locator?.end}`, columns, 12));
139
+ out.push(...pair("passage", v.excerpt, columns, 12));
140
+ } else {
141
+ out.push(...pair("incarnation", v.taskCreated, columns, 12));
142
+ for (const artifact of list(v.deliverables)) out.push(...pair("artifact", `${artifact.id} ${artifact.format} ${artifact.sha256}`, columns, 12));
143
+ for (const claim of list(v.claims)) {
144
+ out.push(...pair("claim", `${claim.claimId} @ ${claim.claimRevision}`, columns, 12));
145
+ out.push(...pair("inventory", claim.complete && claim.inventory ? `r${claim.inventory.revision} ${claim.inventory.sha256}` : "unknown/incomplete: obtain complete inventory before checking", columns, 12));
146
+ for (const link of list(claim.evidence)) out.push(...pair("link", `${link.id} r${link.revision} ${link.status}`, columns, 12));
147
+ }
148
+ out.push([s("Declared bindings only. Select citation mappings in a synthesis manifest; invoke ahub study check explicitly.", "muted")]);
149
+ }
150
+ return out;
151
+ }
152
+
153
+ const SYNTHESIS_NEXT: Record<string, string> = {
154
+ refresh_manifest: "refresh claim, link, inventory and artifact bindings in the manifest",
155
+ provide_artifact: "register unchanged public Markdown/BibTeX deliverables through the existing deliverable workflow",
156
+ repair_citations: "repair declared Markdown citation keys and their BibTeX entries",
157
+ record_evidence: "record current claim evidence with hub_evidence_record",
158
+ resolve_locator: "inspect ahub study evidence for current public registered projection/locator provenance",
159
+ record_person_judgment: "a person records the claim's verdict with ahub task claim; model labels do not count",
160
+ resolve_contradiction: "a person adjudicates or explicitly qualifies the current manifest-bound conclusion",
161
+ read_complete_inventory: "obtain a complete readable inventory; split oversized tasks or repair stored evidence before retrying",
162
+ complete_manifest_claims: "include every current declared task claim in the manifest",
163
+ };
164
+ export function renderSynthesisReadiness(value: unknown, columns?: number): Span[][] {
165
+ const v = value as any, out: Span[][] = [...heading(`Synthesis ${v?.status ?? "unavailable"}`, columns)];
166
+ if (v?.status === "private") return [...out, [s("Readiness withheld by current task/source/artifact privacy; no research content is disclosed.", "attention")]];
167
+ if (!v?.scope) {
168
+ const reason = v?.cause === "source_input_limit" ? "Source input exceeds this bounded check; split the synthesis into smaller tasks."
169
+ : "Inputs or policy changed/unavailable; refresh current public bindings and run ahub study check again.";
170
+ return [...out, [s(reason, "attention")]];
171
+ }
172
+ out.push(...pair("scope", "structural/provenance only; not truth, entailment or source-quality verification", columns, 12));
173
+ for (const key of ["manifestSha256", "binding", "claimCoverage", "deliverable", "bibliography"]) out.push(...pair(key, v[key], columns, 12));
174
+ out.push(...pair("citations", `${v.citations?.state} (cited ${v.citations?.cited ?? "unknown"}, missing ${v.citations?.missing ?? "unknown"})`, columns, 12));
175
+ for (const claim of list(v.claims)) {
176
+ out.push(...heading(claim.claimId, columns));
177
+ for (const key of ["claim", "inventory", "citationKey", "evidenceLink", "locator", "provenance", "judgment", "personVerdict", "contradictionHistory", "contradiction"]) out.push(...pair(key, claim[key], columns, 14));
178
+ }
179
+ for (const next of list(v.next)) out.push(...pair("next", SYNTHESIS_NEXT[next] ?? "inspect the current manifest bindings", columns, 12, "attention"));
180
+ return out;
181
+ }
package/src/cli/study.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  // Argument parsing for `ahub study` (#601). Pure: argv in, one request description or a usage line out, so the I/O in main.ts stays a thin dispatcher and every form is testable without a daemon.
2
- export const STUDY_USAGE = "usage: ahub study draft <parent> <contract.json> | revise <id> <revision> <contract.json> | approve <id> <revision> | approve-protocol <hash> | close <id> <revision> --reason <text> | show [<id> | --after <id>] | experiments (--campaign <id> [--after <n>] | --attempt <ra-id> [--events-after <n>] | --plan <hash> --baseline <ra-id> --variant <ra-id>) [--json] [--color=auto|always|never]";
2
+ export const STUDY_USAGE = "usage: ahub study draft <parent> <contract.json> | revise <id> <revision> <contract.json> | approve <id> <revision> | approve-protocol <hash> | close <id> <revision> --reason <text> | evidence <ev-id> [--revision <n>] | evidence --task <task> | check <task> <manifest.json> | show [<id> | --after <id>] | experiments (--campaign <id> [--after <n>] | --attempt <ra-id> [--events-after <n>] | --plan <hash> --baseline <ra-id> --variant <ra-id>) [--json] [--color=auto|always|never]";
3
3
 
4
4
  export type StudyRequest =
5
+ | { op: "evidence"; id: string; revision?: number }
6
+ | { op: "evidence_inventory"; taskId: number }
7
+ | { op: "check"; taskId: number; file: string }
5
8
  | { op: "draft"; parentTaskId: number; file: string }
6
9
  | { op: "revise"; id: string; revision: number; file: string }
7
10
  | { op: "approve"; id: string; revision: number }
@@ -18,6 +21,16 @@ export function parseStudyArgs(operands: readonly string[]): StudyRequest | { us
18
21
  const [sub, ...rest] = operands;
19
22
  const id = (value: string | undefined) => value !== undefined && ID.test(value) ? value : undefined;
20
23
  const int = (value: string | undefined) => value !== undefined && INT.test(value) ? Number(value) : undefined;
24
+ if (sub === "check") {
25
+ const taskId = int(rest[0]);
26
+ return rest.length === 2 && taskId !== undefined && !!rest[1] ? { op: "check", taskId, file: rest[1] } : usage("check needs a task id and a bounded synthesis manifest file");
27
+ }
28
+ if (sub === "evidence") {
29
+ if (rest[0] === "--task") { const taskId = int(rest[1]); return rest.length === 2 && taskId !== undefined ? { op: "evidence_inventory", taskId } : usage(); }
30
+ const evidence = rest[0], revision = rest.length === 3 && rest[1] === "--revision" ? int(rest[2]) : undefined;
31
+ return evidence !== undefined && /^ev:[a-f0-9]{32}$/.test(evidence) && (rest.length === 1 || rest.length === 3 && revision !== undefined)
32
+ ? { op: "evidence", id: evidence, ...(revision === undefined ? {} : { revision }) } : usage("evidence needs a recorded ev:<32 hex> id or --task <task>");
33
+ }
21
34
  if (sub === "approve-protocol") {
22
35
  if (rest.length !== 1) return usage();
23
36
  const hash = rest[0];
@@ -1,3 +1,4 @@
1
+ import type { RecoveryLaunchFailure } from "./recovery-launch.ts";
1
2
  import { shellQuote } from "./shell-quote.ts";
2
3
  export { shellQuote } from "./shell-quote.ts";
3
4
  import { createProjectAdapterCatalog, definitionOf, type ProjectAdapterCatalog, type KindMap } from "../adapters/registry.ts";
@@ -77,9 +78,11 @@ export interface RecoveryBlocker {
77
78
  | "terminal-orphaned"
78
79
  | "command-error"
79
80
  | "ambiguous-create"
81
+ | "launch-failed"
80
82
  | "launcher-exited"
81
83
  | "terminal-gone";
82
84
  message: string;
85
+ failure?: RecoveryLaunchFailure;
83
86
  peer?: TerminalPeer;
84
87
  handle?: string;
85
88
  /** Stable terminal reference when Orca supplied one, for operator reconciliation. */
@@ -149,6 +152,8 @@ export interface TerminalCreateResult {
149
152
  }
150
153
 
151
154
  export interface TerminalRecoveryOptions {
155
+ /** Host-owned per-attempt exit observation; diagnostic only, never a readiness proof. */
156
+ launchFailure?: () => RecoveryLaunchFailure | undefined;
152
157
  runner?: CommandRunner;
153
158
  /** Exact execution root returned by authenticated extra startup; checked against the current declaration. */
154
159
  executionCwd?: string;
@@ -286,6 +291,7 @@ function normalizeOptions(options?: CommandRunner | TerminalRecoveryOptions): Re
286
291
  const config: TerminalRecoveryOptions = typeof options === "function" ? { runner: options } : options ?? {};
287
292
  const orcaExecutable = config.orcaExecutable ?? resolveOrcaExecutable();
288
293
  return {
294
+ launchFailure: config.launchFailure ?? (() => undefined),
289
295
  runner: config.runner ?? defaultRunner(orcaExecutable),
290
296
  orcaExecutable,
291
297
  packageEntrypoint: config.packageEntrypoint ?? defaultEntrypoint,
@@ -666,6 +672,7 @@ function blocker(code: RecoveryBlocker["code"], message: string, peer?: Terminal
666
672
  code === "ambiguous-create" ? "inspect the existing terminal and attach the original session before resuming" :
667
673
  code === "terminal-orphaned" ? `reattach the pane with orca terminal switch --terminal ${shellQuote(handle!)}; then refresh in ahub upgrade ([r] on the plan, [s] on an open operation), or rerun it` :
668
674
  code === "terminal-unready" ? "finish or cancel the active terminal turn, then resume recovery" :
675
+ code === "launch-failed" ? "fix the launch refusal, then resume this recovery operation" :
669
676
  code === "launcher-exited" ? "the session was not restored; the coordinator's error names the choices" :
670
677
  code === "terminal-gone" ? "the terminal was closed; inspect the project's terminals in Orca before resuming recovery" :
671
678
  "inspect the named terminal and resume recovery after the identity is verified";
@@ -990,10 +997,16 @@ export async function createTerminal(binding: TerminalBinding, options?: Command
990
997
  // incarnation and no recorded launcher may still run. One that never recorded itself is left to the readiness
991
998
  // bound and to the coordinator's reconciliation of its pending receipt.
992
999
  const exited = (why: string) => ({ created: true, ready: false, manualRequired: true, blockers: [blocker("launcher-exited", `the ${binding.peer} restoration launcher in terminal ${createdHandle} ${why} before its TUI was ready`, binding.peer, createdHandle)] });
1000
+ const failed = () => {
1001
+ const failure = config.launchFailure();
1002
+ return failure ? { created: true, ready: false, manualRequired: true, blockers: [{ ...blocker("launch-failed", `restoration command exited ${failure.exitCode}: ${failure.firstLine}; fix the cause, then resume this recovery operation`, binding.peer, createdHandle), failure }] } : undefined;
1003
+ };
993
1004
  const deadline = Date.now() + Math.min(timeoutMs, MAX_WAIT_MS);
994
1005
  const slice = () => Math.max(1, Math.min(EXIT_SLICE_MS, deadline - Date.now())); // Orca refuses --timeout-ms 0
1006
+ const earlyFailure = failed(); if (earlyFailure) return earlyFailure;
995
1007
  let idle = await waitForIdle(replacement, slice(), config);
996
1008
  for (;;) {
1009
+ const failure = failed(); if (failure) return failure;
997
1010
  if (idle.blockers[0]?.code === "terminal-gone") {
998
1011
  const launch = await launches();
999
1012
  if (launch.gone) return exited("exited");
@@ -1015,6 +1028,7 @@ export async function createTerminal(binding: TerminalBinding, options?: Command
1015
1028
  // An idle terminal may be the login shell the launcher returned to, or a TUI that has not yet recorded its
1016
1029
  // launch or been identified by Orca (#599): poll until it maps, contradicts, or the deadline passes.
1017
1030
  for (;;) {
1031
+ const failure = failed(); if (failure) return failure;
1018
1032
  const launch = await launches();
1019
1033
  if (launch.gone) return exited("exited");
1020
1034
  const shown = await showBinding(replacement, config);
@@ -159,6 +159,10 @@ export function renderBlocked(op: RecoveryOperation, choices: readonly NextChoic
159
159
  const marker = op.projects.find(project => project.id === projectId)?.reattachments?.[peer];
160
160
  happened = `${peer}'s recorded session needs reattachment.`;
161
161
  why = marker ? `${projectId}: the session detached after restoration; its recorded terminal is ${marker.binding.handle} and its accepted conversation is ${marker.binding.sessionId}.` : "The terminal and session evidence is unknown in this receipt.";
162
+ } else if (op.failure?.code === "version_refused" || op.failure?.code === "launch_exit") {
163
+ happened = `${op.failure.peer}: the restoration command exited before readiness.`;
164
+ why = `${op.failure.code} (exit ${op.failure.exitCode}): ${terminalText(op.failure.firstLine)}`;
165
+ action = `Fix the cause, then ${recoveryCommand(op, "resume")}. The hold remains until recovery settles.`;
162
166
  } else if (op.failure?.code === "database_busy") {
163
167
  happened = "The recovery database could not complete this step yet.";
164
168
  why = "The coordinator recorded database contention as retryable; its saved recovery state is retained.";
@@ -1,3 +1,4 @@
1
+ import type { RecoveryLaunchFailure } from "./recovery-launch.ts";
1
2
  import { ADAPTERS, definitionOf } from "../adapters/registry.ts";
2
3
  import { readInstanceConfig } from "../hub/instance-config.ts";
3
4
  import type { TerminalBinding } from "./terminal-recovery.ts";
@@ -6,7 +7,7 @@ export type RestoreReceipt =
6
7
  | { state: "pending" }
7
8
  | { state: "waiting"; origin: "pending" | "failed"; binding: TerminalBinding }
8
9
  | { state: "done"; binding: TerminalBinding }
9
- | { state: "failed" };
10
+ | { state: "failed"; failure?: RecoveryLaunchFailure };
10
11
  export interface RestoreEvidence {
11
12
  target: "running" | "stopped" | "changed";
12
13
  launcher: "live" | "gone" | "unknown" | "no-record-yet" | "replaced" | "older-instance";
@@ -50,10 +51,18 @@ export function decodeRestoreReceipt(value: unknown, options: { authority?: "cur
50
51
  if (value === "pending" || value === "failed") return { state: value };
51
52
  if (!object(value)) malformed();
52
53
  if (Object.hasOwn(value, "state")) {
53
- const allowed = value.state === "waiting" ? ["state", "origin", "binding"] : value.state === "done" ? ["state", "binding"] : ["state"];
54
+ const allowed = value.state === "waiting" ? ["state", "origin", "binding"] : value.state === "done" ? ["state", "binding"] : value.state === "failed" ? ["state", "failure"] : ["state"];
54
55
  if (Object.keys(value).some(key => !allowed.includes(key))) malformed();
55
56
  switch (value.state) {
56
- case "pending": case "failed": return { state: value.state };
57
+ case "pending": return { state: "pending" };
58
+ case "failed": {
59
+ const failure = value.failure;
60
+ if (failure !== undefined && (!object(failure) || !["version_refused", "launch_exit"].includes(String(failure.code))
61
+ || !Number.isInteger(failure.exitCode) || Number(failure.exitCode) <= 0 || Number(failure.exitCode) > 255
62
+ || typeof failure.firstLine !== "string" || Array.from(failure.firstLine).length > 512
63
+ || Object.keys(failure).some(key => !["code", "exitCode", "firstLine"].includes(key)))) malformed();
64
+ return { state: "failed", ...(failure ? { failure: failure as unknown as RecoveryLaunchFailure } : {}) };
65
+ }
57
66
  case "waiting": {
58
67
  if (value.origin !== "pending" && value.origin !== "failed") malformed();
59
68
  return { state: "waiting", origin: value.origin, binding: terminalBinding(value.binding, historical) };