@staix/agent-hub 0.50.0 → 0.52.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 (350) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +1 -1
  3. package/docs/adding-an-ai-tool.md +26 -4
  4. package/docs/agent-notes/README.md +1 -0
  5. package/docs/agent-notes/adapters.md +4 -3
  6. package/docs/agent-notes/budget.md +8 -2
  7. package/docs/agent-notes/daemon.md +13 -8
  8. package/docs/agent-notes/local-worker.md +3 -3
  9. package/docs/agent-notes/security-review.md +6 -5
  10. package/docs/agent-notes/tasks.md +10 -3
  11. package/docs/agent-notes/tests.md +4 -3
  12. package/docs/cooperbench.md +1 -1
  13. package/docs/design/adapters.md +21 -0
  14. package/docs/design/cli-output-inventory.md +165 -150
  15. package/docs/design/cli-output.md +4 -3
  16. package/docs/design/guidance-probes.md +1 -0
  17. package/docs/design/roadmap.md +3 -1
  18. package/docs/design/task-board.md +35 -0
  19. package/docs/dogfood.md +21 -3
  20. package/docs/events.md +4 -2
  21. package/docs/memory.md +5 -3
  22. package/docs/operations.md +259 -19
  23. package/docs/quickstart.md +29 -2
  24. package/docs/roadmap.json +20 -20
  25. package/docs/roadmap.md +2 -2
  26. package/docs/roles.md +1 -1
  27. package/docs/sdlc.md +29 -5
  28. package/docs/security.md +11 -5
  29. package/docs/specs/2026-09-19-agent-hub-design.md +44 -0
  30. package/docs/specs/2026-09-19-multi-project-design.md +4 -0
  31. package/docs/specs/2026-09-20-upgrade-recovery-design.md +17 -0
  32. package/docs/specs/mcp-endpoint.md +63 -0
  33. package/docs/verification/2026-11-29-agy-1.5.20.md +33 -0
  34. package/docs/verification/2026-11-29-claude-profile-hook.md +12 -0
  35. package/docs/verification/2026-11-29-idle-daemon-footprint.md +75 -0
  36. package/docs/verification/2026-11-29-kimi-281-reviewer-compat.md +38 -0
  37. package/docs/verification/2026-11-29-kimi-tui-281.md +12 -0
  38. package/docs/verification/2026-11-30-0.51.0.md +91 -0
  39. package/docs/verification/2026-11-30-account-switch-1806.md +445 -0
  40. package/docs/verification/2026-11-30-capability-listing-shape-1808.md +45 -0
  41. package/docs/verification/2026-11-30-upgrade-keep-1807.md +174 -0
  42. package/docs/verification/2026-12-01-1811-confirmation-receipt.md +19 -0
  43. package/docs/verification/2026-12-01-1811-orca-agent-list.md +20 -0
  44. package/docs/verification/2026-12-01-1811-orca-pane-key.md +21 -0
  45. package/docs/verification/2026-12-02-1819-claude-process-after-renewal.md +54 -0
  46. package/docs/verification/2026-12-02-agy-1.5.21.md +74 -0
  47. package/docs/verification/2026-12-02-claude-implementer-2.1.334.md +44 -0
  48. package/docs/verification/2026-12-02-cli-import-graph.md +33 -0
  49. package/docs/verification/2026-12-03-0.52.0.md +150 -0
  50. package/docs/verification/2026-12-03-codex-0173-reviewer-isolation.md +53 -0
  51. package/docs/verification/2026-12-03-codex-0173-reviewer-tool-call.md +34 -0
  52. package/docs/verification/2026-12-03-jcode-1.3.0.md +25 -0
  53. package/docs/verification/agy/README.md +17 -0
  54. package/docs/verification/agy/cli-surface.ts +68 -0
  55. package/docs/verification/agy/interactive-bridge.ts +92 -0
  56. package/docs/verification/agy/interactive-session.ts +131 -0
  57. package/docs/verification/agy/launcher-nonce.ts +215 -0
  58. package/docs/verification/agy/native-hooks.ts +210 -0
  59. package/docs/verification/agy/originals/agent-hub-681/cli-surface.ts +87 -0
  60. package/docs/verification/agy/originals/agent-hub-681/native-hooks-adapted.ts +91 -0
  61. package/docs/verification/agy/originals/agent-hub-681/tui-actual.ts +200 -0
  62. package/docs/verification/agy/originals/agent-hub-684/probe.ts +107 -0
  63. package/docs/verification/agy/originals.json +25 -0
  64. package/docs/verification/agy/permission-new-functions.ts +128 -0
  65. package/docs/verification/agy/run-probe.py +108 -0
  66. package/docs/verification/agy/runtime.ts +171 -0
  67. package/docs/verification/agy/tmux-helper-control.ts +6 -0
  68. package/docs/verification/agy/tmux-session.ts +235 -0
  69. package/docs/verified.json +87 -42
  70. package/package.json +3 -3
  71. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  72. package/plugins/agent-hub/compat.json +157 -0
  73. package/plugins/agent-hub/kimi-hook.js +1416 -24985
  74. package/plugins/agent-hub/server.js +17415 -32755
  75. package/scripts/check-docs.mjs +1 -1
  76. package/src/adapters/acp.ts +13 -13
  77. package/src/adapters/agy/definition.ts +9 -26
  78. package/src/adapters/agy/entry.ts +2 -0
  79. package/src/adapters/channel-peer.ts +3 -1
  80. package/src/adapters/claude-channel-evidence.ts +7 -3
  81. package/src/adapters/claude-channel.ts +38 -257
  82. package/src/adapters/claude-implementer.ts +3 -1
  83. package/src/adapters/codex-appserver.ts +77 -15
  84. package/src/adapters/compat.ts +78 -14
  85. package/src/adapters/configured-acp.ts +23 -163
  86. package/src/adapters/configured-adapter-policy.ts +160 -0
  87. package/src/adapters/configured-pull-entry.ts +53 -0
  88. package/src/adapters/configured-pull.ts +38 -0
  89. package/src/adapters/conformance/fakes/app-server.ts +9 -2
  90. package/src/adapters/declaration-catalog.ts +25 -0
  91. package/src/adapters/declaration-data.ts +342 -0
  92. package/src/adapters/declaration-resolution.ts +53 -0
  93. package/src/adapters/definitions/builtin-metadata.ts +62 -84
  94. package/src/adapters/definitions/jcode-launch.ts +13 -0
  95. package/src/adapters/definitions/native-adapter-policy.ts +390 -0
  96. package/src/adapters/definitions/native-cli-claude-launch.ts +6 -3
  97. package/src/adapters/definitions/native-cli-codex-launch.ts +2 -1
  98. package/src/adapters/definitions/native-cli-entry-claude.ts +17 -2
  99. package/src/adapters/definitions/native-cli-entry-codex.ts +2 -0
  100. package/src/adapters/definitions/native-cli-entry-jcode.ts +6 -2
  101. package/src/adapters/definitions/native-cli-entry-kimi.ts +2 -0
  102. package/src/adapters/definitions/native-cli-entry-pi.ts +2 -0
  103. package/src/adapters/definitions/native-cli-entry-qwen.ts +2 -0
  104. package/src/adapters/definitions/native-cli-entry-types.ts +12 -3
  105. package/src/adapters/definitions/native-cli-jcode-home-init.ts +1 -1
  106. package/src/adapters/definitions/native-cli-launch-common.ts +2 -2
  107. package/src/adapters/definitions/native-cli-preview-common.ts +1 -1
  108. package/src/adapters/definitions/native-cli-retained.ts +1 -1
  109. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  110. package/src/adapters/definitions/native-configuration.ts +18 -0
  111. package/src/adapters/definitions/native-help.ts +24 -0
  112. package/src/adapters/definitions/native-launch-declarations.ts +34 -0
  113. package/src/adapters/definitions/native-launch-policy.ts +4 -0
  114. package/src/adapters/definitions/native-launch-settings.ts +72 -0
  115. package/src/adapters/definitions/native-light-cli.ts +18 -0
  116. package/src/adapters/definitions/native-light-preview.ts +10 -0
  117. package/src/adapters/definitions/native-wrapper-launch.ts +10 -0
  118. package/src/adapters/definitions/qwen.ts +6 -29
  119. package/src/adapters/definitions/reviewer-variants.ts +7 -8
  120. package/src/adapters/external-declarations.ts +31 -0
  121. package/src/adapters/external-modules.ts +4 -29
  122. package/src/adapters/jcode.ts +19 -12
  123. package/src/adapters/native-capabilities.ts +18 -8
  124. package/src/adapters/native-facts-hooks.ts +12 -0
  125. package/src/adapters/native-proof-ports.ts +1 -1
  126. package/src/adapters/presets.ts +136 -0
  127. package/src/adapters/qwen-dual.ts +2 -2
  128. package/src/adapters/registry-types.ts +3 -0
  129. package/src/adapters/registry.ts +20 -81
  130. package/src/adapters/reviewer-print.ts +26 -9
  131. package/src/adapters/role-eligibility.ts +2 -1
  132. package/src/cli/accounts-import.ts +72 -0
  133. package/src/cli/agents-latest-table.ts +88 -0
  134. package/src/cli/agents-latest.ts +22 -0
  135. package/src/cli/agents-output.ts +10 -0
  136. package/src/cli/agents-presets.ts +100 -0
  137. package/src/cli/agents.ts +1 -1
  138. package/src/cli/attention.ts +3 -2
  139. package/src/cli/autonomy-homes.ts +7 -2
  140. package/src/cli/autonomy-offline.ts +1 -1
  141. package/src/cli/bench.ts +1 -1
  142. package/src/cli/budget-renew-guidance.ts +129 -0
  143. package/src/cli/claude-homes.ts +9 -5
  144. package/src/cli/claude-profile-hook.ts +31 -11
  145. package/src/cli/command-context.ts +3 -0
  146. package/src/cli/command-table.ts +123 -0
  147. package/src/cli/commands/accounts.ts +8 -0
  148. package/src/cli/commands/agents.ts +18 -0
  149. package/src/cli/commands/answer.ts +28 -0
  150. package/src/cli/commands/ask.ts +17 -0
  151. package/src/cli/commands/autonomy.ts +83 -0
  152. package/src/cli/commands/backlog.ts +46 -0
  153. package/src/cli/commands/bench.ts +60 -0
  154. package/src/cli/commands/board.ts +48 -0
  155. package/src/cli/commands/broker.ts +9 -0
  156. package/src/cli/commands/budget.ts +96 -0
  157. package/src/cli/commands/capabilities.ts +12 -0
  158. package/src/cli/commands/check-path.ts +55 -0
  159. package/src/cli/commands/completion.ts +8 -0
  160. package/src/cli/commands/console.ts +12 -0
  161. package/src/cli/commands/daemon.ts +8 -0
  162. package/src/cli/commands/deliverables.ts +25 -0
  163. package/src/cli/commands/doctor.ts +249 -0
  164. package/src/cli/commands/down.ts +3 -0
  165. package/src/cli/commands/export.ts +15 -0
  166. package/src/cli/commands/facts.ts +15 -0
  167. package/src/cli/commands/goal.ts +22 -0
  168. package/src/cli/commands/guidance.ts +102 -0
  169. package/src/cli/commands/help.ts +17 -0
  170. package/src/cli/commands/host.ts +45 -0
  171. package/src/cli/commands/init.ts +121 -0
  172. package/src/cli/commands/instructed.ts +19 -0
  173. package/src/cli/commands/instruction-hook.ts +15 -0
  174. package/src/cli/commands/intake.ts +24 -0
  175. package/src/cli/commands/kill.ts +15 -0
  176. package/src/cli/commands/learn.ts +23 -0
  177. package/src/cli/commands/lineage.ts +30 -0
  178. package/src/cli/commands/logs.ts +21 -0
  179. package/src/cli/commands/manager.ts +15 -0
  180. package/src/cli/commands/memory.ts +21 -0
  181. package/src/cli/commands/model.ts +25 -0
  182. package/src/cli/commands/models.ts +40 -0
  183. package/src/cli/commands/native.ts +39 -0
  184. package/src/cli/commands/pause.ts +5 -0
  185. package/src/cli/commands/peer.ts +32 -0
  186. package/src/cli/commands/permission.ts +26 -0
  187. package/src/cli/commands/permit.ts +12 -0
  188. package/src/cli/commands/pet.ts +24 -0
  189. package/src/cli/commands/projects.ts +49 -0
  190. package/src/cli/commands/queue.ts +70 -0
  191. package/src/cli/commands/recovery-run.ts +13 -0
  192. package/src/cli/commands/recovery.ts +130 -0
  193. package/src/cli/commands/release.ts +23 -0
  194. package/src/cli/commands/releases.ts +91 -0
  195. package/src/cli/commands/remember.ts +6 -0
  196. package/src/cli/commands/report.ts +27 -0
  197. package/src/cli/commands/research.ts +53 -0
  198. package/src/cli/commands/reset.ts +89 -0
  199. package/src/cli/commands/restart.ts +5 -0
  200. package/src/cli/commands/results.ts +31 -0
  201. package/src/cli/commands/resume.ts +5 -0
  202. package/src/cli/commands/review.ts +24 -0
  203. package/src/cli/commands/roadmap.ts +21 -0
  204. package/src/cli/commands/role.ts +34 -0
  205. package/src/cli/commands/roles.ts +30 -0
  206. package/src/cli/commands/room.ts +14 -0
  207. package/src/cli/commands/roster.ts +48 -0
  208. package/src/cli/commands/route.ts +9 -0
  209. package/src/cli/commands/say.ts +21 -0
  210. package/src/cli/commands/schedule.ts +17 -0
  211. package/src/cli/commands/sdlc.ts +321 -0
  212. package/src/cli/commands/settings.ts +148 -0
  213. package/src/cli/commands/setup.ts +89 -0
  214. package/src/cli/commands/shared-refusals.ts +25 -0
  215. package/src/cli/commands/smoke.ts +44 -0
  216. package/src/cli/commands/source.ts +64 -0
  217. package/src/cli/commands/specs.ts +13 -0
  218. package/src/cli/commands/status.ts +28 -0
  219. package/src/cli/commands/stop.ts +17 -0
  220. package/src/cli/commands/structure.ts +60 -0
  221. package/src/cli/commands/study.ts +39 -0
  222. package/src/cli/commands/tail.ts +19 -0
  223. package/src/cli/commands/task.ts +114 -0
  224. package/src/cli/commands/title.ts +17 -0
  225. package/src/cli/commands/turns.ts +10 -0
  226. package/src/cli/commands/ui.ts +47 -0
  227. package/src/cli/commands/undo.ts +77 -0
  228. package/src/cli/commands/up.ts +39 -0
  229. package/src/cli/commands/upgrade.ts +5 -0
  230. package/src/cli/commands/usage.ts +33 -0
  231. package/src/cli/commands/version.ts +5 -0
  232. package/src/cli/commands/watch.ts +30 -0
  233. package/src/cli/commands/worktrees.ts +31 -0
  234. package/src/cli/conductor-recovery.ts +1 -1
  235. package/src/cli/console-state.ts +5 -138
  236. package/src/cli/console-versions.ts +1 -1
  237. package/src/cli/facts-hook.ts +11 -4
  238. package/src/cli/help.ts +44 -20
  239. package/src/cli/identity.ts +27 -4
  240. package/src/cli/init-prompt.ts +1 -1
  241. package/src/cli/init-settings.ts +4 -35
  242. package/src/cli/init.ts +1 -1
  243. package/src/cli/json-text-spans.ts +57 -0
  244. package/src/cli/launch-check.ts +156 -0
  245. package/src/cli/launch.ts +19 -70
  246. package/src/cli/light-dispatch.ts +29 -0
  247. package/src/cli/main.js +8 -1
  248. package/src/cli/main.ts +257 -2799
  249. package/src/cli/memory.ts +1 -1
  250. package/src/cli/orca-probe.ts +119 -0
  251. package/src/cli/output.ts +45 -3
  252. package/src/cli/preview.ts +11 -6
  253. package/src/cli/recovery-launch.ts +1 -1
  254. package/src/cli/recovery-version-preflight.ts +28 -9
  255. package/src/cli/replace-process.ts +22 -0
  256. package/src/cli/report-layout.ts +142 -0
  257. package/src/cli/roadmap-usage.ts +16 -0
  258. package/src/cli/roadmap.ts +3 -16
  259. package/src/cli/sdlc-doctor.ts +27 -0
  260. package/src/cli/sdlc-output.ts +55 -1
  261. package/src/cli/setup-homes.ts +2 -2
  262. package/src/cli/start-agents-run.ts +85 -7
  263. package/src/cli/start-check.ts +28 -0
  264. package/src/cli/statusline-tee.ts +25 -4
  265. package/src/cli/terminal-recovery.ts +53 -10
  266. package/src/cli/upgrade-interactive.ts +1 -0
  267. package/src/cli/upgrade-runtime.ts +12 -1
  268. package/src/cli/upgrade.ts +4 -15
  269. package/src/cli/warn-line.ts +1 -1
  270. package/src/hub/accounts.ts +148 -0
  271. package/src/hub/addons.ts +20 -0
  272. package/src/hub/agent-drift.ts +2 -1
  273. package/src/hub/budget-projection.ts +39 -7
  274. package/src/hub/budget.ts +231 -16
  275. package/src/hub/channel-project.ts +3 -3
  276. package/src/hub/ci-watch.ts +311 -79
  277. package/src/hub/conductor-peer.ts +24 -0
  278. package/src/hub/conductor.ts +2 -21
  279. package/src/hub/config-apply.ts +25 -14
  280. package/src/hub/config-edit.ts +1 -1
  281. package/src/hub/config-tier.ts +2 -0
  282. package/src/hub/config.ts +535 -0
  283. package/src/hub/control-client.ts +49 -1
  284. package/src/hub/daemon.ts +492 -569
  285. package/src/hub/delivery-public.ts +11 -0
  286. package/src/hub/events.ts +3 -0
  287. package/src/hub/home-tag.ts +12 -0
  288. package/src/hub/host.ts +217 -0
  289. package/src/hub/hub-check.ts +125 -0
  290. package/src/hub/hub-tools.ts +2 -1
  291. package/src/hub/instance-budget.ts +2 -2
  292. package/src/hub/instance-config.ts +15 -126
  293. package/src/hub/instances.ts +22 -6
  294. package/src/hub/instruction-receipt.ts +2 -2
  295. package/src/hub/kimi-usage.ts +38 -11
  296. package/src/hub/lifecycle.ts +86 -4
  297. package/src/hub/mcp-bridge-core.ts +98 -0
  298. package/src/hub/mcp-channel-push.ts +20 -0
  299. package/src/hub/mcp-endpoint-serve.ts +178 -0
  300. package/src/hub/mcp-endpoint.ts +226 -0
  301. package/src/hub/mcp-tool-call.ts +181 -0
  302. package/src/hub/operational-settings.ts +2 -0
  303. package/src/hub/orca-env.ts +6 -0
  304. package/src/hub/orca-state.ts +84 -0
  305. package/src/hub/path-policy.ts +1 -1
  306. package/src/hub/peers.ts +5 -1
  307. package/src/hub/permission-mode.ts +5 -41
  308. package/src/hub/permission-paths.ts +41 -0
  309. package/src/hub/project.ts +20 -0
  310. package/src/hub/protocol-window.ts +58 -0
  311. package/src/hub/quota-origin.ts +20 -0
  312. package/src/hub/recovery-policy.ts +1 -1
  313. package/src/hub/registry.ts +36 -2
  314. package/src/hub/releases-inventory.ts +198 -0
  315. package/src/hub/report.ts +1 -1
  316. package/src/hub/research.ts +1 -1
  317. package/src/hub/review-brief.ts +47 -2
  318. package/src/hub/roster.ts +6 -3
  319. package/src/hub/routing.ts +9 -2
  320. package/src/hub/runtime-capture-prune.ts +25 -3
  321. package/src/hub/runtime-prune-health.ts +8 -1
  322. package/src/hub/sdlc-check.ts +205 -0
  323. package/src/hub/sdlc-release-authorization.ts +42 -21
  324. package/src/hub/sdlc-release-diagnostics.ts +5 -0
  325. package/src/hub/sdlc-release-policy.ts +21 -7
  326. package/src/hub/sdlc-release.ts +80 -20
  327. package/src/hub/sdlc-sync.ts +146 -0
  328. package/src/hub/sdlc.ts +38 -5
  329. package/src/hub/settings.ts +7 -4
  330. package/src/hub/start-agents.ts +1 -1
  331. package/src/hub/start-mode.ts +11 -4
  332. package/src/hub/structure-budget.ts +131 -0
  333. package/src/hub/structure-scan.ts +149 -0
  334. package/src/hub/tasks-experiment.ts +455 -0
  335. package/src/hub/tasks-guidance.ts +606 -0
  336. package/src/hub/tasks-roadmap-plan.ts +419 -0
  337. package/src/hub/tasks-roadmap.ts +491 -0
  338. package/src/hub/tasks-study.ts +661 -0
  339. package/src/hub/tasks-survey.ts +192 -0
  340. package/src/hub/tasks.ts +457 -2584
  341. package/src/hub/terminal-open.ts +5 -3
  342. package/src/hub/tooling.ts +3 -19
  343. package/src/hub/usage-rollup.ts +9 -3
  344. package/src/local/tools.ts +5 -0
  345. package/src/ui/index.html +1 -1
  346. package/src/ui/needs.ts +17 -5
  347. package/src/ui/peer-palette.ts +2 -4
  348. package/src/ui/plugin.ts +1 -1
  349. package/templates/presets/agents.json +60 -0
  350. package/templates/presets/confirmation-matrix.json +8 -8
package/src/cli/memory.ts CHANGED
@@ -24,7 +24,7 @@ import { memoryUsage, goalUsage, rawMemoryCommand, rawGoalCommand } from "@staix
24
24
  const AHUB_NAMES = { memory: "ahub memory", goal: "ahub goal" };
25
25
  import { mentionsPrivatePath, promotionScreen, withoutPii } from "../hub/memory-policy.ts";
26
26
  import { currentRouting, detectSignals } from "../hub/routing.ts";
27
- import { loadConfig } from "../hub/daemon.ts";
27
+ import { loadConfig } from "../hub/config.ts";
28
28
  import { bindProfileMemory, memoryProjectFor, memoryProjectForStore, openProfileMemory, MemoryProfileBinding, MEMORY_PROFILE_UNAVAILABLE, MEMORY_SPLIT_INCOMPLETE, type MemoryProfileReceipt, type ProfileMemoryOptions } from "../hub/memory-profile.ts";
29
29
  import { createMemorySyncPolicy, inspectDeclinedMemoryRows, projectMemorySyncText } from "../hub/memory-sync-policy.ts";
30
30
 
@@ -0,0 +1,119 @@
1
+ import { COMPAT } from "../adapters/compat.ts";
2
+
3
+ /**
4
+ * #1808 T4: a read-only check of the Orca CLI answers the upgrade recovery depends on (`src/cli/terminal-recovery.ts`, `src/cli/upgrade-runtime.ts`).
5
+ * It runs `orca --version`, `orca terminal list --json` and `orca worktree list --json` and compares field NAMES and types only: a handle, a path or an id never
6
+ * appears in a result, a message or a log. It changes nothing in Orca and decides nothing by itself: a caller turns a shape problem into a doctor row or a plan blocker.
7
+ * A command that failed, or an answer that is not Orca's `ok: true` JSON, is `unreadable`, never a shape problem: the recovery's own Orca calls report that.
8
+ */
9
+ interface OrcaProbeResult {
10
+ /** `orca --version` as plain semver, or undefined when it could not be read. */
11
+ version?: string;
12
+ /** The version is newer than the last one in `COMPAT["orca-cli"].verified`. Never a refusal. */
13
+ newer: boolean;
14
+ /** Each names a command and a missing or mistyped field. Empty when every answered shape is what the recovery reads. */
15
+ problems: string[];
16
+ /** Commands that did not answer with Orca's JSON; they are not shape problems. */
17
+ unreadable: string[];
18
+ }
19
+ type OrcaProbeRunner = (argv: string[]) => Promise<{ code: number | null | undefined; stdout: string | undefined }>;
20
+
21
+ const MAX_ROWS = 2000;
22
+ const plain = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
23
+ const text = (value: unknown): boolean => typeof value === "string" && value.length > 0;
24
+ const triple = (version: string): number[] | undefined => /^(\d+)\.(\d+)\.(\d+)$/.exec(version)?.slice(1).map(Number);
25
+
26
+ /** The newest version a receipt covers. */
27
+ export const orcaLastChecked = (): string => COMPAT["orca-cli"].verified.reduce((best, version) => {
28
+ const a = triple(version), b = triple(best);
29
+ return a && b && (a[0]! - b[0]! || a[1]! - b[1]! || a[2]! - b[2]!) > 0 ? version : best;
30
+ });
31
+
32
+ /** Whether `version` is newer than the last Orca version a receipt checked. An unreadable or non-semver one is never newer. */
33
+ function orcaVersionIsNewer(version: string | undefined): boolean {
34
+ const seen = version === undefined ? undefined : triple(version), known = triple(orcaLastChecked());
35
+ return !!seen && !!known && (seen[0]! - known[0]! || seen[1]! - known[1]! || seen[2]! - known[2]!) > 0;
36
+ }
37
+
38
+ /** `answer` is a parsed `--json` answer; undefined means the command was not read, and nothing is checked for it. */
39
+ function rowProblems(command: string, list: unknown, names: readonly string[], listKeys: readonly string[], rowFields: readonly (readonly [string, ...string[]])[], listRequired: boolean): string[] {
40
+ if (!plain(list) || list.ok !== true) return [];
41
+ const result = plain(list.result) ? list.result : {};
42
+ const key = listKeys.find(name => Array.isArray(result[name]));
43
+ // ponytail: `worktree list` is read by the start path only, and fakes of it in older tests answer with another list, so a missing list is a problem for `terminal list` alone; a row field is checked on both.
44
+ if (key === undefined) return listRequired ? [`orca ${command}: the answer has no ${names.join(" or ")} list`] : [];
45
+ const rows = (result[key] as unknown[]).slice(0, MAX_ROWS);
46
+ const problems: string[] = [];
47
+ for (const alternatives of rowFields) {
48
+ const missing = rows.filter(row => !plain(row) || !alternatives.some(name => text(row[name]))).length;
49
+ if (missing) problems.push(`orca ${command}: ${alternatives.length === 1 ? `field ${alternatives[0]}` : `field ${alternatives.join(" or ")}`} is missing or not text on ${missing} of ${rows.length} rows`);
50
+ }
51
+ return problems;
52
+ }
53
+
54
+ /**
55
+ * The fields the recovery reads. `terminal list`: the handle, incarnation and worktree ids it binds a terminal to, and the worktree path it matches (`worktreePath`,
56
+ * else `projectRoot`). `worktree list`: the id and path it matches a project root with. A field that is optional for the recovery (`agentIdentity`, `orphaned`) is not checked.
57
+ * An empty list has no row to check and is not a problem.
58
+ */
59
+ function orcaShapeProblems(terminalList: unknown, worktreeList: unknown): string[] {
60
+ return [
61
+ ...rowProblems("terminal list --json", terminalList, ["terminals", "items"], ["terminals", "items"], [["handle"], ["incarnationId"], ["worktreeId"], ["worktreePath", "projectRoot"]], true),
62
+ ...rowProblems("worktree list --json", worktreeList, ["worktrees"], ["worktrees"], [["id"], ["path"]], false),
63
+ ];
64
+ }
65
+
66
+ const parsed = (stdout: string | undefined): unknown => { try { return stdout === undefined ? undefined : JSON.parse(stdout); } catch { return undefined; } };
67
+
68
+ /** One probe over a runner the caller supplies (a child process, or the upgrade's injected command port). Never throws. */
69
+ export async function readOrcaProbe(run: OrcaProbeRunner): Promise<OrcaProbeResult> {
70
+ const answer = async (argv: string[]): Promise<{ ok: boolean; stdout: string }> => {
71
+ try { const result = await run(argv); return { ok: result.code === 0 && typeof result.stdout === "string", stdout: result.stdout ?? "" }; }
72
+ catch { return { ok: false, stdout: "" }; }
73
+ };
74
+ const unreadable: string[] = [];
75
+ const versionAnswer = await answer(["--version"]);
76
+ const rawVersion = versionAnswer.ok ? versionAnswer.stdout.trim().split("\n")[0]!.trim() : "";
77
+ const version = triple(rawVersion) ? rawVersion : undefined;
78
+ if (version === undefined) unreadable.push("orca --version");
79
+ const read = async (argv: string[]): Promise<unknown> => {
80
+ const result = await answer(argv), value = result.ok ? parsed(result.stdout) : undefined;
81
+ if (!plain(value) || value.ok !== true) { unreadable.push(`orca ${argv.slice(0, 2).join(" ")} --json`); return undefined; }
82
+ return value;
83
+ };
84
+ const terminals = await read(["terminal", "list", "--json"]);
85
+ const worktrees = await read(["worktree", "list", "--json"]);
86
+ return { ...(version === undefined ? {} : { version }), newer: orcaVersionIsNewer(version), problems: orcaShapeProblems(terminals, worktrees), unreadable };
87
+ }
88
+
89
+ const PROBE_OUTPUT_CAP = 4 * 1024 * 1024;
90
+ /** A runner over one Orca executable with a deadline and an output cap, for `ahub doctor`. The upgrade preflight passes its own command port instead. */
91
+ export function orcaProbeRunner(executable: string, timeoutMs = 5_000): OrcaProbeRunner {
92
+ return async argv => {
93
+ const child = Bun.spawn([executable, ...argv], { stdout: "pipe", stderr: "ignore", stdin: "ignore", timeout: timeoutMs, killSignal: "SIGKILL" });
94
+ const reader = child.stdout.getReader();
95
+ const chunks: Uint8Array[] = [];
96
+ let total = 0, overflow = false;
97
+ try {
98
+ for (;;) {
99
+ const { done, value } = await reader.read();
100
+ if (done) break;
101
+ total += value.byteLength;
102
+ if (total > PROBE_OUTPUT_CAP) { overflow = true; child.kill("SIGKILL"); break; }
103
+ chunks.push(value);
104
+ }
105
+ } catch { /* a failed read ends the probe with what was counted */ }
106
+ const code = await child.exited;
107
+ return { code: overflow ? 1 : code, stdout: overflow ? undefined : Buffer.concat(chunks).toString("utf8") };
108
+ };
109
+ }
110
+
111
+ /** The `ahub doctor` row for an Orca that is installed: failed (a field the recovery reads is missing), a note (newer version, or an answer that could not be read), or ok. */
112
+ export function orcaDoctorRow(result: OrcaProbeResult): { ok: boolean | undefined; name: string; detail: string } {
113
+ const seen = result.version ?? "version unreadable";
114
+ if (result.problems.length) return { ok: false, name: "orca cli", detail: `${seen}: ${result.problems.join("; ")}; the upgrade recovery would read these answers wrongly and blocks its Orca terminals until this is fixed (update ahub or Orca)` };
115
+ const last = orcaLastChecked();
116
+ if (result.newer) return { ok: undefined, name: "orca cli", detail: `${seen} is newer than ${last}, the last version checked; the commands the recovery reads still have the fields it needs` };
117
+ if (result.unreadable.length) return { ok: undefined, name: "orca cli", detail: `${seen}: could not read ${result.unreadable.join(", ")} (is Orca running?); nothing was changed` };
118
+ return { ok: true, name: "orca cli", detail: `${seen}: the commands the recovery reads have the fields it needs` };
119
+ }
package/src/cli/output.ts CHANGED
@@ -1,10 +1,12 @@
1
+ import type { NeedItem } from "../ui/needs.ts";
2
+ import { attentionCommand } from "./attention.ts";
1
3
  import type { ReviewGate, ReviewUnknownQuota } from "../hub/review-budget.ts";
2
4
  import { projectionText } from "../hub/budget-projection.ts";
3
5
  import { quotaAccountReading } from "../hub/quota-account.ts";
4
6
  import { projectModelStatus } from "./model.ts";
5
7
  import type { RuntimeModelStatus } from "../hub/model-overrides.ts";
6
8
  import type { QueueBackpressureStatus } from "../hub/queue-backpressure.ts";
7
- import { definitionOf } from "../adapters/registry.ts";
9
+ import { builtinDeclarationOf as definitionOf } from "../adapters/declaration-catalog.ts";
8
10
  import { windowKind } from "../hub/window-kind.ts";
9
11
  import { boardColumns, type BoardPeerInput } from "../ui/task-board.ts";
10
12
  import { peerStyle } from "../ui/peer-palette.ts";
@@ -19,7 +21,15 @@ import type { SpecsStatus } from "../hub/specs-task.ts";
19
21
  import { queueResolveChoices, queueResolveCommand } from "../hub/person-command.ts";
20
22
 
21
23
  export interface DoctorCheck { section: "Tools" | "Hub" | "Config" | "Models" | "Memory"; level: "ok" | "warn" | "fail" | "unknown"; name: string; detail: string }
24
+
22
25
  export interface StatusOutput {
26
+ attentionItems?: readonly NeedItem[];
27
+ /** #1807: a new hub reports its startup-bound range and whether settings reach below its floor. */
28
+ protocolMin?: number;
29
+ protocolMax?: number;
30
+ bridgeProtocolFloorLimited?: boolean;
31
+ /** #1798: the daemon's one hub check; every surface renders it and none recomputes it. */
32
+ hubCheck?: import("../hub/hub-check.ts").HubCheck;
23
33
  runtimeModels?: RuntimeModelStatus[];
24
34
  runtimeModelsUnavailable?: boolean;
25
35
  roomsUnavailable?: unknown;
@@ -265,6 +275,11 @@ function contextText(p: any, now: number): string {
265
275
  if (!c) return "unknown";
266
276
  return `${c.used === null || c.used === undefined ? "unknown" : `${Math.round(c.used * 100)}%`}${c.freshness === "stale" ? " stale" : ""}${typeof c.measuredAt === "number" ? ` ${relative(c.measuredAt, now)}` : ""}${c.source ? ` ${c.source}` : ""}`;
267
277
  }
278
+ function bridgeProtocolStatus(data: StatusOutput): string | undefined {
279
+ const { bridgeProtocolFloorLimited, protocolMin, protocolMax } = data;
280
+ if (typeof bridgeProtocolFloorLimited !== "boolean" || !Number.isSafeInteger(protocolMin) || !Number.isSafeInteger(protocolMax)) return;
281
+ return `${protocolMin} to ${protocolMax}${bridgeProtocolFloorLimited ? ` (settings stop at the implemented floor ${protocolMin})` : ""}`;
282
+ }
268
283
  export function renderStatus(data: StatusOutput, columns?: number, now = Date.now(), full = false, ascii = false): Span[][] {
269
284
  if (data.roleInfo) data = { ...data, peers: Object.fromEntries(Object.entries(data.peers).map(([peer, value]) => [peer, { ...value, ...data.roleInfo?.[peer] }])) };
270
285
  // #1654 T3: the shared header, then a section mark per group. Every detail line below keeps its text, so a search for one still finds it.
@@ -272,6 +287,8 @@ export function renderStatus(data: StatusOutput, columns?: number, now = Date.no
272
287
  const mark = (name: string, count?: string) => { out.push(...(out.length && out.at(-1)!.length ? [[]] : []), ...new LayoutReport(columns, ascii).section(name, count).lines()); };
273
288
  const hubStart = out.length; // the Hub section opens here only if a row below lands in it
274
289
  if (data.cwd) out.push(...detail("project", data.cwd, columns));
290
+ const bridgeProtocol = bridgeProtocolStatus(data);
291
+ if (bridgeProtocol) out.push(...detail("bridge protocols", bridgeProtocol, columns));
275
292
  if (data.runtimeModelsUnavailable === true) out.push(...lines("Runtime models unavailable: could not read a bounded model catalog; run ahub model list for the cause. For a known peer, use ahub model set <peer> <model> or ahub model clear <peer>; repair storage or reduce the retained peer catalog as indicated before listing again.", columns, "attention"));
276
293
  else if (Array.isArray(data.runtimeModels)) out.push(...renderRuntimeModels(data.runtimeModels.map(projectModelStatus).filter((row): row is RuntimeModelStatus => row !== null), columns));
277
294
  const timing = data.controlWriteTiming;
@@ -391,7 +408,9 @@ export function renderStatus(data: StatusOutput, columns?: number, now = Date.no
391
408
  if (typeof p.reviewerUnavailable === "string" && p.reviewerUnavailable) out.push(...detail("reviewer", flat(p.reviewerUnavailable), columns, "failure")); // #722: the cause class, never a path
392
409
  if (p.ownerIsolationNote) out.push(...detail("owner isolation", p.ownerIsolationNote, columns, "attention"));
393
410
  if (p.permissionNote) out.push(...detail("permission", p.permissionNote, columns, "muted"));
411
+ if (typeof p.preset?.id === "string" && (p.preset.status === "verified" || p.preset.status === "untested")) out.push(...detail("preset", `${p.preset.id} (${p.preset.status})`, columns, p.preset.status === "verified" ? "muted" : "attention")); // #1809
394
412
  if (typeof p.statusNotice?.message === "string" && p.statusNotice.message) out.push(...detail("status notice", p.statusNotice.message, columns, "attention"));
413
+ if (p.refusedHello && typeof p.refusedHello.at === "number") out.push(...detail("refused hello", `${refusedHelloText(p.refusedHello)}; the owned launch is serving, so ${id} is not detached`, columns, "attention")); // #1795
395
414
  if (typeof p.detached?.cause === "string" && p.detached.cause) out.push(...detail("detached", `${p.detached.cause}${typeof p.detached.command === "string" && p.detached.command ? `; relaunch it with ${p.detached.command}` : ""}`, columns, "attention"));
396
415
  if (p.requestedModel && p.servedBy && p.requestedModel !== p.servedBy) out.push(...detail("requested model", p.requestedModel, columns));
397
416
  if (p.reviewScope === "code" || p.reviewScope === "full") out.push(...detail("review scope", p.reviewScope === "code" ? "code only (cannot run tests or read CI; the merger gates on exact-head CI)" : "full", columns, "muted")); // #852
@@ -453,6 +472,12 @@ export function statusAttention(data: StatusOutput, now = Date.now()): Attention
453
472
  for (const warning of data.isolatedChecks?.orphans ?? []) add("warn", `isolated check: ${warning}`);
454
473
  for (const id of data.isolatedChecks?.unknownReceipts ?? []) add("warn", `check receipt ${id}: unknown; receipt storage unavailable`);
455
474
  if (data.isolatedChecks?.maintenanceUnavailable) add("warn", "check maintenance unavailable; saved run outcomes are unchanged");
475
+ for (const warning of data.attentionItems ?? []) {
476
+ if (warning.kind !== "budget" || warning.level !== "watch" || typeof warning.peer !== "string"
477
+ || !/^[a-z0-9][a-z0-9-]*$/.test(warning.peer) || typeof warning.id !== "string"
478
+ || !["5h", "week", "tokens"].includes(warning.id) || typeof warning.until !== "number" || warning.until < now) continue;
479
+ add("warn", `${warning.peer} ${warning.id} quota is projected to run out ${relative(warning.until, now)}`, attentionCommand(warning));
480
+ }
456
481
  for (const [id, p] of Object.entries(data.peers)) {
457
482
  for (const session of Array.isArray(p.standbySessions) ? p.standbySessions : []) {
458
483
  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;
@@ -465,13 +490,19 @@ export function statusAttention(data: StatusOutput, now = Date.now()): Attention
465
490
  const budgetPause = data.budget?.[id]?.paused;
466
491
  const text = budgetPause ? `budget: ${budgetPause.reason ?? "threshold"}${typeof budgetPause.resetsAt === "number" ? `; resets ${relative(budgetPause.resetsAt, now)}` : "; reset unknown"}`
467
492
  : typeof p.paused === "object" ? `${p.paused.by ?? "paused"}${p.paused.reason ? `: ${p.paused.reason}` : ""}` : flat(p.paused);
468
- add("warn", `${id} is paused (${text})`, budgetPause ? "ahub budget" : `ahub resume ${id}`);
493
+ add("warn", `${id} is paused (${text})`, budgetPause ? attentionCommand({ kind: "budget", level: "watch", peer: id }) : `ahub resume ${id}`);
469
494
  }
470
495
  if (typeof p.reviewerUnavailable === "string" && p.reviewerUnavailable) add("fail", `${id} reviewer unavailable: ${flat(p.reviewerUnavailable)}`);
471
496
  if (p.ownerIsolationNote) add("warn", `${id} owner isolation: ${p.ownerIsolationNote}`);
472
497
  if (typeof p.statusNotice?.message === "string" && p.statusNotice.message) add("warn", `${id}: ${p.statusNotice.message}`);
473
498
  // #1668: the hub refused a hub-tools hello because a server the hub did not start is serving that peer's socket; the hub already knows the launch that ends it.
474
- if (typeof p.detached?.cause === "string" && p.detached.cause) add("warn", `${id} is detached: ${p.detached.cause}`, typeof p.detached.command === "string" ? p.detached.command : undefined);
499
+ // #1795: a stray process, not a detached peer. #1798: a read-only next step, the process row when its pid is known.
500
+ if (p.refusedHello && typeof p.refusedHello.at === "number") add("warn", `${id}: ${refusedHelloText(p.refusedHello)}`, typeof p.refusedHello.pid === "number" && Number.isSafeInteger(p.refusedHello.pid) ? `ps -p ${p.refusedHello.pid} -o pid,command` : "ahub status");
501
+ const hubPeer = data.hubCheck?.peers?.find((row: { id: string }) => row.id === id);
502
+ const queuedText = hubPeer && Number(hubPeer.queued) > 0 ? `; ${hubPeer.queued} queued` : "";
503
+ if (typeof p.detached?.cause === "string" && p.detached.cause) add("warn", `${id} is detached: ${p.detached.cause}${queuedText}`, typeof p.detached.command === "string" ? p.detached.command : undefined);
504
+ // #1798: a link weaker than expected is Attention, with its evidence value, the queued count and the full next step (detached has its own item above).
505
+ else if (hubPeer && hubPeer.ok === false && hubPeer.observed !== "pending" && hubPeer.observed !== "detached") add("warn", `${id}: ${flat(String(hubPeer.observed))} link (evidence: ${flat(String(hubPeer.evidence))})${queuedText}`, typeof hubPeer.nextStep === "string" ? hubPeer.nextStep : undefined);
475
506
  if (typeof p.importantWaitingSince === "number" && p.importantWaitingNote) add("warn", `${id}: ${String(p.importantWaitingNote)}`, `ahub queue list --peer ${id}`);
476
507
  const actionPolicy = data.actionPolicyInfo?.[id];
477
508
  if (actionPolicy?.note && !actionPolicy.enforceable) add("warn", `${id} action policy: ${actionPolicy.note}`);
@@ -496,6 +527,8 @@ export function renderStatusDefault(data: StatusOutput, columns?: number, now =
496
527
  if (!attention.length) report.bullet("ok", "nothing needs attention");
497
528
  for (const item of attention) { report.bullet(item.marker, item.text); if (item.next) report.next(item.next); }
498
529
  const hub: [string, unknown][] = [["version", data.version ?? "unknown"], ["pid", data.pid ?? "unknown"], ["control", `127.0.0.1:${data.controlPort ?? "unknown"}`], ["project", data.cwd ?? ""]];
530
+ const bridgeProtocol = bridgeProtocolStatus(data);
531
+ if (bridgeProtocol) hub.push(["bridge protocols", bridgeProtocol]);
499
532
  if (data.planner) hub.push(["planner", `${data.planner.peers?.join(", ") || "nobody"} (${data.planner.source ?? "unknown"})`]);
500
533
  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"}`]);
501
534
  const specs = data.specs;
@@ -637,6 +670,11 @@ export function renderBudget(data: BudgetOutput, columns?: number, now = Date.no
637
670
  // 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.
638
671
  for (const note of data.peers ?? []) out.push(...detail(note.peer, note.note, columns, peerTone(note.peer)));
639
672
  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"));
673
+ for (const [peer, b] of Object.entries(data.budget)) {
674
+ if (b.renewable !== true || !/^[a-z0-9][a-z0-9-]*$/.test(peer) || !(b.paused || b.warnings?.length)) continue;
675
+ out.push(...detail("Same account after resetting its quota", `ahub budget renew ${peer} --reset`, columns));
676
+ out.push(...detail("After switching accounts", `ahub budget renew ${peer} --switched`, columns));
677
+ }
640
678
  for (const [peer, b] of Object.entries(data.budget)) {
641
679
  const info = b.paused ? quotaAccountReading(b.accountUsage) : undefined;
642
680
  if (!info) continue;
@@ -808,6 +846,10 @@ function fields(value: unknown, columns: number | undefined, now: number, prefix
808
846
  visit(value, prefix, prefix);
809
847
  return rows(["FIELD", "VALUE"], leaves, columns);
810
848
  }
849
+ /** #1795: what a refused hub-tools hello names. The pid and command are display text from the hello and one bounded process read. */
850
+ function refusedHelloText(hello: { at: number; pid?: number; command?: string }): string {
851
+ return `a process that is not this peer's owned launch was refused${typeof hello.pid === "number" ? ` (pid ${hello.pid}${hello.command ? `: ${flat(hello.command)}` : ""})` : ""}`;
852
+ }
811
853
  export function renderQueueShow(delivery: any, columns?: number, now = Date.now(), project?: string): Span[][] {
812
854
  // #1399: the resolve line runs as printed: id, revision, a suggested action, a prefilled reason and the project that hosts the hub.
813
855
  const messages: any[] = Array.isArray(delivery?.messages) ? delivery.messages : [];
@@ -1,20 +1,25 @@
1
- import { definitionOf, builtinPreviewOf } from "../adapters/registry.ts";
2
- import { loadConfig } from "../hub/daemon.ts";
1
+ import { lightNativePreview } from "../adapters/definitions/native-light-preview.ts";
2
+ import { builtinDeclarationOf } from "../adapters/declaration-catalog.ts";
3
+ import { loadConfig } from "../hub/config.ts";
3
4
  import { childEnv } from "../hub/child-process.ts";
4
5
  import { startModeOf } from "../hub/start-mode.ts";
5
6
  import { instanceLaunchArguments, buildLaunch, buildKimiLaunch, buildKimiTuiLaunch, nativeLaunchEnv, claudeObservationHooks } from "./launch.ts";
6
7
  import { kimiMcpPlan } from "./kimi-mcp.ts";
7
- import { jcodeCommand, jcodeTuiCommand } from "../adapters/jcode.ts";
8
- import { qwenSessionId } from "../hub/crash.ts";
8
+ import { jcodeCommand, jcodeTuiCommand } from "../adapters/definitions/jcode-launch.ts";
9
+ import { qwenSessionId } from "../adapters/definitions/qwen-native.ts";
9
10
  import { relayModelIds } from "../models/relay.ts";
10
- import { buildPiLaunch } from "../pi/launch.ts";
11
+ const buildPiLaunch: typeof import("../pi/launch.ts").buildPiLaunch =
12
+ (...args) => (require("../pi/launch.ts") as typeof import("../pi/launch.ts")).buildPiLaunch(...args);
13
+
11
14
 
12
15
  /** Read-only builtin preview. Native redaction uses the same launch builders as actual startup. */
13
16
  export function launcherPreview(tool: string, raw: string[], cwd: string, stateDir: string, unattended: boolean, requestedInstance?: string) {
14
17
  const config = loadConfig(cwd);
15
18
  const selected = instanceLaunchArguments(tool, requestedInstance ? ["--as", requestedInstance, ...raw] : raw, config.instances);
16
19
  const args = selected.args.filter(arg => !["--print-command", "--dry-run", "--json"].includes(arg));
17
- const definition = definitionOf(tool), preview = builtinPreviewOf(tool);
20
+ const light = lightNativePreview(tool);
21
+ const runtime = light ? undefined : require("../adapters/registry.ts") as typeof import("../adapters/registry.ts");
22
+ const definition = light ? builtinDeclarationOf(tool) : runtime?.definitionOf(tool), preview = light ?? runtime?.builtinPreviewOf(tool);
18
23
  if (!definition || !preview) throw new Error("native preview definition unavailable");
19
24
  if (selected.instance && definition.start.explicitHeadlessMode) {
20
25
  const mode = args.indexOf("--mode");
@@ -4,7 +4,7 @@ import { format } from "node:util";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { looksSecret } from "@staix/agent-mem";
7
- import { loadConfig } from "../hub/daemon.ts";
7
+ import { loadConfig } from "../hub/config.ts";
8
8
  import { loadRouting, detectSignals } from "../hub/routing.ts";
9
9
  import { mentionsPrivatePath } from "../hub/memory-policy.ts";
10
10
  import { sanitize } from "../hub/envelope.ts";
@@ -68,10 +68,13 @@ export async function readRecoveryVersionPreflight(
68
68
  || gate.command !== undefined && !words(gate.command))) throw new Error("invalid recovery version preflight scope");
69
69
  const module = JSON.stringify(join(targetRoot, "src/adapters/compat.ts"));
70
70
  const env = withoutOrcaEnv(childEnv({ ...process.env, JCODE_NO_TELEMETRY: "1", JCODE_DISABLE_CLAUDE_MCP: "1", AGY_CLI_DISABLE_AUTO_UPDATE: "1" }));
71
+ // A changed authority or target is its own error: nothing below may catch it as a failed probe, and once seen it ends the whole preflight as unknown even if it changes back.
72
+ class AuthorityChanged extends Error {}
73
+ const still = () => { if (!ports.current()) throw new AuthorityChanged("recovery version preflight authority changed"); };
71
74
  const run = async (argv: string[], input?: string) => {
72
- if (!ports.current()) throw new Error("recovery version preflight authority changed");
75
+ still();
73
76
  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");
77
+ still();
75
78
  if (result.code !== 0 || typeof result.stdout !== "string" || Buffer.byteLength(result.stdout) > MAX_OUTPUT_BYTES) return undefined;
76
79
  return result.stdout;
77
80
  };
@@ -79,24 +82,40 @@ export async function readRecoveryVersionPreflight(
79
82
  for (const gate of gates) {
80
83
  let observation = unknown(gate);
81
84
  try {
85
+ observation = await (async (): Promise<RecoveryVersionObservation> => {
86
+ let observation = unknown(gate);
82
87
  // 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));`]);
88
+ 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, gate: p.gate } : null));`]);
84
89
  const policy: unknown = policyText === undefined ? undefined : JSON.parse(policyText);
85
- if (!plain(policy) || !words(policy.probe)) { results.push(observation); continue; }
90
+ if (!plain(policy) || !words(policy.probe)) return observation;
86
91
  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; }
92
+ // #1808: an `observe` entry never refuses, so a version probe that fails, times out or throws must not block a restore. Only the target's own policy says "observe";
93
+ // a missing gate (an older target), any other gate or an unreadable policy stays unknown. An authority change is never a probe failure: it is rethrown, and it is checked again right before an unreadable version is accepted and after every gate.
94
+ const watched = policy.gate === "observe";
95
+ const unreadable = (): RecoveryVersionObservation => (still(), { ...observation, state: "accepted", message: `${gate.peer}: target only watches this CLI and its version could not be read; nothing is refused` });
96
+ let native: string | undefined;
97
+ try { native = await run([executable!, ...prefix, ...policy.probe.slice(1)]); }
98
+ catch (error) { if (error instanceof AuthorityChanged) throw error; if (watched) return unreadable(); throw new Error("version probe failed"); }
99
+ if (native === undefined) return watched ? unreadable() : observation;
89
100
  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
101
  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)) {
102
+ // #1808: an `observe` entry never refuses, so an observed verdict (even one whose version could not be read) never blocks recovery.
103
+ if (plain(verdict) && verdict.ok === true && verdict.state === "observed") observation = { ...observation, state: "accepted",
104
+ ...(typeof verdict.version === "string" && verdict.version.length <= 64 && SEMVER.test(verdict.version) ? { version: verdict.version } : {}),
105
+ message: `${gate.peer}: target only watches this CLI; nothing is refused` };
106
+ else if (plain(verdict) && typeof verdict.version === "string" && verdict.version.length <= 64 && SEMVER.test(verdict.version)) {
92
107
  const version = verdict.version;
93
108
  if (verdict.ok === true && ["verified", "trusted", "in-line"].includes(String(verdict.state))) observation = { ...observation, state: "accepted", version,
94
109
  message: `${gate.peer}: target accepts installed version ${version}` };
95
110
  else if (verdict.ok === false && verdict.state === "refused") observation = { ...observation, state: "refused", version,
96
111
  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
112
  }
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.
113
+ return observation;
114
+ })();
115
+ } catch (error) {
116
+ // A failed policy/probe is unknown, never accepted or a leaked native exception. A changed authority or target invalidates every observation, earlier ones too.
117
+ if (error instanceof AuthorityChanged) return gates.map(unknown);
118
+ }
100
119
  if (!ports.current()) return gates.map(unknown);
101
120
  results.push(observation);
102
121
  }
@@ -0,0 +1,22 @@
1
+ import { accessSync, constants } from "node:fs";
2
+ import { resolve } from "node:path";
3
+
4
+ /** The absolute program spawn would run: execve never searches PATH. Undefined when the runtime has no execve or the program cannot be found and executed (the caller then spawns and reports the error as before). */
5
+ function replaceTarget(bin: string, env: NodeJS.ProcessEnv, cwd: string, hasExecve = typeof process.execve === "function"): string | undefined {
6
+ if (!hasExecve) return undefined;
7
+ const found = bin.includes("/") ? resolve(cwd, bin) : Bun.which(bin, { PATH: env.PATH ?? "", cwd }) ?? undefined;
8
+ if (!found) return undefined;
9
+ try { accessSync(found, constants.X_OK); return found; } catch { return undefined; }
10
+ }
11
+
12
+ /**
13
+ * #1778 T6a: the wrapper becomes the agent. The process at the wrapper's pid is then the agent, no ahub process stays resident, and the agent's exit status or terminating signal reaches the caller directly.
14
+ * Returns only when execve is not available for this program, so the caller takes its spawn path; a failed execve is reported through `fail`.
15
+ * The caller closes every hub handle before calling: execve keeps an inherited descriptor open, and the hub client is the one the wrapper holds.
16
+ */
17
+ export function replaceProcess(bin: string, argv: string[], env: NodeJS.ProcessEnv, cwd: string, fail: (message: string) => never, hasExecve?: boolean): void {
18
+ const target = replaceTarget(bin, env, cwd, hasExecve);
19
+ if (!target) return;
20
+ try { process.chdir(cwd); process.execve!(target, [bin, ...argv], env as Record<string, string>); }
21
+ catch (error) { fail(`cannot run ${bin}: ${error instanceof Error ? error.message : String(error)}`); }
22
+ }
@@ -0,0 +1,142 @@
1
+ import { Report as SharedReport, paint as sharedPaint, wrap as sharedWrap } from "@staix/cli-output";
2
+ import { PEER_PALETTE } from "../ui/peer-palette.ts";
3
+ import { sanitize } from "../hub/envelope.ts";
4
+ import { TONE_SGR, MARKERS, MARKER_COLUMN, cellWidth, markerCell, type MarkerName, type Role } from "./output-standard.ts";
5
+
6
+ /** Strip terminal controls before any daemon or child output reaches a terminal. Preserve printable Unicode. */
7
+ // Preserve the hub's control and header policy for non-Report output.
8
+ export function terminalText(value: unknown): string {
9
+ return sanitize(String(value ?? "")
10
+ .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|$)/g, "")
11
+ .replace(/\x1b[P_X^][\s\S]*?(?:\x1b\\|$)/g, "")
12
+ .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "")
13
+ .replace(/\x1b[^\n]?/g, "").replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, ""));
14
+ }
15
+ export type Tone = "info" | "strong" | "success" | "attention" | "failure" | "muted" | "peerClaude" | "peerCodex" | "taskKeyword" | "number" | "issueRef" | "taskRef";
16
+ /** A report span names a semantic role (CLI output standard v1, docs/design/cli-output.md) or, for the console, a tone; a role wins. */
17
+ export interface Span { text: string; tone?: Tone; role?: Role }
18
+ export const PALETTE: Readonly<Record<Tone, string>> = Object.freeze({
19
+ info: PEER_PALETTE.hub.ansi, strong: TONE_SGR.strong, success: PEER_PALETTE.local.ansi, attention: PEER_PALETTE.pi.ansi, failure: TONE_SGR.failure, muted: PEER_PALETTE.other.ansi,
20
+ peerClaude: PEER_PALETTE.claude.ansi, peerCodex: PEER_PALETTE.codex.ansi,
21
+ taskKeyword: PEER_PALETTE.kimi.ansi, number: TONE_SGR.number, issueRef: TONE_SGR.issueRef, taskRef: TONE_SGR.taskRef,
22
+ });
23
+ /** The console's tones onto roles. A tone that is not here names an identity (a peer, a task keyword, a reference), never a status. */
24
+ export const TONE_ROLE: Readonly<Partial<Record<Tone, Role>>> = Object.freeze({
25
+ info: "accent", strong: "header", success: "success", attention: "warning", failure: "error", muted: "hint", number: "value",
26
+ });
27
+ export function paint(line: Span[], color: boolean): string {
28
+ return sharedPaint(line.map(({ tone, ...span }) => ({ ...span, text: terminalText(span.text), ...(tone ? { style: tone } : {}) })), color, PALETTE);
29
+ }
30
+
31
+ /**
32
+ * The layout grammar of standard v1 as one builder, so every report has the same header, section, key/value row, bullet row, next step
33
+ * and summary line. Blank lines follow the standard: exactly one before each section, none after it, never two in a row, none at the
34
+ * end. Lines are Span arrays; `paint(line, color)` prints them. The builder never colors by itself: it names roles.
35
+ */
36
+ // Shared Report supplies matching primitives; layout uses shared wrapping with the legacy fallback below.
37
+ export class Report {
38
+ private readonly out: Span[][] = [];
39
+ /** `columns` undefined means no wrap width: standard v1 wraps on a pipe only when COLUMNS is set, so a script reading `ahub doctor | grep` gets whole lines. */
40
+ constructor(readonly columns: number | undefined = undefined, readonly ascii = false) {}
41
+ /** The text as lines at most `room` cells wide, or as one line per source line when there is no wrap width. */
42
+ private fit(text: string, room: number): string[] {
43
+ return this.columns === undefined ? terminalText(text).split("\n").map(line => line.replace(/\t/g, " ")) : wrap(text, Math.max(10, room), 0);
44
+ }
45
+ private push(line: Span[]) { this.out.push(line); }
46
+ /** ` <tool> <Report>` in `header`, then one line of context in `hint` on the same line. At most one per report. */
47
+ header(tool: string, name: string, context?: string): this {
48
+ this.out.push(...new SharedReport(this.columns, this.ascii).header(tool, name, context).lines());
49
+ return this;
50
+ }
51
+ /**
52
+ * #1654 AC3: the one header-fit rule. The header line does not wrap, so a name that fits the terminal stays in it and a longer
53
+ * one moves to a wrapped line under a short header. `context` follows the name after two spaces in `hint`; with `inline` it
54
+ * joins the name by one space (`Merge queue owner/repo`) and moves in `value`. A name too wide for any header keeps its first
55
+ * word there and repeats in full on the wrapped line. No wrap width means no moving.
56
+ */
57
+ titled(tool: string, name: string, context?: string, inline = false): this {
58
+ const fits = (text: string) => this.columns === undefined || cellWidth(` ${tool} ${text}`) <= this.columns;
59
+ const joined = !context ? name : inline ? `${name} ${context}` : `${name} ${context}`;
60
+ if (fits(joined)) return inline && context ? this.header(tool, joined) : this.header(tool, name, context || undefined);
61
+ if (context && fits(name)) return this.header(tool, name).note(context, inline ? "value" : "hint");
62
+ return this.header(tool, name.split(" ")[0]!).note(joined, "value");
63
+ }
64
+ /** One blank line, then `▸ <Name>` (ASCII `> <Name>`) in `section`, with an optional count in `hint`. */
65
+ section(name: string, count?: string): this {
66
+ if (this.out.length && this.out.at(-1)!.length) this.push([]);
67
+ this.out.push(...new SharedReport(this.columns, this.ascii).section(name, count).lines());
68
+ return this;
69
+ }
70
+ /**
71
+ * Key/value rows of one section: two-space indent, `Key:` padded to the widest key, two spaces, value. A key wider than 28 cells
72
+ * puts its value on the next line at a four-space indent. An empty value is `(unset)` in `hint`.
73
+ */
74
+ kv(rows: readonly (readonly [string, unknown])[], indent = 2, options: { colon?: boolean } = {}): this {
75
+ const suffix = options.colon === false ? "" : ":";
76
+ const keys = rows.map(([key]) => cellWidth(`${terminalText(key)}${suffix}`));
77
+ const pad = Math.max(0, ...keys.filter(width => width <= 28));
78
+ for (const [index, [key, raw]] of rows.entries()) {
79
+ const label = `${terminalText(key)}${suffix}`, text = terminalText(raw ?? "").trim();
80
+ const value = (line: string): Span => text ? { text: line, role: "value" } : { text: "(unset)", role: "hint" };
81
+ const lead = " ".repeat(indent);
82
+ // a terminal too narrow to leave 10 cells beside the label stacks the value under its key, like a key wider than 28
83
+ // stacked when fewer than 10 cells remain beside the label, or when the value's longest word does not fit there
84
+ const longest = Math.max(0, ...text.split(/\s+/).map(word => cellWidth(word)));
85
+ const narrow = keys[index]! <= 28 && this.columns !== undefined && (indent + pad + 2 + 10 > this.columns || longest > this.columns - indent - pad - 2 && longest <= this.columns - indent);
86
+ if (keys[index]! > 28 || narrow) {
87
+ // a terminal too narrow for the label column keeps the value at the key's own indent, so a long word is not broken by the hang
88
+ const hang = narrow ? 0 : 2;
89
+ this.push([{ text: `${lead}${label}`, role: "key" }]);
90
+ for (const line of text ? this.fit(text, (this.columns ?? 0) - indent - hang) : [""]) this.push([{ text: `${lead}${" ".repeat(hang)}` }, value(line)]);
91
+ continue;
92
+ }
93
+ const gap = " ".repeat(pad - keys[index]! + 2), room = (this.columns ?? 0) - indent - pad - 2;
94
+ const lines = text ? this.fit(text, room) : [""];
95
+ this.push([{ text: lead }, { text: label, role: "key" }, { text: gap }, value(lines[0]!)]);
96
+ for (const line of lines.slice(1)) this.push([{ text: " ".repeat(indent + pad + 2) }, value(line)]);
97
+ }
98
+ return this;
99
+ }
100
+ /** ` <marker> <text>`; a nested detail line uses four spaces. The text carries the state word, so meaning survives without color. */
101
+ bullet(name: MarkerName, text: string, nested = false): this {
102
+ const indent = nested ? " " : " ", lead = indent.length + MARKER_COLUMN + 1;
103
+ const lines = this.fit(text, (this.columns ?? 0) - lead);
104
+ this.push([{ text: indent }, { text: markerCell(name, this.ascii), role: MARKERS[name].role }, { text: " " }, { text: lines[0]! }]);
105
+ for (const line of lines.slice(1)) this.push([{ text: " ".repeat(lead) + line }]);
106
+ return this;
107
+ }
108
+ /** Lines another renderer built (a table), placed as they are. A section's blank line is still added by `section()`. */
109
+ append(lines: readonly Span[][]): this { for (const line of lines) this.push([...line]); return this; }
110
+ /** A free line in one role, indented two cells (a pointer to more detail, a note). */
111
+ note(text: string, role: Role = "hint"): this {
112
+ for (const line of this.fit(text, (this.columns ?? 0) - 2)) this.push([{ text: " " }, { text: line, role }]);
113
+ return this;
114
+ }
115
+ /** ` → <command>` in `accent`: complete and copyable, never shortened. */
116
+ next(command: string): this {
117
+ this.out.push(...new SharedReport(this.columns, this.ascii, { sanitize: terminalText, sanitizeFirst: true, wrapNext: false }).next(command).lines());
118
+ return this;
119
+ }
120
+ /** The last line of a check command: `✗ 2 failed ⚠ 3 warnings ✓ 18 ok`, zero counts omitted, unknowns as `? 2 unknown`. */
121
+ summary(counts: { failed?: number; warnings?: number; unknown?: number; ok?: number }): this {
122
+ const lines = new SharedReport(this.columns, this.ascii).summary(counts).lines();
123
+ if (lines.length) { if (this.out.length) this.push([]); this.out.push(...lines); }
124
+ return this;
125
+ }
126
+ lines(): Span[][] { return this.out.map(line => line.map(item => ({ ...item }))); }
127
+ /** The report as text: one painted string per line, no trailing blank line. */
128
+ render(color: boolean): string[] { return this.out.map(line => paint(line, color)); }
129
+ }
130
+
131
+ /**
132
+ * A source line keeps its indent and its continuations hang `hang` columns deeper, both capped at half the width, so
133
+ * below that cap wrapped untrusted text never starts where its source line, or a hub line at that indent, starts. Breaks fall
134
+ * at whitespace, which they drop; only a word longer than a whole line is split. A tab counts as one space.
135
+ * Lines come out sanitized: a width counts the `> ` that sanitize() puts before a line starting like a hub header.
136
+ */
137
+ export function wrap(value: unknown, columns: number, hang = 4): string[] {
138
+ // A bare chunk ending in "--- from" becomes a header marker when table padding follows it.
139
+ const quoteChunk = (chunk: string) => sanitize(chunk + " ").slice(0, -1);
140
+ // Code-point splitting keeps legacy output for every width, including the non-positive ones.
141
+ return sharedWrap(terminalText(value), columns, hang, quoteChunk, false, "codepoint");
142
+ }
@@ -0,0 +1,16 @@
1
+ const optionalFields = "[--horizon now|next|later] [--order <n>] [--target <date>|none] [--parent <id>|none]";
2
+ export const ROADMAP_FORMS = {
3
+ list: "[list] [--json]", show: "show <id> [--json]",
4
+ new: `new --title <text> --outcome <text> ${optionalFields}`,
5
+ edit: `edit <id> --revision <n> [--title <text>] [--outcome <text>] ${optionalFields}`,
6
+ link: "link <id> <spec|issue|task|release> <ref>", unlink: "unlink <id> <kind> <ref>",
7
+ order: "order <id> <n>", state: "state <id> <proposed|planned|active|done|dropped>",
8
+ unplaced: "unplaced [--repo <owner/name>] [--json]",
9
+ triage: "triage [--repo <owner/name>] [--list] [--json]",
10
+ decompose: "decompose <id> [--accept <part>] [--publish [--apply --confirm <fingerprint>]] [--json]",
11
+ accept: "accept <suggestion>", reject: "reject <suggestion>",
12
+ importGithub: "import-github [--repo <owner/name>] [--apply] [--json]",
13
+ check: "check [--json]", sync: "sync [--apply --confirm <fingerprint>] [--json]",
14
+ export: "export [--write | --issue <n> [--apply --confirm <fingerprint>]] [--json]",
15
+ } as const;
16
+ export const ROADMAP_USAGE = `usage: ${Object.values(ROADMAP_FORMS).map(form => `ahub roadmap ${form}`).join(" | ")}`;
@@ -1,22 +1,9 @@
1
1
  import { milestoneId, milestoneRevision, milestoneLinkRef, parseMilestoneInput, parseMilestonePatch, githubRepo, type MilestoneLinkKind } from "../hub/roadmap.ts";
2
2
  import { terminalText, wrap } from "./console-state.ts";
3
3
 
4
- const optionalFields = "[--horizon now|next|later] [--order <n>] [--target <date>|none] [--parent <id>|none]";
5
- export const ROADMAP_FORMS = {
6
- list: "[list] [--json]", show: "show <id> [--json]",
7
- new: `new --title <text> --outcome <text> ${optionalFields}`,
8
- edit: `edit <id> --revision <n> [--title <text>] [--outcome <text>] ${optionalFields}`,
9
- link: "link <id> <spec|issue|task|release> <ref>", unlink: "unlink <id> <kind> <ref>",
10
- order: "order <id> <n>", state: "state <id> <proposed|planned|active|done|dropped>",
11
- unplaced: "unplaced [--repo <owner/name>] [--json]",
12
- triage: "triage [--repo <owner/name>] [--list] [--json]",
13
- decompose: "decompose <id> [--accept <part>] [--publish [--apply --confirm <fingerprint>]] [--json]",
14
- accept: "accept <suggestion>", reject: "reject <suggestion>",
15
- importGithub: "import-github [--repo <owner/name>] [--apply] [--json]",
16
- check: "check [--json]", sync: "sync [--apply --confirm <fingerprint>] [--json]",
17
- export: "export [--write | --issue <n> [--apply --confirm <fingerprint>]] [--json]",
18
- } as const;
19
- export const ROADMAP_USAGE = `usage: ${Object.values(ROADMAP_FORMS).map(form => `ahub roadmap ${form}`).join(" | ")}`;
4
+ import { ROADMAP_USAGE } from "./roadmap-usage.ts";
5
+ export { ROADMAP_FORMS, ROADMAP_USAGE } from "./roadmap-usage.ts";
6
+
20
7
  export interface RoadmapArgs {
21
8
  op: "hub_roadmap_list" | "hub_roadmap_show" | "hub_roadmap_check" | "hub_roadmap_edit" | "hub_roadmap_unplaced" | "hub_roadmap_triage" | "hub_roadmap_decompose" | "roadmap_import_github" | "roadmap_sync" | "roadmap_sync_apply" | "roadmap_export" | "roadmap_export_apply";
22
9
  args: Record<string, unknown>;