@staix/agent-hub 0.38.0 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/README.md +28 -12
  3. package/docs/adding-an-ai-tool.md +7 -5
  4. package/docs/agent-notes/README.md +23 -0
  5. package/docs/agent-notes/adapters.md +9 -5
  6. package/docs/agent-notes/benchmarks.md +2 -0
  7. package/docs/agent-notes/budget.md +9 -0
  8. package/docs/agent-notes/bus.md +1 -0
  9. package/docs/agent-notes/daemon.md +21 -9
  10. package/docs/agent-notes/local-worker.md +4 -2
  11. package/docs/agent-notes/security-review.md +56 -0
  12. package/docs/agent-notes/tasks.md +22 -6
  13. package/docs/agent-notes/tests.md +10 -9
  14. package/docs/contracts/companion-cli-v1.json +4 -0
  15. package/docs/design/adapters.md +142 -0
  16. package/docs/design/agent-hub-architecture.md +46 -1
  17. package/docs/design/agent-hub.md +10 -0
  18. package/docs/design/bus.md +7 -0
  19. package/docs/design/cli-output.md +183 -0
  20. package/docs/design/execution-reference.md +6 -1
  21. package/docs/design/roadmap.md +191 -0
  22. package/docs/design/task-board.md +185 -5
  23. package/docs/dogfood.md +30 -9
  24. package/docs/events.md +7 -7
  25. package/docs/memory.md +5 -5
  26. package/docs/operations.md +315 -54
  27. package/docs/profiles.md +101 -8
  28. package/docs/quickstart.md +47 -6
  29. package/docs/research.md +6 -3
  30. package/docs/roles.md +52 -0
  31. package/docs/sdlc.md +190 -2
  32. package/docs/security.md +90 -15
  33. package/docs/text-projection.md +1 -0
  34. package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
  35. package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
  36. package/docs/verification/2026-11-14-0.39.0.md +51 -0
  37. package/docs/verification/2026-11-14-codex-0169-reviewer-isolation.md +70 -0
  38. package/docs/verification/2026-11-14-codex-0169-reviewer-tool-call.md +48 -0
  39. package/docs/verification/2026-11-14-pi-152-compat.md +45 -0
  40. package/docs/verification/2026-11-15-0.40.0.md +39 -0
  41. package/docs/verification/2026-11-16-pi-loopback-1447.md +39 -0
  42. package/docs/verification/pi-152-model-free.ts +57 -0
  43. package/docs/verification/pi-152-native.mjs +21 -0
  44. package/docs/verified.json +48 -25
  45. package/package.json +4 -4
  46. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  47. package/plugins/agent-hub/kimi-hook.js +2266 -530
  48. package/plugins/agent-hub/kimi-review-policy-worker.js +16 -11
  49. package/plugins/agent-hub/server.js +2423 -645
  50. package/src/adapters/acp-model-policy.ts +1 -1
  51. package/src/adapters/acp-session-model.ts +35 -0
  52. package/src/adapters/acp.ts +14 -0
  53. package/src/adapters/agy/definition.ts +2 -2
  54. package/src/adapters/agy/hooks.ts +7 -0
  55. package/src/adapters/claude-channel.ts +1 -1
  56. package/src/adapters/claude-implementer.ts +8 -0
  57. package/src/adapters/claude-print-child.ts +26 -2
  58. package/src/adapters/claude-print.ts +4 -0
  59. package/src/adapters/codex-appserver.ts +90 -16
  60. package/src/adapters/codex-review-isolation.ts +63 -17
  61. package/src/adapters/compat.ts +10 -10
  62. package/src/adapters/conformance/fakes/acp-server.ts +11 -2
  63. package/src/adapters/conformance/fakes/app-server.ts +5 -1
  64. package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
  65. package/src/adapters/definitions/builtin-metadata.ts +12 -12
  66. package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
  67. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  68. package/src/adapters/definitions/native-config-policy.ts +1 -1
  69. package/src/adapters/definitions/native-quota.ts +122 -0
  70. package/src/adapters/definitions/native-recovery.ts +3 -0
  71. package/src/adapters/definitions/qwen.ts +2 -2
  72. package/src/adapters/kimi-review.ts +23 -0
  73. package/src/adapters/kimi-wire-usage.ts +39 -16
  74. package/src/adapters/local-worker.ts +9 -4
  75. package/src/adapters/pi-state-model.ts +12 -0
  76. package/src/adapters/pi.ts +76 -11
  77. package/src/adapters/print-result-model.ts +24 -0
  78. package/src/adapters/registry-types.ts +12 -2
  79. package/src/adapters/registry.ts +19 -2
  80. package/src/adapters/reviewer-print.ts +132 -16
  81. package/src/adapters/role-eligibility.ts +99 -0
  82. package/src/adapters/same-directory.ts +16 -0
  83. package/src/cli/agy-mcp.ts +18 -7
  84. package/src/cli/answer-args.ts +11 -3
  85. package/src/cli/console-question.ts +1 -1
  86. package/src/cli/console-state.ts +98 -11
  87. package/src/cli/console.ts +6 -2
  88. package/src/cli/error-format.ts +19 -0
  89. package/src/cli/free-text.ts +20 -0
  90. package/src/cli/handoff-args.ts +1 -1
  91. package/src/cli/help.ts +350 -30
  92. package/src/cli/identity-audit.ts +8 -7
  93. package/src/cli/identity.ts +27 -4
  94. package/src/cli/init-prompt.ts +31 -2
  95. package/src/cli/init-roles.ts +156 -0
  96. package/src/cli/init-settings.ts +24 -2
  97. package/src/cli/init.ts +232 -17
  98. package/src/cli/main.js +2 -2
  99. package/src/cli/main.ts +250 -69
  100. package/src/cli/model.ts +1 -1
  101. package/src/cli/output-standard.ts +56 -0
  102. package/src/cli/output.ts +199 -9
  103. package/src/cli/preview.ts +1 -1
  104. package/src/cli/recovery-launch.ts +114 -0
  105. package/src/cli/recovery-package.ts +14 -7
  106. package/src/cli/recovery-version-preflight.ts +104 -0
  107. package/src/cli/roadmap.ts +215 -0
  108. package/src/cli/role-doctor.ts +39 -0
  109. package/src/cli/sdlc-output.ts +66 -1
  110. package/src/cli/smoke-pty-bridge.ts +7 -24
  111. package/src/cli/study-output.ts +54 -0
  112. package/src/cli/study.ts +14 -1
  113. package/src/cli/task-output.ts +3 -1
  114. package/src/cli/terminal-recovery.ts +14 -0
  115. package/src/cli/upgrade-presentation-flags.ts +2 -2
  116. package/src/cli/upgrade-presentation.ts +4 -0
  117. package/src/cli/upgrade-restore-state.ts +12 -3
  118. package/src/cli/upgrade-runtime.ts +40 -2
  119. package/src/cli/upgrade.ts +8 -4
  120. package/src/hub/advisor-survey.ts +139 -0
  121. package/src/hub/audit-source.ts +66 -0
  122. package/src/hub/board.ts +677 -15
  123. package/src/hub/budget.ts +54 -4
  124. package/src/hub/bus.ts +9 -0
  125. package/src/hub/check-runner.ts +3 -4
  126. package/src/hub/ci-watch.ts +19 -4
  127. package/src/hub/conductor.ts +14 -8
  128. package/src/hub/config-apply.ts +2 -1
  129. package/src/hub/config-edit-host.ts +77 -5
  130. package/src/hub/considered-findings.ts +47 -0
  131. package/src/hub/control-client.ts +1 -1
  132. package/src/hub/daemon.ts +585 -98
  133. package/src/hub/deliverable-files.ts +17 -1
  134. package/src/hub/dogfood-profile.ts +3 -2
  135. package/src/hub/events.ts +25 -4
  136. package/src/hub/execution-reference.ts +1 -1
  137. package/src/hub/folder-trigger.ts +11 -4
  138. package/src/hub/github-import.ts +81 -0
  139. package/src/hub/hub-tools.ts +117 -20
  140. package/src/hub/install-policy.ts +23 -0
  141. package/src/hub/kimi-usage.ts +34 -2
  142. package/src/hub/lifecycle-schema.ts +3 -3
  143. package/src/hub/memory-profile.ts +9 -1
  144. package/src/hub/memory-sync-state.ts +1 -0
  145. package/src/hub/model-overrides.ts +2 -1
  146. package/src/hub/no-writes.ts +5 -0
  147. package/src/hub/operational-authority.ts +8 -1
  148. package/src/hub/operational-view.ts +6 -2
  149. package/src/hub/peers.ts +2 -0
  150. package/src/hub/pi-failure.ts +7 -0
  151. package/src/hub/plan-conformance.ts +20 -2
  152. package/src/hub/question-desk.ts +26 -7
  153. package/src/hub/questions.ts +33 -5
  154. package/src/hub/quota-account.ts +34 -0
  155. package/src/hub/recovery-policy.ts +18 -4
  156. package/src/hub/research-evidence.ts +51 -3
  157. package/src/hub/research.ts +77 -13
  158. package/src/hub/restart.ts +21 -0
  159. package/src/hub/review-budget.ts +88 -0
  160. package/src/hub/review-findings.ts +93 -12
  161. package/src/hub/reviewer-pool-config.ts +6 -2
  162. package/src/hub/reviewer-pool.ts +39 -6
  163. package/src/hub/roadmap-triage.ts +86 -0
  164. package/src/hub/roadmap-unplaced.ts +169 -0
  165. package/src/hub/roadmap-view.ts +83 -0
  166. package/src/hub/roadmap.ts +127 -0
  167. package/src/hub/routing.ts +7 -3
  168. package/src/hub/sdlc-merge.ts +6 -5
  169. package/src/hub/sdlc-queue.ts +17 -7
  170. package/src/hub/sdlc-release.ts +1 -1
  171. package/src/hub/sdlc.ts +47 -8
  172. package/src/hub/security-audit.ts +178 -0
  173. package/src/hub/security-pass.ts +115 -0
  174. package/src/hub/settings.ts +11 -5
  175. package/src/hub/source-read.ts +80 -2
  176. package/src/hub/sources.ts +57 -9
  177. package/src/hub/specs-task.ts +7 -0
  178. package/src/hub/startup-event-seeds.ts +5 -3
  179. package/src/hub/startup-timing.ts +1 -0
  180. package/src/hub/synthesis-readiness.ts +279 -0
  181. package/src/hub/task-sweep.ts +29 -2
  182. package/src/hub/task-worktree.ts +37 -0
  183. package/src/hub/tasks.ts +1464 -76
  184. package/src/hub/text-projection.ts +11 -1
  185. package/src/memory/capture.ts +2 -1
  186. package/src/pi/dependency-publish.ts +50 -0
  187. package/src/pi/extension.ts +1 -1
  188. package/src/pi/launch.ts +1 -1
  189. package/src/pi/task-dependencies.ts +249 -0
  190. package/src/ui/index.html +56 -13
  191. package/src/ui/office-model.ts +11 -3
  192. package/src/ui/office-space.ts +50 -30
  193. package/src/ui/plugin-questions.ts +5 -0
  194. package/src/ui/plugin.ts +27 -12
  195. package/templates/config.json +1 -1
package/src/cli/model.ts CHANGED
@@ -21,7 +21,7 @@ export function projectModelStatus(value: unknown): RuntimeModelStatus | null {
21
21
  if (descriptor && "value" in descriptor) row[key] = descriptor.value;
22
22
  }
23
23
  } catch { return null; }
24
- if (!peerToken(row.peer) || !(row.effectiveModel === null || isNativeModelToken(row.effectiveModel)) || !(row.desiredModel === null || isNativeModelToken(row.desiredModel)) || !(typeof row.source === "string" && ["override", "instance", "launch", "native default", "native thread default (was override)"].includes(row.source)) || typeof row.pendingNextTurn !== "boolean") return null;
24
+ if (!peerToken(row.peer) || !(row.effectiveModel === null || isNativeModelToken(row.effectiveModel)) || !(row.desiredModel === null || isNativeModelToken(row.desiredModel)) || !(typeof row.source === "string" && ["override", "instance", "launch", "native default", "native thread default (was override)", "observed (served)", "observed (session)"].includes(row.source)) || typeof row.pendingNextTurn !== "boolean") return null;
25
25
  let unsupported: RuntimeModelStatus["unsupported"];
26
26
  if (row.unsupported !== undefined) {
27
27
  if (!row.unsupported || typeof row.unsupported !== "object" || Array.isArray(row.unsupported)) return null;
@@ -0,0 +1,56 @@
1
+ // CLI output standard v1 (docs/design/cli-output.md): the portable core. This file imports nothing, so a CLI outside the hub can reuse it as is. It holds the nine roles, the marker table and color resolution.
2
+ // Human-output code names a role or a marker, never an SGR code or a glyph literal.
3
+ /**
4
+ * The nine semantic roles of CLI output standard v1 on the 16 ANSI colors, so a terminal theme decides the shades. Code names a role,
5
+ * never an SGR code (`test/cli-output-conformance.test.ts` fails on a raw SGR literal in `src/cli/` and `src/hub/`). `value` is the
6
+ * default foreground and carries no SGR. Bold is only for `header`, `section` and the three status roles; no backgrounds.
7
+ */
8
+ /** End of every painted span. */
9
+ export const SGR_RESET = "\x1b[0m";
10
+ /** SGR of the console tones that are not an identity palette entry; the role table above is the standard, these are the TUI's own. */
11
+ export const TONE_SGR = Object.freeze({ strong: "\x1b[1;36m", failure: "\x1b[31m", number: "\x1b[1m", issueRef: "\x1b[4m", taskRef: "\x1b[4;35m" } as const);
12
+ export type Role = "header" | "section" | "key" | "value" | "success" | "warning" | "error" | "hint" | "accent";
13
+ export const ROLE_SGR: Readonly<Record<Role, string>> = Object.freeze({
14
+ header: "\x1b[1;34m", section: "\x1b[1;35m", key: "\x1b[34m", value: "", success: "\x1b[1;32m", warning: "\x1b[1;33m", error: "\x1b[1;31m", hint: "\x1b[90m", accent: "\x1b[36m",
15
+ });
16
+ export const MARKER_NAMES = ["ok", "fail", "warn", "absent", "unknown", "pending", "active", "next"] as const;
17
+ export type MarkerName = (typeof MARKER_NAMES)[number];
18
+ /** Semantic glyphs, each with its ASCII form and the one role that colors it. Code names a marker, never a glyph literal. */
19
+ export const MARKERS: Readonly<Record<MarkerName, { glyph: string; ascii: string; role: Role }>> = Object.freeze({
20
+ ok: { glyph: "\u2713", ascii: "ok", role: "success" }, fail: { glyph: "\u2717", ascii: "x", role: "error" }, warn: { glyph: "\u26a0", ascii: "!", role: "warning" },
21
+ absent: { glyph: "-", ascii: "-", role: "hint" }, unknown: { glyph: "?", ascii: "?", role: "hint" }, pending: { glyph: "~", ascii: "~", role: "hint" },
22
+ active: { glyph: "*", ascii: "*", role: "success" }, next: { glyph: "\u2192", ascii: "->", role: "accent" },
23
+ });
24
+ export const SECTION_MARKER = { glyph: "\u25b8", ascii: ">" } as const;
25
+ export const MARKER_COLUMN = 2;
26
+ /** Cells a string occupies: East Asian Ambiguous characters count as 1, so a Korean or CJK terminal keeps the same alignment. */
27
+ export const cellWidth = (text: string): number => Bun.stringWidth(text, { ambiguousIsNarrow: true });
28
+ /** A marker padded to the 2-cell marker column (ASCII `ok` and `->` fill it). */
29
+ export function markerCell(name: MarkerName, ascii: boolean): string {
30
+ const text = ascii ? MARKERS[name].ascii : MARKERS[name].glyph;
31
+ return text + " ".repeat(Math.max(0, MARKER_COLUMN - cellWidth(text)));
32
+ }
33
+ /** The environment one output stream's color decision reads (`streamEnv` builds it). */
34
+ export interface ColorEnv { isTTY: boolean; TERM?: string; NO_COLOR?: string; FORCE_COLOR?: string; CLICOLOR?: string; CLICOLOR_FORCE?: string }
35
+ /** `isTTY` of the stream that is decided (stdout and stderr are decided separately) plus the color variables of `env`. */
36
+ export function streamEnv(isTTY: boolean, env: Readonly<Record<string, string | undefined>> = process.env): ColorEnv {
37
+ return { isTTY, TERM: env.TERM, NO_COLOR: env.NO_COLOR, FORCE_COLOR: env.FORCE_COLOR, CLICOLOR: env.CLICOLOR, CLICOLOR_FORCE: env.CLICOLOR_FORCE };
38
+ }
39
+ /**
40
+ * Color for one stream, first rule wins (standard v1): `--color=never|always`; non-empty NO_COLOR off; FORCE_COLOR or CLICOLOR_FORCE
41
+ * non-empty and not `0` on; FORCE_COLOR=0 or CLICOLOR=0 off; a TTY whose TERM is not `dumb` on; otherwise off. `auto` and no flag
42
+ * apply rules 2 to 6. An unknown flag value is a usage error. `--json` is never colored: the caller does not ask.
43
+ */
44
+ export function resolveColor(flag: string | undefined, env: ColorEnv): boolean | Error {
45
+ if (flag === "always") return true;
46
+ if (flag === "never") return false;
47
+ if (flag !== undefined && flag !== "auto") return new Error("usage: ahub <command> [--color=auto|always|never]");
48
+ if (env.NO_COLOR) return false;
49
+ if ((env.FORCE_COLOR && env.FORCE_COLOR !== "0") || (env.CLICOLOR_FORCE && env.CLICOLOR_FORCE !== "0")) return true;
50
+ if (env.FORCE_COLOR === "0" || env.CLICOLOR === "0") return false;
51
+ return env.isTTY && env.TERM !== "dumb";
52
+ }
53
+ /** ASCII markers when `--ascii` is given or the locale (`LC_ALL`, then `LC_CTYPE`, then `LANG`) is not UTF-8. */
54
+ export function asciiMarkers(env: Readonly<Record<string, string | undefined>> = process.env, flag = false): boolean {
55
+ return flag || !/utf-?8/i.test(env.LC_ALL || env.LC_CTYPE || env.LANG || "");
56
+ }
package/src/cli/output.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { ReviewGate, ReviewUnknownQuota } from "../hub/review-budget.ts";
2
+ import { quotaAccountReading } from "../hub/quota-account.ts";
1
3
  import { projectModelStatus } from "./model.ts";
2
4
  import type { RuntimeModelStatus } from "../hub/model-overrides.ts";
3
5
  import type { QueueBackpressureStatus } from "../hub/queue-backpressure.ts";
@@ -5,7 +7,7 @@ import { definitionOf } from "../adapters/registry.ts";
5
7
  import { windowKind } from "../hub/window-kind.ts";
6
8
  import { boardColumns, type BoardPeerInput } from "../ui/task-board.ts";
7
9
  import { peerStyle } from "../ui/peer-palette.ts";
8
- import { cells, TABLES, table, fitLine, wrap, duration, relative, plural, terminalText, initialConsoleState, stateTone, type Span, type Tone } from "./console-state.ts";
10
+ import { cells, TABLES, table, fitLine, wrap, duration, relative, plural, terminalText, initialConsoleState, stateTone, Report as LayoutReport, type MarkerName, type Span, type Tone } from "./console-state.ts";
9
11
  import { taskProgress } from "../ui/task-progress.ts";
10
12
  import { backendLabel, memorySyncLine, reviewInputHealthLine, roomsUnavailableLine } from "./status-lines.ts";
11
13
  import { ownerIsolationText } from "./role-holders.ts";
@@ -46,7 +48,7 @@ export interface StatusOutput {
46
48
  tasks?: Record<string, number>; personRun?: number[]; models?: { backends?: any[] }; permissionDefaults?: any[]; deliveryError?: string; reviewInputHealth?: { state?: string; cause?: string | null }; crash?: string[];
47
49
  }
48
50
  /** `peers`: one note per peer that shows no number, and why (no quota, nothing read yet); absent from an older hub. */
49
- export interface BudgetOutput { budget: Record<string, any>; gate?: number; peers?: { peer: string; kind?: string; note: string }[] }
51
+ export interface BudgetOutput { budget: Record<string, any>; gate?: number; review?: { gate: ReviewGate; unknown_quota: ReviewUnknownQuota; rule: string }; peers?: { peer: string; kind?: string; note: string }[] }
50
52
  export interface RosterRow { peer: string; on: boolean; startMode: string; state: string; queued: number; tasks: number }
51
53
  export function renderRuntimeModels(models: readonly RuntimeModelStatus[], columns?: number): Span[][] {
52
54
  const out = rows(["PEER", "EFFECTIVE MODEL", "SOURCE", "STATE"], models.map(row => [span(row.peer, "info", true), span(row.effectiveModel ?? "not reported"), span(row.source), span(row.pendingNextTurn ? "pending next turn" : "current")]), columns);
@@ -59,6 +61,41 @@ export function renderRuntimeModels(models: readonly RuntimeModelStatus[], colum
59
61
  export function renderRoster(data: RosterRow[], columns?: number): Span[][] {
60
62
  return rows(["PEER", "ROSTER", "START", "STATE", "Q", "TASKS"], data.map(row => [span(row.peer, "info", true), span(row.on ? "on" : "off", row.on ? "success" : "muted", true), span(row.startMode, undefined, true), span(row.state, stateTone(row.state), true), span(row.queued, undefined, true), span(row.tasks, undefined, true)]), columns);
61
63
  }
64
+ /** #1411 T2: who holds which flow role as the running hub settled them, from its status reply. */
65
+ export interface RolesView {
66
+ peers: { peer: string; roles: string[] }[];
67
+ planner: { peers: string[]; source: string } | null;
68
+ reviewFallback: { required: boolean; sameFamily: string } | null;
69
+ }
70
+ export function rolesView(status: any): RolesView {
71
+ const off = new Set((Array.isArray(status?.roster) ? status.roster : []).filter((row: any) => row?.on === false).map((row: any) => row.peer));
72
+ const info = status?.roleInfo && typeof status.roleInfo === "object" ? status.roleInfo : {};
73
+ const peers = Object.keys(info).filter(peer => !off.has(peer)).sort()
74
+ .map(peer => ({ peer, roles: Array.isArray(info[peer]?.flowRoles) ? info[peer].flowRoles.map(String) : [] }));
75
+ const planner = Array.isArray(status?.planner?.peers) ? { peers: status.planner.peers.map(String), source: String(status.planner.source ?? "unknown") } : null;
76
+ const fallback = status?.reviewFallback;
77
+ const reviewFallback = fallback && typeof fallback.required === "boolean" ? { required: fallback.required, sameFamily: String(fallback.sameFamily ?? "fallback") } : null;
78
+ return { peers, planner, reviewFallback };
79
+ }
80
+ /** Who reviews when no pool reviewer can run, as routing decides it (src/hub/routing.ts assign()); an older hub sends no settings, so unknown. */
81
+ function reviewFallbackLine(view: RolesView): string {
82
+ const fallback = view.reviewFallback;
83
+ if (!fallback || !view.planner) return "unknown: this hub does not report it; upgrade the running hub";
84
+ if (fallback.required && fallback.sameFamily !== "never") return "the person (review.pool is set)";
85
+ const planners = view.planner.peers.join(", ");
86
+ if (!planners) return "the person (no planner)";
87
+ return fallback.sameFamily === "never"
88
+ ? `a planner of another family than the task's owner (${planners}), else the person`
89
+ : `a planner other than the task's owner (${planners}), another family first, else the person`;
90
+ }
91
+ export function renderRoles(view: RolesView, columns?: number): Span[][] {
92
+ return [
93
+ ...rows(["PEER", "ROLES"], view.peers.map(row => [span(row.peer, peerTone(row.peer), true), span(row.roles.length ? row.roles.join(", ") : "-", row.roles.length ? undefined : "muted")]), columns),
94
+ [],
95
+ ...lines(`planner: ${view.planner ? `${view.planner.peers.join(", ") || "nobody"} (${view.planner.source})` : "unknown"}`, columns),
96
+ ...lines(`when no reviewer can run: ${reviewFallbackLine(view)}`, columns),
97
+ ];
98
+ }
62
99
  export function outputWidth(env: { isTTY: boolean; columns?: number; COLUMNS?: string }): number | undefined {
63
100
  if (env.isTTY) return Math.max(80, Number.isFinite(env.columns) ? env.columns! : 80);
64
101
  return env.COLUMNS && /^[1-9][0-9]*$/.test(env.COLUMNS) && Number.isSafeInteger(Number(env.COLUMNS)) ? Number(env.COLUMNS) : undefined;
@@ -371,6 +408,119 @@ export function renderStatus(data: StatusOutput, columns?: number, now = Date.no
371
408
  if (data.personRun?.length) out.push(...lines(`WAITING ON YOU ${data.personRun.map(id => `#${id}`).join(", ")} (person-run: no agent is offered it; ahub backlog list)`, columns, "attention"));
372
409
  return out;
373
410
  }
411
+ /** One thing on `ahub status` that needs action: a marker, the finding, and the exact next command when the fix is known. */
412
+ export interface AttentionItem { marker: "fail" | "warn"; text: string; next?: string }
413
+ /**
414
+ * CLI output standard v1: every item of the status data that needs a person or an agent to act, in one list. Facts stay out; a row that is only information
415
+ * is not here. A next step is given only where the command is complete and copyable (no placeholder), never invented.
416
+ */
417
+ export function statusAttention(data: StatusOutput, now = Date.now()): AttentionItem[] {
418
+ const items: AttentionItem[] = [];
419
+ const add = (marker: AttentionItem["marker"], text: string, next?: string) => { items.push({ marker, text: flat(text), ...(next ? { next } : {}) }); };
420
+ if (data.runtimeModelsUnavailable === true) add("warn", "runtime models unavailable: could not read a bounded model catalog", "ahub model list");
421
+ const specs = data.specs;
422
+ if (specs && [specs.errors, specs.stale].every(value => Number.isSafeInteger(value) && value >= 0) && (specs.errors || specs.stale)) add("warn", `specs: ${specs.errors} errors, ${specs.stale} stale`, "ahub specs check");
423
+ if (specs?.truncated) add("warn", "specs: report truncated; narrow specs.roots", "ahub specs check");
424
+ if (specs?.missingBlockHint) add("warn", "specs: AGENTS.md has no specs instruction block");
425
+ for (const pending of data.pendingRestart ?? []) add("warn", `restart pending: ${pending.key}: ${pending.reason}`, "ahub restart --dry-run");
426
+ if (data.mainCheckout) add("warn", `main checkout: ${data.mainCheckout}`);
427
+ // Only a refused version needs action. A trusted one is already accepted (the command would repeat what was done) and an in-line one is within policy: both are facts, shown as a count on the Hub row.
428
+ for (const drift of data.agentDrift ?? []) if (drift.state === "refused") add("warn", `agent CLI ${drift.id} ${drift.version} is refused`, `ahub agents trust ${drift.id} ${drift.version}`);
429
+ if (data.retainedConfig?.length) add("warn", `config retained: ${data.retainedConfig.map(row => row.key).join(", ")}`, "ahub settings reload");
430
+ for (const row of data.schedules ?? []) if (row.error) add("warn", `schedule ${row.id}: ${row.error}`, "ahub schedule list");
431
+ for (const [peer, row] of Object.entries(data.queueBackpressure?.peers ?? {})) if (row.blocked) add("warn", `${peer} queue pressure: automatic offers held: ${row.reason ?? row.code ?? "unknown"}`, `ahub queue list --peer ${peer}`);
432
+ for (const stall of data.taskStalls ?? []) add("warn", `task #${stall.task} stalled: ${stall.cause.kind}${stall.cause.peer ? ` ${stall.cause.peer}` : ""}${stall.cause.dependency ? ` #${stall.cause.dependency}` : ""}: ${stall.cause.code}`, `ahub task show ${stall.task}`);
433
+ for (const offer of data.pendingTaskOffers ?? []) add("warn", `task #${offer.task} is waiting for ${offer.peer}`, `ahub task show ${offer.task}`);
434
+ if (data.memoryProfile?.state === "unavailable") add("warn", `memory unavailable${data.memoryProfile.error ? `: ${data.memoryProfile.error}` : ""}`, "ahub doctor");
435
+ if (data.memoryProfile?.sync?.state === "failed") add("warn", `memory sync failed: ${memorySyncLine(data.memoryProfile.sync)}`, "ahub doctor");
436
+ if (data.memoryRead?.truncated) add("warn", `memory view truncated: newest ${data.memoryRead.limit} project candidates considered`);
437
+ if (data.planner?.source === "none") add("warn", "no planner is configured", "ahub roles");
438
+ for (const [id, isolated] of Object.entries(data.ownerIsolation ?? {})) { const text = ownerIsolationText(isolated, data.ownerIsolationNotes?.[id]); if (text && !isolated) add("warn", `${id} owner isolation: ${text}`); }
439
+ if (data.roomsUnavailable !== undefined) add("fail", roomsUnavailableLine(data.roomsUnavailable));
440
+ if (data.deliveryError) add("fail", `delivery storage: ${data.deliveryError}; dispatch is stopped`, "ahub doctor");
441
+ for (const [peer, count] of Object.entries(data.deliveryFailures ?? {})) if (Number.isSafeInteger(count) && count > 0) add("warn", `${peer} has ${count} failed deliver${count === 1 ? "y" : "ies"}`, `ahub queue discard --peer ${peer} --state failed`);
442
+ if (data.reviewInputHealth) { const health = reviewInputHealthLine(data.reviewInputHealth); if (health) add(data.reviewInputHealth.state === "corrupt" ? "fail" : "warn", `review input provenance: ${health}`); }
443
+ for (const pending of data.permissionDefaults ?? []) add("warn", `permission default: ${pending.peer} never-ask from ${pending.source} stays ask until a person confirms`, "ahub console");
444
+ for (const crash of data.crash ?? []) add("warn", `crash recovery: ${crash}`);
445
+ for (const warning of data.isolatedChecks?.orphans ?? []) add("warn", `isolated check: ${warning}`);
446
+ for (const id of data.isolatedChecks?.unknownReceipts ?? []) add("warn", `check receipt ${id}: unknown; receipt storage unavailable`);
447
+ if (data.isolatedChecks?.maintenanceUnavailable) add("warn", "check maintenance unavailable; saved run outcomes are unchanged");
448
+ for (const [id, p] of Object.entries(data.peers)) {
449
+ for (const session of Array.isArray(p.standbySessions) ? p.standbySessions : []) {
450
+ if (!session || typeof session.id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(session.id)) continue;
451
+ add("warn", `${id} has a standby session waiting${Number.isFinite(session.since) ? ` ${relative(session.since, now)}` : ""}`, `ahub peer takeover ${id} ${session.id}`);
452
+ }
453
+ if (typeof p.reviewObserverHoldNote === "string" && p.reviewObserverHoldNote) add("warn", `${id} review input: ${p.reviewObserverHoldNote}`);
454
+ if (p.heldRows?.length) for (const row of p.heldRows) add("fail", `${id}: a delivery is held for review (from ${row.senders.join(",")}; ${duration(Math.max(0, now - row.createdAt))} old)`, `ahub queue show ${row.id}`);
455
+ else if (p.heldBy) add("fail", `${id}: a delivery is held for review${p.holdNote ? `: ${flat(p.holdNote)}` : ""}`, `${queueResolveCommand({ id: p.heldBy, peer: id, state: "needs_review" })}`);
456
+ if (p.paused) {
457
+ const budgetPause = data.budget?.[id]?.paused;
458
+ const text = budgetPause ? `budget: ${budgetPause.reason ?? "threshold"}${typeof budgetPause.resetsAt === "number" ? `; resets ${relative(budgetPause.resetsAt, now)}` : "; reset unknown"}`
459
+ : typeof p.paused === "object" ? `${p.paused.by ?? "paused"}${p.paused.reason ? `: ${p.paused.reason}` : ""}` : flat(p.paused);
460
+ add("warn", `${id} is paused (${text})`, budgetPause ? "ahub budget" : `ahub resume ${id}`);
461
+ }
462
+ if (typeof p.reviewerUnavailable === "string" && p.reviewerUnavailable) add("fail", `${id} reviewer unavailable: ${flat(p.reviewerUnavailable)}`);
463
+ if (p.ownerIsolationNote) add("warn", `${id} owner isolation: ${p.ownerIsolationNote}`);
464
+ if (typeof p.statusNotice?.message === "string" && p.statusNotice.message) add("warn", `${id}: ${p.statusNotice.message}`);
465
+ if (typeof p.importantWaitingSince === "number" && p.importantWaitingNote) add("warn", `${id}: ${String(p.importantWaitingNote)}`, `ahub queue list --peer ${id}`);
466
+ const actionPolicy = data.actionPolicyInfo?.[id];
467
+ if (actionPolicy?.note && !actionPolicy.enforceable) add("warn", `${id} action policy: ${actionPolicy.note}`);
468
+ }
469
+ for (const b of data.models?.backends ?? []) for (const [key, label] of [["coolingUntil", "cooling"], ["failingUntil", "dispatch held"]] as const) {
470
+ if (!b[key]) continue; const at = Date.parse(b[key]);
471
+ add("warn", `${backendLabel(b)} ${label}${Number.isFinite(at) ? ` until ${relative(at, now)}` : ""}`);
472
+ }
473
+ // The documented line (docs/operations.md, person-run legs): its words are kept so a person searching status for it still finds it.
474
+ if (data.personRun?.length) add("warn", `WAITING ON YOU ${data.personRun.map(id => `#${id}`).join(", ")} (person-run: no agent is offered it)`, "ahub backlog list");
475
+ return items;
476
+ }
477
+ /**
478
+ * `ahub status` as CLI output standard v1 reads it: a header, an Attention section (every item that needs action, marked, with its next command), then the hub,
479
+ * the peers and the tasks. Everything else the older view printed stays in `renderStatus`, behind `--verbose` and `--full`. `columns` undefined is a pipe: no wrap.
480
+ */
481
+ export function renderStatusDefault(data: StatusOutput, columns?: number, now = Date.now(), ascii = false): Span[][] {
482
+ if (data.roleInfo) data = { ...data, peers: Object.fromEntries(Object.entries(data.peers).map(([peer, value]) => [peer, { ...value, ...data.roleInfo?.[peer] }])) };
483
+ const report = new LayoutReport(columns, ascii).header("ahub", "Status", [data.version, data.pid !== undefined ? `pid ${data.pid}` : undefined, data.controlPort !== undefined ? `127.0.0.1:${data.controlPort}` : undefined].filter(Boolean).join(" "));
484
+ const attention = statusAttention(data, now);
485
+ report.section("Attention", attention.length ? plural(attention.length, "item") : undefined);
486
+ if (!attention.length) report.bullet("ok", "nothing needs attention");
487
+ for (const item of attention) { report.bullet(item.marker, item.text); if (item.next) report.next(item.next); }
488
+ const hub: [string, unknown][] = [["version", data.version ?? "unknown"], ["pid", data.pid ?? "unknown"], ["control", `127.0.0.1:${data.controlPort ?? "unknown"}`], ["project", data.cwd ?? ""]];
489
+ if (data.planner) hub.push(["planner", `${data.planner.peers?.join(", ") || "nobody"} (${data.planner.source ?? "unknown"})`]);
490
+ if (data.memoryProfile) hub.push(["memory", `${data.memoryProfile.profile === "generation" ? `generation ${data.memoryProfile.generation?.slice(0, 8) ?? "unknown"}` : data.memoryProfile.profile ?? "unbound"}; ${data.memoryProfile.state ?? "unknown"}`]);
491
+ const specs = data.specs;
492
+ if (specs && [specs.specCount, specs.documents, specs.errors, specs.stale].every(value => Number.isSafeInteger(value) && value >= 0) && (specs.specCount > 0 || specs.documents > 0 || specs.errors > 0)) hub.push(["specs", `${specs.specCount} (errors ${specs.errors}, stale ${specs.stale})`]);
493
+ const outside = (data.agentDrift ?? []).filter(row => row.state !== "refused");
494
+ if (outside.length) hub.push(["agent CLIs", `${outside.length} outside the verified version, already accepted (ahub agents)`]);
495
+ if (data.schedules?.length) hub.push(["schedules", plural(data.schedules.length, "schedule")]);
496
+ report.section("Hub").kv(hub);
497
+ const peers = Object.entries(data.peers);
498
+ const s = initialConsoleState(); s.panel = 1; s.peers = data.peers; s.budget = data.budget ?? {};
499
+ const head = peers.some(([, p]) => p.permissionMode && p.permissionMode !== "ask") ? ["PEER", "STATE", "MODE", ...TABLES[1]!.slice(2)] : [...TABLES[1]!];
500
+ head.push("CONTEXT");
501
+ const peerRows = peers.map(([id, p]) => { const result = cells(s, { id, ...p }, false, now); result[0] = span(id, peerTone(id)); result.push(span(contextText(p, now))); return result; });
502
+ report.section("Peers", peers.length ? `${peers.length}` : undefined);
503
+ if (peerRows.length) report.append(rows(head, peerRows, columns));
504
+ else report.note("no peers attached yet (ahub claude | ahub codex | ahub kimi)");
505
+ // Plain keys under each peer: the peer is the heading, so a key never repeats its name (`form`, not `claude form`).
506
+ for (const [id, p] of peers) {
507
+ const facts: [string, unknown][] = [];
508
+ if (typeof p.form === "string") facts.push(["form", p.form]);
509
+ if (p.flowRoles) facts.push(["flow roles", p.flowRoles.join(", ") || "none"]);
510
+ if (Array.isArray(p.capableRoles)) facts.push(["capable roles", p.capableRoles.join(", ") || "none"]);
511
+ if (p.catalogRoles && Array.isArray(p.catalogRoles.value) && p.catalogRoles.value.length) facts.push(["catalog roles", p.catalogRoles.value.join(", ")]);
512
+ if (typeof p.oldestQueuedAt === "number") facts.push(["oldest queued", relative(p.oldestQueuedAt, now)]);
513
+ if (!facts.length) continue;
514
+ report.append([[{ text: ` ${id}`, tone: peerTone(id) }]]).kv(facts, 4);
515
+ }
516
+ const counts = Object.entries(data.tasks ?? {});
517
+ report.section("Tasks", counts.length ? `${counts.reduce((sum, [, n]) => sum + n, 0)}` : undefined);
518
+ if (counts.length) report.kv(counts.map(([state, n]) => [state, n] as const));
519
+ else report.note("no tasks");
520
+ if (data.taskWip && Object.keys(data.taskWip).length) report.kv([["planner WIP", Object.entries(data.taskWip).map(([peer, value]) => `${peer} ${value.wip}/${value.wipLimit}${wipSplit(value)}`).join("; ")]]);
521
+ report.note("ahub board lists them; ahub status --verbose shows every detail", "hint");
522
+ return report.lines();
523
+ }
374
524
  // #724: short next-step codes for the compact board, keyed on the blocker texts of src/hub/sdlc.ts; the full advice stays in --full and ahub task show.
375
525
  const STAGE_CODES: [string, string][] = [["issue identity missing", "issue?"], ["PR identity missing", "PR?"], ["PR is not open", "PR closed"], ["current PR evidence unknown", "PR state?"],
376
526
  ["required check", "CI?"], ["local gate", "gate?"], ["current head has not been reviewed", "review?"], ["GitHub review approval", "approval?"], ["review requests", "requests?"],
@@ -463,6 +613,7 @@ export function renderBoard(tasks: any[], columns?: number, now = Date.now(), fu
463
613
  }
464
614
  export function renderBudget(data: BudgetOutput, columns?: number, now = Date.now(), _full = false): Span[][] {
465
615
  const out: Span[][] = [];
616
+ if (data.review) out.push(...detail("Reviewer admission", data.review.rule, columns));
466
617
  // KIND names what the number is (#285): the provider's own (native), tokens the hub counted against a ceiling (count), or a person's (manual).
467
618
  // A window without a kind, from an older hub, is classified by `windowKind`. A fresh window that does not gate says so in STATE.
468
619
  const windows = Object.entries(data.budget).flatMap(([peer, b]) => (b.windows ?? []).map((w: any) => [span(peer, peerTone(peer)), span(w.id), span(`${Math.round(w.used * 100)}%`, "number"), span(typeof w.resetsAt === "number" ? relative(w.resetsAt, now) : "-", "muted"), span(windowKind({ id: w.id, source: w.source ?? "", kind: w.kind }), "muted"), span(w.source ?? "unknown", "muted"), span(typeof w.at === "number" ? relative(w.at, now) : "unknown", "muted"), span(w.stale ? "stale" : w.superseded ? "info only" : "fresh", w.stale ? "attention" : undefined)]));
@@ -471,6 +622,23 @@ export function renderBudget(data: BudgetOutput, columns?: number, now = Date.no
471
622
  // A peer with no number says why, in its own line, so a peer without quota is not mistaken for one that has not reported.
472
623
  for (const note of data.peers ?? []) out.push(...detail(note.peer, note.note, columns, peerTone(note.peer)));
473
624
  for (const [peer, b] of Object.entries(data.budget)) if (b.paused) out.push(...detail(`paused ${peer}`, `${b.paused.reason ?? "budget"}${typeof b.paused.resetsAt === "number" ? `; resumes ${relative(b.paused.resetsAt, now)}` : ""}`, columns, "attention"));
625
+ for (const [peer, b] of Object.entries(data.budget)) {
626
+ const info = b.paused ? quotaAccountReading(b.accountUsage) : undefined;
627
+ if (!info) continue;
628
+ const parts: string[] = [];
629
+ if (info.resetCreditsAvailable !== undefined) {
630
+ const expiry = info.resetCreditsExpireAt !== undefined ? `expires ${new Date(info.resetCreditsExpireAt).toISOString().split("T")[0]}`
631
+ : info.resetCreditsExpiryKnown ? "no expiry" : "expiry unknown";
632
+ parts.push(`${plural(info.resetCreditsAvailable, "reset credit")} available${info.resetCreditsAvailable ? ` (${expiry})` : ""}`);
633
+ }
634
+ parts.push(info.ordinaryUsageAllowed === undefined ? "ordinary usage unknown" : info.ordinaryUsageAllowed ? "ordinary usage allowed" : "ordinary usage not allowed");
635
+ const flag = (value: boolean | undefined) => value === undefined ? "unknown" : value ? "yes" : "no";
636
+ parts.push(`credits available: ${flag(info.hasCredits)}`, `unlimited credits: ${flag(info.unlimited)}`);
637
+ if (info.stale) parts.push("stale snapshot");
638
+ else if (info.ordinaryUsageAllowed === false && (info.hasCredits === true || info.unlimited === true)) parts.push("turns would use paid credits");
639
+ out.push(...detail(peer, parts.join("; "), columns, "attention"));
640
+ }
641
+
474
642
  return out;
475
643
  }
476
644
  function boardColumnContext(tasks: any[], allTasks: any[] | null): any[] {
@@ -501,17 +669,39 @@ export function renderBoardColumns(tasks: any[], peers: Record<string, BoardPeer
501
669
  return out;
502
670
  }
503
671
 
504
- export function renderDoctor(checks: DoctorCheck[], columns?: number, _now = Date.now(), _full = false): Span[][] {
505
- const out: Span[][] = [];
506
- const tone = { ok: "success", warn: "attention", fail: "failure", unknown: "muted" } as const;
672
+ /** The standard's cap for every non-flexible text column (docs/design/cli-output.md, Layout grammar: Table). */
673
+ const COLUMN_CAP = 32;
674
+ /** A text longer than `cells` keeps its start and its end and drops the middle: `~/Library/.../home`. Never cuts inside a grapheme. */
675
+ export function shortenMiddle(text: string, cells: number): string {
676
+ const value = flat(text);
677
+ if (width(value) <= cells || cells < 5) return value;
678
+ const units = [...graphemes.segment(value)].map(part => part.segment), room = cells - 3;
679
+ let head = "", tail = "", front = 0, back = units.length;
680
+ const headRoom = Math.ceil(room / 2), tailRoom = room - headRoom;
681
+ for (; front < units.length && width(head + units[front]!) <= headRoom; front++) head += units[front]!;
682
+ for (; back > front && width(units[back - 1]! + tail) <= tailRoom; back--) tail = units[back - 1]! + tail;
683
+ return `${head}...${tail}`;
684
+ }
685
+ const DOCTOR_ORDER: Record<DoctorCheck["level"], number> = { fail: 0, warn: 1, unknown: 2, ok: 3 };
686
+ const DOCTOR_MARKER: Record<DoctorCheck["level"], MarkerName> = { fail: "fail", warn: "warn", unknown: "unknown", ok: "ok" };
687
+ /**
688
+ * `ahub doctor` as standard v1 reads: per section a marker, the check (capped at 32 cells, a long path shortened in the middle) and its finding;
689
+ * failures first, then warnings, unknowns and oks; one summary line last. The word of each state stays in the row, so it reads without color.
690
+ */
691
+ export function renderDoctor(checks: DoctorCheck[], columns?: number, _now = Date.now(), _full = false, ascii = false): Span[][] {
692
+ const report = new LayoutReport(columns, ascii);
507
693
  for (const section of ["Tools", "Hub", "Config", "Models", "Memory"] as const) {
508
694
  const group = checks.filter(check => check.section === section); if (!group.length) continue;
509
- if (out.length) out.push([]); out.push([span(section, "strong")]);
510
- out.push(...rows(["LEVEL", "CHECK", "FINDING"], group.map(check => [span(check.level, tone[check.level]), span(check.name), span(check.detail || "finding unknown")]), columns));
695
+ const worst = group.filter(check => check.level !== "ok").length;
696
+ report.section(section, worst ? `${worst} of ${group.length} need a look` : `${group.length} ok`);
697
+ for (const check of [...group].sort((x, y) => DOCTOR_ORDER[x.level] - DOCTOR_ORDER[y.level])) {
698
+ const name = shortenMiddle(check.name, COLUMN_CAP), finding = flat(check.detail) || "finding unknown";
699
+ report.bullet(DOCTOR_MARKER[check.level], `${check.level === "ok" ? "" : `${check.level} `}${name}: ${finding}`);
700
+ }
511
701
  }
512
702
  const count = (level: DoctorCheck["level"]) => checks.filter(c => c.level === level).length;
513
- out.push([], ...lines(`${count("fail")} failure${count("fail") === 1 ? "" : "s"}, ${count("warn")} warning${count("warn") === 1 ? "" : "s"}, ${count("ok")} ok, ${count("unknown")} unknown`, columns));
514
- return out;
703
+ report.summary({ failed: count("fail"), warnings: count("warn"), unknown: count("unknown"), ok: count("ok") });
704
+ return report.lines();
515
705
  }
516
706
 
517
707
  export function renderProjects(projects: any[], columns?: number, _now = Date.now()): Span[][] {
@@ -10,7 +10,7 @@ import { relayModelIds } from "../models/relay.ts";
10
10
  import { buildPiLaunch } from "../pi/launch.ts";
11
11
 
12
12
  /** Read-only builtin preview. Native redaction uses the same launch builders as actual startup. */
13
- export function launcherPreview(tool: "claude" | "codex" | "kimi" | "pi" | "qwen" | "jcode", raw: string[], cwd: string, stateDir: string, unattended: boolean, requestedInstance?: string) {
13
+ export function launcherPreview(tool: string, raw: string[], cwd: string, stateDir: string, unattended: boolean, requestedInstance?: string) {
14
14
  const config = loadConfig(cwd);
15
15
  const selected = instanceLaunchArguments(tool, requestedInstance ? ["--as", requestedInstance, ...raw] : raw, config.instances);
16
16
  const args = selected.args.filter(arg => !["--print-command", "--dry-run", "--json"].includes(arg));
@@ -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
+ }