@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
@@ -0,0 +1,70 @@
1
+ import { queueResolveArgsValid } from "../../hub/person-command.ts";
2
+ import { renderQueue, renderQueueShow } from "../output.ts";
3
+ import type { CommandContext } from "../command-context.ts";
4
+
5
+ export async function run(context: CommandContext) {
6
+ const { connect, cwd, outputArguments, outputOptions, printOutput, takeFlags, warn } = context;
7
+ const fail: CommandContext["fail"] = context.fail;
8
+ const options = outputOptions();
9
+ const [operation = "list", ...rest] = outputArguments();
10
+ const hub = await connect();
11
+ try {
12
+ if (operation === "list") {
13
+ const all = rest.includes("--all");
14
+ const { one, rest: flags } = takeFlags(rest.filter((word) => word !== "--all"), ["--peer"], []);
15
+ if (flags.length) fail("usage: ahub queue list [--peer <id>] [--all] [--json] [--full] [--color=auto|always|never]");
16
+ const result = await hub.request({ t: "queue", op: "list", ...(one["--peer"] ? { peer: one["--peer"] } : {}), ...(all ? { all: true } : {}) });
17
+ if (!result.ok) fail(result.error,result.refusalAudited===true,result.authorityRefused);
18
+ if (options.json) return console.log(JSON.stringify(result.deliveries, null, 2));
19
+ printOutput(renderQueue(result.deliveries, options.columns, Date.now()), options.color);
20
+ // #1096: rows a resolution already settled are history, hidden by default; say how many and how to see them, on stderr so a pipe of the table stays clean.
21
+ if (result.hiddenSettled) warn(`${result.hiddenSettled} settled deliver${result.hiddenSettled === 1 ? "y" : "ies"} hidden (already resolved); ahub queue list --all shows them`);
22
+ return;
23
+ }
24
+ if (operation === "discard") {
25
+ // #713: the person's bulk clear of one peer's queue. Without --yes it only says how many it would discard.
26
+ const yes = rest.includes("--yes");
27
+ const { one, rest: others } = takeFlags(rest.filter((word) => word !== "--yes"), ["--peer", "--reason", "--state"], []);
28
+ if (others.length || !one["--peer"] || (one["--state"] !== undefined && !["queued", "needs_review", "failed"].includes(one["--state"]))) fail("usage: ahub queue discard --peer <id> --reason <text> [--state queued|needs_review|failed] [--yes]; without --state it clears the peer's queued and unsettled failed deliveries");
29
+ if (yes && !one["--reason"]?.trim()) fail("ahub queue discard needs --reason <text> with --yes: it is recorded on every discarded delivery");
30
+ // #1096: with no --state the bulk clear takes the peer's queued rows and its unsettled failed rows (needs_review rows still need an explicit --state, as before); an explicit --state names exactly one kind.
31
+ const states = one["--state"] === undefined ? ["queued", "failed"] : [one["--state"]];
32
+ // A hub from before `queue_discard_states` ignores `states` and discards queued rows whatever kind was asked for, so the new wire form is never sent to it. A single queued or needs_review kind still goes in the legacy `state` field that every hub reads.
33
+ const legacy = states.length === 1 && (states[0] === "queued" || states[0] === "needs_review");
34
+ if (!legacy && !hub.features.includes("queue_discard_states")) fail(`the running hub predates failed-row discard and would discard queued rows instead of ${one["--state"] === undefined ? "queued and failed rows" : `${one["--state"]} rows`}; nothing was sent. Upgrade and restart it first, or run ahub queue discard --peer ${one["--peer"]} --state queued to clear queued rows only`);
35
+ const result = await hub.request({ t: "queue", op: "discard", peer: one["--peer"], ...(legacy ? { state: states[0] } : { states }), ...(yes ? { confirmed: true, reason: one["--reason"] } : {}) }, 60_000);
36
+ if (!result.ok) fail(result.error,result.refusalAudited===true,result.authorityRefused);
37
+ if (options.json) return console.log(JSON.stringify(result, null, 2));
38
+ // One kind keeps the sentence this command always printed ("12 queued deliveries for claude"); a mix of kinds names each ("3 queued and 2 failed deliveries for claude").
39
+ const present = Object.entries(result.byState ?? {}).filter(([, n]) => n) as [string, number][];
40
+ const noun = `deliver${result.count === 1 ? "y" : "ies"}`;
41
+ const what = present.length > 1 ? `${result.count} ${noun}` : `${result.count} ${present[0]?.[0] ?? states.join(" or ")} ${noun}`;
42
+ const split = present.length > 1 ? ` (${present.map(([kind, n]) => `${n} ${kind}`).join(" and ")})` : "";
43
+ if (!yes) return console.log(`${what} for ${result.peer}${split}; nothing discarded. Run again with --reason <text> --yes to discard them.`);
44
+ console.log(`discarded ${result.discarded} of ${what} for ${result.peer}${split}${result.refused ? `; ${result.refused} refused (${Object.entries(result.refusedBy ?? {}).map(([why, n]) => `${why} ${n}`).join(", ")})` : ""}`);
45
+ return;
46
+ }
47
+ const [id, ...flags] = rest;
48
+ if (!id || !["show", "resolve"].includes(operation)) fail("usage: ahub queue show <id> | resolve <id> --action completed|retry|discard --reason <text> [--revision N] | discard --peer <id> --reason <text> [--state queued|needs_review|failed] [--yes]");
49
+ if (operation === "show") {
50
+ if (flags.length) fail("usage: ahub queue show <id>");
51
+ const shown = await hub.request({ t: "queue", op: "show", id });
52
+ if (!shown.ok) fail(shown.error,shown.refusalAudited===true,shown.authorityRefused);
53
+ if (options.json) return console.log(JSON.stringify(shown.delivery, null, 2));
54
+ return printOutput(renderQueueShow(shown.delivery, options.columns, Date.now(), cwd), options.color);
55
+ }
56
+ const { one, rest: extra } = takeFlags(flags, ["--action", "--reason", "--revision"], []);
57
+ const rawRevision = one["--revision"], parsedRevision = rawRevision === undefined ? undefined : Number(rawRevision);
58
+ if (!queueResolveArgsValid(one["--action"], one["--reason"], rawRevision, extra)) fail("usage: ahub queue resolve <id> --action completed|retry|discard --reason <text> [--revision N]");
59
+ let revision = parsedRevision;
60
+ if (revision === undefined) {
61
+ const shown = await hub.request({ t: "queue", op: "show", id });
62
+ if (!shown.ok) fail(shown.error,shown.refusalAudited===true,shown.authorityRefused);
63
+ revision = shown.delivery.revision;
64
+ }
65
+ const result = await hub.request({ t: "queue", op: "resolve", id, revision, action: one["--action"], reason: one["--reason"] });
66
+ if (!result.ok) fail(result.error,result.refusalAudited===true,result.authorityRefused);
67
+ if (options.json) console.log(JSON.stringify(result.delivery, null, 2));
68
+ else printOutput(renderQueueShow(result.delivery, options.columns, Date.now(), cwd), options.color);
69
+ } finally { hub.close(); }
70
+ }
@@ -0,0 +1,13 @@
1
+ import { retireConductorOperation } from "../conductor-recovery.ts";
2
+ import { runRecovery } from "../upgrade.ts";
3
+ import { makeRecoveryDriver } from "../upgrade-runtime.ts";
4
+ import type { CommandContext } from "../command-context.ts";
5
+
6
+ export async function run(context: CommandContext) {
7
+ const { args, conductorPeer, delegatedPeer } = context;
8
+ const fail: CommandContext["fail"] = context.fail;
9
+ if (args.length !== 1 || process.env.AGENTHUB_RECOVERY_OPERATION !== args[0]) fail("recovery-run is an internal command");
10
+ const result = await runRecovery(args[0]!, makeRecoveryDriver(undefined, delegatedPeer, undefined, conductorPeer));
11
+ if (result.phase !== "completed") process.exitCode = 1;
12
+ else if (conductorPeer) retireConductorOperation(result, conductorPeer);
13
+ }
@@ -0,0 +1,130 @@
1
+ import { authorizeConductorOperation, retireConductorOperation } from "../conductor-recovery.ts";
2
+ import { spawn } from "node:child_process";
3
+ import { existsSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { realPath } from "../../hub/project.ts";
6
+ import { VERSION } from "../../version.ts";
7
+ import { operationIdPattern, readOperation, recoveryLock, recoveryRunner, supportsAction } from "../../hub/recovery-store.ts";
8
+ import { abortRecovery, disposeRecovery, recordRecoveryDelegation, repairedFreshSession, reattachRecovery, liveProjects, nextChoices, nextActionsText, publicOperation, recoveryCommand, type RecoveryOperation } from "../upgrade.ts";
9
+ import { makeRecoveryDriver } from "../upgrade-runtime.ts";
10
+ import { operationScreen } from "../upgrade-interactive.ts";
11
+ import { renderOperation, renderBlocked, renderSummary } from "../upgrade-presentation.ts";
12
+ import { renderRecoveryStatus } from "../upgrade-output.ts";
13
+ import { LIVE_TEST_PERSON_REFUSAL, liveTestRefusal } from "../identity.ts";
14
+ import { wrap } from "../console-state.ts";
15
+ import type { CommandContext } from "../command-context.ts";
16
+
17
+ export async function run(context: CommandContext) {
18
+ const { audit, cliDir, conductorPeer, cwd, delegatedPeer, humanRecovery, onTerminal, parseRecoveryReattach, printRecovery, printRecoveryStatus, recoveryDisplay, recoveryEndInspection, recoveryFormatting, spawnRecovery, takeFlags, upgradeHost, warn } = context;
19
+ const fail: CommandContext["fail"] = context.fail;
20
+ const display = recoveryDisplay();
21
+ const [action, given, ...more] = display.args;
22
+ const usage = "usage: ahub recovery [status|resume|abort] [<operation-id>] | ahub recovery dispose [<operation-id>] --fresh-session <peer>|--stop-and-archive --reason <text>";
23
+ if (action === "reattach") {
24
+ const selected = parseRecoveryReattach(display.args);
25
+ if (!selected) fail("usage: ahub recovery reattach <operation-id> codex|claude|pi");
26
+ let operation: RecoveryOperation;
27
+ try { operation = readOperation<RecoveryOperation>(selected.id); }
28
+ catch { fail(`recovery receipt ${selected.id} cannot be read; inspect the retained operation with ahub recovery status ${selected.id}; no session was started`); }
29
+ if (typeof operation.sourceRoot !== "string" || !operation.sourceRoot.trim()) fail(`recovery receipt ${selected.id} has no retained coordinator path; inspect it with ahub recovery status ${selected.id}; no session was started`);
30
+ const coordinator = join(operation.sourceRoot, "src/cli/main.js");
31
+ if (!existsSync(coordinator)) fail(`the retained coordinator for ${selected.id} is unavailable; restore its retained package and inspect ahub recovery status ${selected.id} before retrying; no session was started`);
32
+ let coordinatorIsCurrent: boolean;
33
+ try { coordinatorIsCurrent = realPath(coordinator) === realPath(join(cliDir, "main.js")); }
34
+ catch { fail(`the retained coordinator for ${selected.id} cannot be resolved; inspect ahub recovery status ${selected.id} before retrying; no session was started`); }
35
+ if (supportsAction(operation.sourceRoot, "reattach") && !coordinatorIsCurrent) {
36
+ if (humanRecovery(display.json)) {
37
+ for (const line of wrap("ahub: using the operation's retained coordinator for reattachment", display.options.columns)) console.error(line);
38
+ if (display.options.verbose) for (const line of wrap(recoveryCommand(operation, "reattach", selected.peer), display.options.columns)) console.error(line);
39
+ } else console.error(`ahub: using the operation's coordinator: ${recoveryCommand(operation, "reattach", selected.peer)}`);
40
+ const formatting = recoveryFormatting(coordinator, display.options);
41
+ const code = await new Promise<number>(resolve => {
42
+ const child = spawn(process.execPath, [coordinator, "recovery", "reattach", selected.id, selected.peer, ...formatting], { cwd, stdio: display.json ? ["inherit", "ignore", "inherit"] : "inherit", env: process.env });
43
+ child.on("error", () => { warn("coordinator could not start", recoveryCommand(operation, "status")); resolve(1); });
44
+ child.on("close", status => resolve(status ?? 1));
45
+ });
46
+ process.exitCode = code;
47
+ if (display.json && code === 0) console.log(JSON.stringify(publicOperation(readOperation<RecoveryOperation>(selected.id)), null, 2));
48
+ return;
49
+ }
50
+ const result = await reattachRecovery(selected.id, selected.peer, makeRecoveryDriver());
51
+ if (display.json) { console.log(JSON.stringify(publicOperation(result), null, 2)); return; }
52
+ printRecovery(renderOperation(result, undefined, display.options));
53
+ const live = await liveProjects(result, makeRecoveryDriver(undefined, delegatedPeer, undefined, conductorPeer).inspect);
54
+ printRecovery(renderBlocked(result, nextChoices(result, undefined, live), display.options));
55
+ return;
56
+ }
57
+ // #272: without an id, this project's hold (or a retained legacy machine hold); bare on a terminal, its screen.
58
+ const named = !!given && operationIdPattern.test(given);
59
+ const id = named ? given : recoveryLock(undefined, cwd);
60
+ const rest = named || given === undefined ? more : [given, ...more];
61
+ if (action === undefined && humanRecovery(display.json)) {
62
+ if (!id) return console.log("no recovery operation is open");
63
+ return onTerminal(async (io) => { await operationScreen(upgradeHost("restart", VERSION), io, id); }, display.options);
64
+ }
65
+ if (!["status", "resume", "abort", "dispose"].includes(action ?? "") || (action !== "dispose" && rest.length)) fail(usage);
66
+ if (!id) fail("no recovery operation holds the lock; name one by its id");
67
+ const delegatedFresh = delegatedPeer && action === "dispose" ? takeFlags(rest, ["--fresh-session", "--reason"], []).one["--fresh-session"] : undefined;
68
+ let operation: RecoveryOperation;
69
+ try { operation = readOperation<RecoveryOperation>(id); }
70
+ catch (error) {
71
+ if (delegatedFresh !== undefined) { audit("refused"); fail(LIVE_TEST_PERSON_REFUSAL); }
72
+ throw error;
73
+ }
74
+ if (delegatedFresh !== undefined) {
75
+ const repairedFresh = repairedFreshSession(operation, delegatedFresh);
76
+ if (repairedFresh === undefined || liveTestRefusal("recovery", display.args, { repairedFresh })) {
77
+ audit("refused"); fail(LIVE_TEST_PERSON_REFUSAL);
78
+ }
79
+ }
80
+ if (conductorPeer) {
81
+ if (operation.id !== id) fail("conductor recovery authority unavailable; the person runs it in ahub console or a terminal");
82
+ await authorizeConductorOperation(operation, conductorPeer);
83
+ }
84
+ const runner = recoveryRunner(id);
85
+ if (action === "status") {
86
+ // #215: abort and resume are offered by what the open sources show, read as the runner's errors read them.
87
+ const live = runner ? {} : await liveProjects(operation, makeRecoveryDriver(undefined, delegatedPeer, undefined, conductorPeer).inspect);
88
+ if (display.json) console.log(JSON.stringify(publicOperation(operation, runner, live), null, 2));
89
+ else printRecovery(renderRecoveryStatus(operation, runner, nextChoices(operation, runner, live), display.options));
90
+ }
91
+ else if (action === "abort") {
92
+ await abortRecovery(id, makeRecoveryDriver(undefined, delegatedPeer, undefined, conductorPeer));
93
+ if (conductorPeer) retireConductorOperation(readOperation<RecoveryOperation>(id), conductorPeer);
94
+ if (display.json) console.log(JSON.stringify(publicOperation(readOperation<RecoveryOperation>(id)), null, 2));
95
+ else console.log("preflight cancelled; no committed transition was rolled back");
96
+ }
97
+ else if (action === "dispose") {
98
+ // Console authority; #408 live-test delegation remains for ordinary fresh choices, never repaired loss.
99
+ const { one, rest: flags } = takeFlags(rest, ["--fresh-session", "--reason"], []);
100
+ const stop = flags.length === 1 && flags[0] === "--stop-and-archive";
101
+ const reason = one["--reason"]?.trim() ?? "";
102
+ if (!reason || reason.length > 500 || (flags.length && !stop) || stop === !!one["--fresh-session"]) fail(usage);
103
+ const result = await disposeRecovery(id, stop ? { stop: true } : { fresh: one["--fresh-session"]! }, reason, makeRecoveryDriver(undefined, delegatedPeer, undefined, conductorPeer));
104
+ if (!stop) {
105
+ if (display.json) { console.log(JSON.stringify(publicOperation(result), null, 2)); return spawnRecovery(result, true); }
106
+ console.log(`${one["--fresh-session"]}: a fresh session is accepted and the lost one is recorded; resuming`);
107
+ return spawnRecovery(result, false, humanRecovery(false) ? display.options : undefined);
108
+ }
109
+ if (display.json) console.log(JSON.stringify(publicOperation(result), null, 2));
110
+ else printRecovery(renderSummary(result, await recoveryEndInspection(result), display.options));
111
+ }
112
+ else if (["completed", "cancelled"].includes(operation.phase)) console.log(display.json ? JSON.stringify(publicOperation(operation, runner), null, 2) : `recovery is already ${operation.phase}`);
113
+ // #215: an operation being abandoned is never resumed, whichever coordinator started it (an older one would).
114
+ else if (operation.disposition) fail(`a stop-and-archive of this operation is partway; nothing was resumed; ${nextActionsText(operation, await liveProjects(operation, makeRecoveryDriver(undefined, delegatedPeer, undefined, conductorPeer).inspect))}`);
115
+ else if (runner === "unknown") {
116
+ if (display.json) console.log(JSON.stringify(publicOperation(operation, runner), null, 2));
117
+ else if (humanRecovery(false)) printRecoveryStatus(operation, "Runner ownership is unknown; nothing was started.", display.options);
118
+ else console.log(`whether a runner holds this operation could not be read; nothing was started; ${recoveryCommand(operation, "status")}`);
119
+ }
120
+ else if (runner) {
121
+ if (display.json) console.log(JSON.stringify(publicOperation(operation, runner), null, 2));
122
+ else if (humanRecovery(false)) printRecoveryStatus(operation, `runner ${runner} is still working on this operation`, display.options);
123
+ else console.log(`runner ${runner} is still working on this operation; ${recoveryCommand(operation, "status")}`);
124
+ }
125
+ else {
126
+ if (delegatedPeer) operation = recordRecoveryDelegation(operation.id, { peer: delegatedPeer, command: "recovery resume" });
127
+ if (display.json) { spawnRecovery(operation, true); console.log(JSON.stringify(publicOperation(operation), null, 2)); }
128
+ else spawnRecovery(operation, false, humanRecovery(false) ? display.options : undefined);
129
+ }
130
+ }
@@ -0,0 +1,23 @@
1
+ import { type Span } from "../console-state.ts";
2
+ import { renderReleaseChange, renderReleaseList, renderReleaseNew, renderReleaseShow } from "../task-output.ts";
3
+ import type { CommandContext } from "../command-context.ts";
4
+
5
+ export async function run(context: CommandContext) {
6
+ const { args, outputOptions, showToolText, splitPresentation, taskOp } = context;
7
+ const fail: CommandContext["fail"] = context.fail;
8
+ const split = splitPresentation(args, { edges: true }), operands = split.operands;
9
+ const [sub, name, revision, value] = operands;
10
+ const present = outputOptions(split.flags); // before any request: an invalid --color must refuse before a mutation is sent
11
+ const shown = (render: (data: any, columns?: number, now?: number, ascii?: boolean) => Span[][]) => async (text: Promise<string>) => showToolText(render, await text, present);
12
+ if (sub === "list" && operands.length === 1) return shown(renderReleaseList)(taskOp("hub_release_list", {}));
13
+ if (sub === "show" && name && operands.length === 2) return shown(renderReleaseShow)(taskOp("release_show", { name }));
14
+ if (sub === "new" && name && revision && operands.length === 4 && /^\d+$/.test(value ?? "")) return shown(renderReleaseNew)(taskOp("release_new", { name, goal: revision, order: Number(value) }));
15
+ if (!name || !/^\d+$/.test(revision ?? "")) fail("usage: ahub release new <name> <goal> <order>|list|show <name>|plan <name> <revision> <dates-json>|activate|freeze|ship|drop <name> <revision>");
16
+ const states: Record<string, string> = { activate: "active", freeze: "frozen", ship: "shipped", drop: "dropped" };
17
+ let fields: unknown;
18
+ if (sub === "plan" && value && operands.length === 4) {
19
+ try { fields = JSON.parse(value); } catch { return fail("release dates must be JSON"); }
20
+ } else if (sub && Object.hasOwn(states, sub) && operands.length === 3) fields = { state: states[sub] };
21
+ else return fail("invalid release command");
22
+ return shown(renderReleaseChange)(taskOp("release_change", { name, revision: Number(revision), fields }));
23
+ }
@@ -0,0 +1,91 @@
1
+ import { hubHome } from "../../hub/project.ts";
2
+ import type { CommandContext } from "../command-context.ts";
3
+ import { Report, asciiMarkers, resolveColor, streamEnv, terminalText } from "../console-state.ts";
4
+ import { listReleases, pruneReleases, RELEASE_KINDS, type PruneResult, type ReleaseEntry, type ReleaseInventory, type ReleaseKind } from "../../hub/releases-inventory.ts";
5
+
6
+ /** #1781: `ahub releases list` and `ahub releases prune`. Console authority only: classifyPeerCommand has no entry, so an agent shell is refused before this runs. */
7
+ export const RELEASES_USAGE = "usage: ahub releases list [--json] | ahub releases prune [--kind <capture|coordinator-source|registry-install>] [--older-than <days>] [--apply] [--json]";
8
+ export interface ReleasesOutcome { code: number; error?: string; next?: string }
9
+ interface Parsed { op: "list" | "prune"; json: boolean; apply: boolean; kind?: ReleaseKind; olderThanDays?: number; color?: string; ascii: boolean }
10
+
11
+ export function parseReleasesArgs(args: readonly string[]): Parsed | string {
12
+ const op = args[0];
13
+ if (op !== "list" && op !== "prune") return RELEASES_USAGE;
14
+ const parsed: Parsed = { op, json: false, apply: false, ascii: false };
15
+ for (let i = 1; i < args.length; i++) {
16
+ const arg = args[i]!;
17
+ if (arg === "--json" && !parsed.json) parsed.json = true;
18
+ else if (arg === "--ascii") parsed.ascii = true;
19
+ else if (arg.startsWith("--color=") && parsed.color === undefined) parsed.color = arg.slice("--color=".length);
20
+ else if (op === "prune" && arg === "--apply" && !parsed.apply) parsed.apply = true;
21
+ else if (op === "prune" && arg === "--kind" && parsed.kind === undefined) {
22
+ const value = args[++i];
23
+ if (!value || !(RELEASE_KINDS as readonly string[]).includes(value)) return RELEASES_USAGE;
24
+ parsed.kind = value as ReleaseKind;
25
+ } else if (op === "prune" && arg === "--older-than" && parsed.olderThanDays === undefined) {
26
+ const value = args[++i];
27
+ if (!value || !/^(0|[1-9][0-9]{0,5})$/.test(value)) return RELEASES_USAGE;
28
+ parsed.olderThanDays = Number(value);
29
+ } else return RELEASES_USAGE;
30
+ }
31
+ return parsed;
32
+ }
33
+
34
+ const size = (bytes: number): string => bytes >= 1 << 30 ? `${(bytes / (1 << 30)).toFixed(1)} GiB` : bytes >= 1 << 20 ? `${(bytes / (1 << 20)).toFixed(1)} MiB` : `${Math.ceil(bytes / 1024)} KiB`;
35
+ /** Sum only leaf entries: a legacy install already measures the captures and registry/ listed beside it. */
36
+ const total = (entries: readonly ReleaseEntry[]) => size(entries.filter(entry => !entries.some(other => other !== entry && other.path.startsWith(`${entry.path}/`))).reduce((sum, entry) => sum + entry.bytes, 0));
37
+ const view = (entry: ReleaseEntry) => ({ name: entry.name, path: entry.path, kind: entry.kind, version: entry.version, digest: entry.digest, bytes: entry.bytes,
38
+ modified: new Date(entry.modified).toISOString(), referencedBy: entry.referencedBy, removable: !entry.kept, ...(entry.kept ? { kept: entry.kept } : {}) });
39
+
40
+ function renderInventory(inventory: ReleaseInventory, report: Report, title: string): Report {
41
+ report.titled("ahub", title, `${inventory.entries.length} entries, ${total(inventory.entries)}`);
42
+ if (!inventory.complete) report.section("Attention").bullet("warn", `${terminalText(inventory.cause ?? "references could not be read")}; every entry is kept`).next(inventory.next ?? "ahub doctor");
43
+ for (const kind of [...RELEASE_KINDS, "unknown"] as const) {
44
+ const rows = inventory.entries.filter(entry => entry.kind === kind);
45
+ if (!rows.length) continue;
46
+ report.section(kind, `${rows.length}, ${total(rows)}`);
47
+ for (const entry of rows) report.bullet(entry.kept ? "active" : "ok", `${terminalText(entry.name)} ${size(entry.bytes)} ${entry.kept ? terminalText(entry.kept) : "unreferenced"}`);
48
+ }
49
+ return report;
50
+ }
51
+
52
+ export async function runReleasesCommand(args: readonly string[], home: string, env: NodeJS.ProcessEnv = process.env, deps: Parameters<typeof listReleases>[1] = {}): Promise<ReleasesOutcome> {
53
+ const parsed = parseReleasesArgs(args);
54
+ if (typeof parsed === "string") return { code: 2, error: parsed };
55
+ const color = resolveColor(parsed.color, streamEnv(!!process.stdout.isTTY), "ahub");
56
+ if (color instanceof Error) return { code: 2, error: RELEASES_USAGE };
57
+ const out = (text: string) => { process.stdout.write(text.endsWith("\n") ? text : `${text}\n`); };
58
+ const report = () => new Report(undefined, asciiMarkers(env, parsed.ascii));
59
+ if (parsed.op === "list") {
60
+ const inventory = listReleases(home, deps);
61
+ if (parsed.json) out(JSON.stringify({ home: inventory.home, complete: inventory.complete, ...(inventory.cause ? { cause: inventory.cause, next: inventory.next } : {}), entries: inventory.entries.map(view) }, null, 2));
62
+ else out(renderInventory(inventory, report(), "Releases").render(color === true).join("\n"));
63
+ return { code: 0 };
64
+ }
65
+ const result: PruneResult = pruneReleases(home, { apply: parsed.apply, ...(parsed.kind ? { kinds: [parsed.kind] } : {}), ...(parsed.olderThanDays !== undefined ? { olderThanDays: parsed.olderThanDays } : {}) }, deps);
66
+ const failed = !result.complete || result.skipped.length > 0;
67
+ if (parsed.json) {
68
+ out(JSON.stringify({ home: result.home, applied: result.applied, complete: result.complete, ...(result.cause ? { cause: result.cause, next: result.next } : {}),
69
+ candidates: result.candidates, removed: result.removed, quarantined: result.quarantined, skipped: result.skipped, kept: result.entries.filter(entry => entry.kept).map(view) }, null, 2));
70
+ } else {
71
+ const r = renderInventory({ ...result, entries: result.entries.filter(entry => entry.kept) }, report(), "Releases prune");
72
+ const names = (paths: readonly string[]) => paths.map(path => result.entries.find(entry => entry.path === path)).filter((entry): entry is ReleaseEntry => !!entry);
73
+ r.section(result.applied ? "Removed" : "Would remove", `${result.applied ? result.removed.length : result.candidates.length}`);
74
+ for (const entry of names(result.applied ? result.removed : result.candidates)) r.bullet("ok", `${terminalText(entry.name)} ${size(entry.bytes)}`);
75
+ if (result.skipped.length) {
76
+ r.section("Skipped", `${result.skipped.length}`);
77
+ for (const item of result.skipped) r.bullet("warn", `${terminalText(item.path)}: ${terminalText(item.why)}`);
78
+ r.next("ahub doctor");
79
+ }
80
+ if (!result.applied) r.note(result.candidates.length ? "nothing was changed; add --apply to remove these" : "nothing to remove");
81
+ out(r.render(color === true).join("\n"));
82
+ }
83
+ return { code: failed && parsed.apply || !result.complete ? 1 : 0 };
84
+ }
85
+
86
+
87
+ export async function run({ args, fail }: CommandContext): Promise<void> {
88
+ const outcome = await runReleasesCommand(args, hubHome());
89
+ if (outcome.error) fail("usage: ahub releases list [--json] | ahub releases prune [--kind <capture|coordinator-source|registry-install>] [--older-than <days>] [--apply] [--json]");
90
+ if (outcome.code) process.exit(outcome.code);
91
+ }
@@ -0,0 +1,6 @@
1
+ import { freeText } from "../free-text.ts";
2
+ import type { CommandContext } from "../command-context.ts";
3
+
4
+ export async function run({ args, taskOp }: CommandContext) {
5
+ return console.log(await taskOp("hub_remember", { text: freeText(args, "ahub remember <text>") }));
6
+ }
@@ -0,0 +1,27 @@
1
+ import { join } from "node:path";
2
+ import { readEvents } from "../../hub/events.ts";
3
+ import { summarize, summarizeByTask } from "../../hub/report.ts";
4
+ import { readDogfood } from "../../hub/dogfood-read.ts";
5
+ import { dogfoodSince, formatDogfood } from "../../hub/dogfood.ts";
6
+ import { asciiMarkers } from "../console-state.ts";
7
+ import { renderReport } from "../output.ts";
8
+ import type { CommandContext } from "../command-context.ts";
9
+
10
+ export async function run(context: CommandContext) {
11
+ const { args, cwd, outputOptions, printOutput, since, stateDir } = context;
12
+ const fail: CommandContext["fail"] = context.fail;
13
+ const options = outputOptions();
14
+ if (args.includes("--dogfood")) {
15
+ let from: number;
16
+ try { from = dogfoodSince(args.filter(arg => !arg.startsWith("--color="))); }
17
+ catch { return fail("usage: ahub report --dogfood [--since 7d|<iso>] [--json]"); }
18
+ const scorecard = await readDogfood(cwd, stateDir, from);
19
+ return console.log(options.json ? JSON.stringify(scorecard, null, 2) : formatDogfood(scorecard).join("\n"));
20
+ }
21
+ const by = args.indexOf("--by");
22
+ if (by >= 0 && args[by + 1] !== "task") return fail("--by takes task");
23
+ const events = readEvents(join(stateDir, "events.jsonl"), since());
24
+ const data = by >= 0 ? summarizeByTask(events) : summarize(events);
25
+ if (options.json) return console.log(JSON.stringify(data, null, 2));
26
+ printOutput(renderReport(data, options.columns, Date.now(), by >= 0, asciiMarkers(process.env, args.includes("--ascii"))), options.color);
27
+ }
@@ -0,0 +1,53 @@
1
+ import { refuseUnsupportedExportFormat } from "./shared-refusals.ts";
2
+ import { join } from "node:path";
3
+ import { Registry, type Project } from "../../hub/registry.ts";
4
+ import { datasetInputFor, exportResearchDataset, projectFamilyOf } from "../../hub/research-dataset.ts";
5
+ import { readEvidence } from "../../hub/research-record.ts";
6
+ import { VERSION } from "../../version.ts";
7
+ import { readEvents } from "../../hub/events.ts";
8
+ import { addonReport, appendRecords, closedAtOf, formatAddons, formatResearch, readStores, researchReport, taskRecords, toCsv } from "../../hub/research.ts";
9
+ import type { CommandContext } from "../command-context.ts";
10
+
11
+ export function run(context: CommandContext) {
12
+ const { args, cwd, researchArgs, researchProject, since, stateDir } = context;
13
+ const fail: CommandContext["fail"] = context.fail;
14
+ // #247: measures from the opt-in research records; `export` writes them out, `backfill` builds them from events.jsonl.
15
+ const [sub] = args;
16
+ researchArgs();
17
+ if (sub === "backfill") {
18
+ const project = researchProject(), familyOf = projectFamilyOf(cwd);
19
+ const written = appendRecords(project.id, taskRecords(readEvents(join(stateDir, "events.jsonl")), project.id, { version: VERSION, source: "backfill" }, { ...readEvidence(stateDir, project.id), ...(familyOf ? { familyOf } : {}) }));
20
+ return console.log(`${written} research record${written === 1 ? "" : "s"} written from this project's events`);
21
+ }
22
+ const all = args.includes("--all");
23
+ const from = since();
24
+ if (sub === "export" && args.includes("--dataset")) {
25
+ // #1277: the dataset is read-only over the stores; a project that was never researched has no file and no directory. The target is refused inside any registered project.
26
+ const registry = new Registry();
27
+ let registered: Project[];
28
+ try { registered = registry.list(); } finally { registry.close(); }
29
+ const here = researchProject(false), chosen = all ? registered : [here];
30
+ const inputs = chosen.flatMap(p => { const input = datasetInputFor(p); return input ? [input] : []; });
31
+ if (!inputs.length) return fail(all ? "no registered project has research records" : "this project has no research records; turn research on and run ahub research backfill");
32
+ try {
33
+ const written = exportResearchDataset(args[args.indexOf("--dataset") + 1]!, inputs, { ...(from > 0 ? { since: from } : {}) }, [...registered, here]);
34
+ for (const w of written) console.log(`${w.projectKeyHash}: ${w.counts.tasks} task${w.counts.tasks === 1 ? "" : "s"} (${w.counts.approved} approved, ${w.counts.cancelled} cancelled), ${w.counts.labels} label${w.counts.labels === 1 ? "" : "s"} -> ${w.dir}`);
35
+ } catch (error) { return fail((error as Error).message); }
36
+ return;
37
+ }
38
+ const records = readStores(all ? undefined : researchProject(false).id);
39
+ if (sub === "export") {
40
+ const format = args[args.indexOf("--format") + 1] ?? "jsonl";
41
+ if (args.includes("--format") && !["jsonl", "csv"].includes(format)) refuseUnsupportedExportFormat(fail);
42
+ const kept = records.filter((r) => r.kind === "label" || Date.parse(closedAtOf(r) ?? "") >= from);
43
+ return void process.stdout.write(args.includes("--format") && format === "csv" ? toCsv(kept) : kept.map((r) => JSON.stringify(r)).join("\n") + (kept.length ? "\n" : ""));
44
+ }
45
+ if (sub === "addons") {
46
+ // #248: approved tasks with each add-on on against off, by the tooling fingerprint in their records.
47
+ const rows = addonReport(records, from);
48
+ return console.log(args.includes("--json") ? JSON.stringify(rows, null, 2) : formatAddons(rows).join("\n"));
49
+ }
50
+ if (sub !== undefined && !sub.startsWith("--")) fail("usage: ahub research [--since 30d] [--all] [--json] | addons [--since] [--all] [--json] | export [--format jsonl|csv | --dataset <dir>] [--since] [--all] | backfill");
51
+ const r = researchReport(records, from);
52
+ console.log(args.includes("--json") ? JSON.stringify(r, null, 2) : formatResearch(r).join("\n"));
53
+ }
@@ -0,0 +1,89 @@
1
+ import { existsSync } from "node:fs";
2
+ import { randomUUID } from "node:crypto";
3
+ import { join } from "node:path";
4
+ import { Registry } from "../../hub/registry.ts";
5
+ import { inspectProject, stopProject } from "../../hub/lifecycle.ts";
6
+ import { processSignature } from "../../pi/process-signature.ts";
7
+ import { registeredProjects } from "../upgrade.ts";
8
+ import { asciiMarkers } from "../console-state.ts";
9
+ import { archiveProblem, archiveState, damagedState, failureText, MANIFEST, planReset, resetLines, resetRuntime, startState, type ResetPlan } from "../reset.ts";
10
+ import { RESET_KEPT, RESET_MEMORY, renderLifecycleReceipt, renderResetPlan } from "../reset-output.ts";
11
+ import type { CommandContext } from "../command-context.ts";
12
+
13
+ export async function run(context: CommandContext) {
14
+ const { args, cwd, hubManifest, liveManifest, matchingProject, printOutput, resetLockFree, stateDir } = context;
15
+ const fail: CommandContext["fail"] = context.fail;
16
+ if (args.some((a) => !["--all", "--yes"].includes(a))) fail("usage: ahub reset [--all] [--yes]");
17
+ const all = args.includes("--all");
18
+ resetLockFree();
19
+ // Registered with another state directory: `ahub up` here would register the default one and orphan that state.
20
+ const elsewhere = registeredProjects().find((p) => p.root === cwd);
21
+ const project = matchingProject() ?? fail(hubManifest() ? "hub has no matching registration; use its matching CLI to stop it; nothing was changed"
22
+ : elsewhere ? `this project is registered with the state directory ${elsewhere.stateDir}; run ahub --project ${elsewhere.id} reset; nothing was changed`
23
+ : "no registration matches this project and state directory; nothing was changed (ahub up registers it)");
24
+ if (!existsSync(stateDir)) return printOutput(renderLifecycleReceipt({ lines: ["no state directory; nothing to reset"] }), false);
25
+ // A state directory elsewhere (AGENTHUB_STATE_DIR, or a symlink) would cross file systems or pull outside state
26
+ // into the project tree.
27
+ if (all && stateDir !== join(cwd, ".agenthub", "state")) fail(`--all moves only ${join(cwd, ".agenthub", "state")}; this project's state is in ${stateDir}: stop the hub and archive it by hand; nothing was changed`);
28
+ const unsafe = all ? archiveProblem(cwd, stateDir) : undefined;
29
+ if (unsafe) fail(`${unsafe}; nothing was changed`);
30
+ const live = await inspectProject(project);
31
+ if (!["stopped", "running", "stopping"].includes(live.state)) fail(`${live.error ?? `hub is ${live.state}`}; nothing was changed`);
32
+ const recovery = live.status?.recovery as { operationId?: string; phase?: string } | undefined;
33
+ if (recovery?.operationId && recovery.phase !== "released") fail(`recovery operation ${recovery.operationId} is open in this hub; nothing was changed`);
34
+ const ascii = asciiMarkers(process.env);
35
+ if (!args.includes("--yes")) {
36
+ // Planned only for the dry run: `--all --yes` archives a state directory it cannot read as it is.
37
+ let plan: ResetPlan | undefined, unread: string | undefined;
38
+ try { plan = planReset(stateDir, project.id); }
39
+ catch (error) {
40
+ if (!all) fail(`cannot read the state (${failureText(error)}); nothing was changed${damagedState(error) ? "; ahub reset --all --yes archives it as it is" : ""}`);
41
+ unread = failureText(error);
42
+ }
43
+ const stale = live.state === "stopped" && !all ? MANIFEST.filter((name) => existsSync(join(stateDir, name))) : [];
44
+ return printOutput(renderResetPlan({ all, state: live.state, stateDir, archive: join(cwd, ".agenthub", "archive"),
45
+ projectId: project.id, plan, unread, stale }, undefined, undefined, ascii), false);
46
+ }
47
+ await stopProject(project);
48
+ let receiptStarted = false;
49
+ const receipt = (...lines: string[]) => {
50
+ printOutput(renderLifecycleReceipt({ ...(receiptStarted ? {} : { title: all ? "Reset --all" : "Reset" }), lines }, undefined, undefined, ascii), false);
51
+ receiptStarted = true;
52
+ };
53
+ if (live.state !== "stopped") receipt("hub stopped");
54
+ // Hold the claim a daemon takes to run: a hub started after the stop holds it (refused here), and none can start
55
+ // while the reset acts. A reset that dies leaves a claim with a dead pid, which the next start takes over.
56
+ const registry = new Registry();
57
+ // The prefix tells a concurrent reset's claim from a daemon's.
58
+ const claim = `reset-${randomUUID()}`;
59
+ try {
60
+ if (!registry.claim(project.id, claim, process.pid, processSignature(process.pid))) {
61
+ const holder = registry.get(project.id);
62
+ throw new Error(holder?.instanceId?.startsWith("reset-") ? `another ahub reset of this project is running (pid ${holder.pid}); nothing was reset` : "a hub started after the stop; nothing was reset, run ahub reset again");
63
+ }
64
+ if (liveManifest()) throw new Error("a hub started after the stop; nothing was reset, run ahub reset again");
65
+ // A recovery that took this project's hold after the first check must not run beside its reset.
66
+ resetLockFree();
67
+ if (all) {
68
+ let archived: string;
69
+ try { archived = archiveState(cwd, stateDir); }
70
+ catch (error) { throw new Error(`the hub is stopped; nothing was moved: ${failureText(error)}`); }
71
+ receipt(`moved the state directory to ${archived}`);
72
+ try { startState(stateDir, archived); }
73
+ catch (error) { throw new Error(`${(error as Error).message}; the state directory is archived at ${archived}: create ${stateDir} (0700) and copy project.json from the archive`); }
74
+ receipt(`the new state directory holds only project.json (to restore: ahub kill, move ${stateDir} into ${join(cwd, ".agenthub", "archive")}/, then move the archive back to ${stateDir})`);
75
+ } else {
76
+ let result: ReturnType<typeof resetRuntime>;
77
+ try { result = resetRuntime(stateDir, project); }
78
+ catch (error) {
79
+ throw new Error(`${failureText(error)}; the hub is stopped and the reset is incomplete: ${damagedState(error) ? "the state cannot be read, so a rerun fails the same way; ahub reset --all --yes archives it as it is" : "run ahub reset --yes again to finish it"}`);
80
+ }
81
+ receipt(`settled ${result.settled.length} deliveries as discard with reason "reset"`);
82
+ for (const line of resetLines(result.plan).slice(1)) receipt(`cleared ${line}`);
83
+ if (result.stale.length) receipt(`removed the manifest a hub left when it did not stop cleanly: ${result.stale.join(", ")}`);
84
+ receipt(RESET_KEPT);
85
+ }
86
+ } finally { registry.release(project.id, claim); registry.close(); }
87
+ receipt(RESET_MEMORY);
88
+ receipt("Claude Code sessions attached to this hub lost their hub session: relaunch them with ahub claude");
89
+ }
@@ -0,0 +1,5 @@
1
+ import type { CommandContext } from "../command-context.ts";
2
+
3
+ export function run({ upgrade }: CommandContext) {
4
+ return upgrade("restart");
5
+ }
@@ -0,0 +1,31 @@
1
+ import { parseResultsArgs } from "../results-args.ts";
2
+ import { renderAnswerReceipt, renderResults } from "../answer-output.ts";
3
+ import type { CommandContext } from "../command-context.ts";
4
+
5
+ export async function run(context: CommandContext) {
6
+ const { args, connect, outputOptions, printOutput } = context;
7
+ const fail: CommandContext["fail"] = context.fail;
8
+ const options = outputOptions();
9
+ const parsed = parseResultsArgs(args.filter(arg => arg !== "--json" && !arg.startsWith("--color=") && arg !== "--full"));
10
+ if (!parsed.ok) return fail(parsed.error);
11
+ const request = parsed.value;
12
+ const hub = await connect();
13
+ try {
14
+ if (request.action === "read") {
15
+ const reply = await hub.request({ t: "result_seen", id: request.id, surface: "terminal" });
16
+ if (reply.ok === false) return fail(String(reply.error ?? "the result could not be marked read"));
17
+ return options.json ? console.log(JSON.stringify({ ok: true, id: request.id, read: true })) : printOutput(renderAnswerReceipt({ kind: "read", id: request.id }), options.color);
18
+ }
19
+ if (request.action === "read-all" || request.action === "unread-last") {
20
+ const reply = await hub.request({ t: "results", action: request.action, surface: "terminal" });
21
+ if (reply.ok === false) return fail(String(reply.error ?? "the receipt could not be written"));
22
+ if (options.json) return console.log(JSON.stringify(request.action === "read-all" ? { ok: true, marked: reply.marked } : { ok: true, unread: reply.unread }));
23
+ return printOutput(renderAnswerReceipt(request.action === "read-all" ? { kind: "read-all", marked: reply.marked } : { kind: "unread-last", unread: reply.unread }), options.color);
24
+ }
25
+ const reply = await hub.request({ t: "results", unread: request.unread });
26
+ if (reply.ok === false) return fail(String(reply.error ?? "results are unavailable"));
27
+ const rows = Array.isArray(reply.results) ? reply.results : [];
28
+ if (options.json) return console.log(JSON.stringify(rows, null, 2));
29
+ printOutput(renderResults({ rows, unread: request.unread, more: Number(reply.more) }), options.color);
30
+ } finally { hub.close(); }
31
+ }
@@ -0,0 +1,5 @@
1
+ import type { CommandContext } from "../command-context.ts";
2
+
3
+ export function run({ hold }: CommandContext) {
4
+ return hold("resume");
5
+ }
@@ -0,0 +1,24 @@
1
+ import type { CommandContext } from "../command-context.ts";
2
+
3
+ export async function run(context: CommandContext) {
4
+ const { args, takeFlags, taskOp } = context;
5
+ const fail: CommandContext["fail"] = context.fail;
6
+ // #520: the review brief a reviewer gets, for a person or an outside tool.
7
+ if (args[0] === "brief") {
8
+ if (args.length !== 2 || !/^\d+$/.test(args[1]!)) fail("usage: ahub review brief <task id>");
9
+ return console.log(await taskOp("review_brief", { id: Number(args[1]) }));
10
+ }
11
+ const { one, many, rest } = takeFlags(args, ["--head", "--findings", "--security-pass"], ["--unmet"]);
12
+ const [id, verdict, ...note] = rest;
13
+ if (!id || !verdict) fail("usage: ahub review <id> approved|changes_requested [note...] [--unmet <item>]... [--head <sha>] [--findings <json>] [--security-pass <json>] | ahub review brief <id>");
14
+ let securityPass: unknown;
15
+ if (one["--security-pass"] !== undefined) {
16
+ try { securityPass = JSON.parse(one["--security-pass"]); } catch { fail("--security-pass must be a JSON object like {\"covered\":[\"unit\"],\"not_covered\":[]}"); }
17
+ }
18
+ let findings: unknown;
19
+ if (one["--findings"] !== undefined) {
20
+ try { findings = JSON.parse(one["--findings"]); } catch { fail("--findings must be a JSON array"); }
21
+ if (!Array.isArray(findings)) fail("--findings must be a JSON array");
22
+ }
23
+ console.log(await taskOp("hub_review", { id: Number(id), verdict, ...(one["--head"] ? { head: one["--head"] } : {}), note: note.join(" "), ...(findings === undefined ? {} : { findings }), ...(securityPass === undefined ? {} : { security_pass: securityPass }), ...(many["--unmet"]?.length ? { unmet: many["--unmet"] } : {}) }));
24
+ }
@@ -0,0 +1,21 @@
1
+ import { parseRoadmapArgs, renderRoadmap } from "../roadmap.ts";
2
+ import { roadmapWorktree, writeRoadmap } from "../roadmap-write.ts";
3
+ import { loadConfig } from "../../hub/config.ts";
4
+ import type { CommandContext } from "../command-context.ts";
5
+
6
+ export async function run(context: CommandContext) {
7
+ const { args, cwd, invokedFrom, outputOptions, taskOp } = context;
8
+ const fail: CommandContext["fail"] = context.fail;
9
+ let options;
10
+ try { options = parseRoadmapArgs(args); } catch (error) { return fail(`${error instanceof Error ? error.message : "invalid roadmap arguments"}; see ahub help roadmap`); }
11
+ // R3 (#1481): the GitHub reads and the model call each carry their own deadline, so these ops wait longer than the 30 s default.
12
+ const text = await taskOp(options.op, options.args, false, undefined, ["hub_roadmap_unplaced", "hub_roadmap_triage", "hub_roadmap_decompose", "roadmap_import_github", "hub_roadmap_check", "roadmap_sync", "roadmap_sync_apply", "roadmap_export_apply"].includes(options.op) ? 60_000 : undefined);
13
+ if (options.write) {
14
+ let rendered: { json: string; markdown: string };
15
+ try { rendered = JSON.parse(text); const root = roadmapWorktree(cwd, invokedFrom), policy = loadConfig(cwd); writeRoadmap(root, rendered, { deny: policy.local.deny, readOnly: policy.data?.readonly ?? [], pii: policy.pii?.paths ?? [] }); }
16
+ catch (error) { return fail(error instanceof Error ? error.message : "roadmap export unavailable"); }
17
+ if (!options.json) { console.log("Roadmap files written in the current worktree."); return; }
18
+ }
19
+ if (options.json) console.log(text);
20
+ else console.log(renderRoadmap(text, outputOptions().columns));
21
+ }