@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,84 @@
1
+ /**
2
+ * #1811 T2: a peer whose delivery stays unaccepted in an Orca pane may be waiting for the person at a prompt. The hub asks
3
+ * Orca for that pane's state with one bounded read of a public command and shows `blocked` or `waiting` as an Attention item.
4
+ * It reads only (`orca agent list --json --worktree id:<worktree id>`) and never answers the prompt.
5
+ *
6
+ * Shape verified on Orca 1.4.283 (docs/verification/2026-12-01-1811-orca-agent-list.md): `result.agents[]` rows carry `paneKey`
7
+ * (the pane's `tabId:leafId`), `state` (`working`, `blocked`, `waiting` or `done`) and `worktreeId`; the `--worktree` selector
8
+ * takes `id:<worktreeId>`, which the launch record holds.
9
+ */
10
+
11
+ type OrcaPaneState = "blocked" | "waiting";
12
+ interface OrcaRead { status: number; stdout: string }
13
+ /** Runs the Orca CLI with `argv`; rejects or answers a nonzero status when it cannot. Replaced in tests. */
14
+ type OrcaAgentRunner = (argv: readonly string[], boundMs: number) => Promise<OrcaRead>;
15
+ interface WatchedPane { handle: string; paneKey: string; worktreeId: string }
16
+ interface BlockedPane { peer: string; handle: string; state: OrcaPaneState; since: number }
17
+
18
+ /** How long a delivery stays unaccepted before the pane is asked, the bound of one read, and the least gap between two reads for a peer. */
19
+ const PANE_UNACCEPTED_MS = 120_000;
20
+ const PANE_READ_BOUND_MS = 5_000;
21
+ const PANE_READ_GAP_MS = 60_000;
22
+
23
+ /** The state of the agent in `paneKey`, or undefined when the answer has no such row or is not the shape read here. */
24
+ function paneStateOf(stdout: string, paneKey: string): OrcaPaneState | "other" | undefined {
25
+ let value: unknown;
26
+ try { value = JSON.parse(stdout); } catch { return undefined; }
27
+ const result = (value as { result?: { agents?: unknown } } | null)?.result;
28
+ if (!result || !Array.isArray(result.agents)) return undefined;
29
+ const rows = result.agents.filter((row): row is { paneKey: string; state?: unknown } => !!row && typeof row === "object" && (row as { paneKey?: unknown }).paneKey === paneKey);
30
+ if (rows.length !== 1) return undefined; // none or ambiguous: Orca does not say
31
+ const state = rows[0]!.state;
32
+ return state === "blocked" || state === "waiting" ? state : "other";
33
+ }
34
+
35
+ /** The default runner: the public CLI, killed at the bound, never run when its executable is not on the path. */
36
+ export function orcaAgentRunner(executable: () => string): OrcaAgentRunner {
37
+ return async (argv, boundMs) => {
38
+ const bin = executable();
39
+ if (!Bun.which(bin)) throw new Error("orca is not on the path");
40
+ const child = Bun.spawn([bin, ...argv], { stdout: "pipe", stderr: "ignore" });
41
+ // The bound covers the output too: a killed process whose child keeps the pipe open must not hold the read.
42
+ let timer: ReturnType<typeof setTimeout> | undefined;
43
+ const bound = new Promise<never>((_, reject) => { timer = setTimeout(() => { child.kill(); reject(new Error("orca read timed out")); }, boundMs); });
44
+ try { return await Promise.race([Promise.all([child.stdout.text(), child.exited]).then(([stdout, status]) => ({ stdout, status })), bound]); }
45
+ finally { clearTimeout(timer); }
46
+ };
47
+ }
48
+
49
+ export class OrcaPaneWatch {
50
+ private readonly lastRead = new Map<string, number>();
51
+ private readonly blockedBy = new Map<string, BlockedPane>();
52
+ private readonly reading = new Set<string>();
53
+ constructor(private readonly options: { run: OrcaAgentRunner; now?: () => number; unacceptedMs?: number; boundMs?: number; gapMs?: number }) {}
54
+
55
+ /** Whether a delivery queued at `oldestUnacceptedAt` has waited long enough to ask Orca about its pane; the daemon checks it before it reads a launch record. */
56
+ due(oldestUnacceptedAt: number | undefined): boolean {
57
+ return oldestUnacceptedAt !== undefined && (this.options.now ?? Date.now)() - oldestUnacceptedAt >= (this.options.unacceptedMs ?? PANE_UNACCEPTED_MS);
58
+ }
59
+
60
+ /** The panes that wait for the person now, one per peer. */
61
+ blocked(): BlockedPane[] { return [...this.blockedBy.values()]; }
62
+
63
+ /**
64
+ * One peer: `oldestUnacceptedAt` is when its oldest delivery was queued (undefined when none waits) and `pane` its recorded
65
+ * Orca pane (undefined when it has none, which is never read). Settles to nothing on an error, a timeout or any other state.
66
+ */
67
+ async check(peer: string, oldestUnacceptedAt: number | undefined, pane: WatchedPane | undefined): Promise<void> {
68
+ const now = (this.options.now ?? Date.now)();
69
+ if (!pane || oldestUnacceptedAt === undefined || now - oldestUnacceptedAt < (this.options.unacceptedMs ?? PANE_UNACCEPTED_MS)) { this.blockedBy.delete(peer); return; }
70
+ const last = this.lastRead.get(peer);
71
+ if (this.reading.has(peer) || last !== undefined && now - last < (this.options.gapMs ?? PANE_READ_GAP_MS)) return; // keep what the last read said
72
+ this.lastRead.set(peer, now);
73
+ this.reading.add(peer);
74
+ try {
75
+ const answer = await this.options.run(["agent", "list", "--json", "--worktree", `id:${pane.worktreeId}`], this.options.boundMs ?? PANE_READ_BOUND_MS);
76
+ const state = answer.status === 0 ? paneStateOf(answer.stdout, pane.paneKey) : undefined;
77
+ if (state === "blocked" || state === "waiting") {
78
+ const was = this.blockedBy.get(peer);
79
+ this.blockedBy.set(peer, { peer, handle: pane.handle, state, since: was && was.state === state ? was.since : now });
80
+ } else this.blockedBy.delete(peer);
81
+ } catch { this.blockedBy.delete(peer); }
82
+ finally { this.reading.delete(peer); }
83
+ }
84
+ }
@@ -1,7 +1,7 @@
1
1
  import { accessSync, constants, lstatSync, opendirSync, readlinkSync, statSync } from "node:fs";
2
2
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
3
  import { realPath } from "./project.ts";
4
- import { foldSegment } from "./permission-mode.ts";
4
+ import { foldSegment } from "./permission-paths.ts";
5
5
  /**
6
6
  * Whether `rel`, the result of `relative(root, path)`, names something inside the root: not `..`, not a path that starts with a `..` SEGMENT, and not absolute.
7
7
  * A string prefix test is wrong here: `..ignored/f.txt` is a valid directory named `..ignored` inside the project (#552), while `../f.txt` leaves it.
package/src/hub/peers.ts CHANGED
@@ -50,6 +50,10 @@ export interface FrontendProxyPort {
50
50
 
51
51
  export interface PeerAdapter {
52
52
  readonly id: PeerId;
53
+ /** Fixed builtin only. Synchronously compare the caller's home in memory. Undefined delegates to the next-launch comparison. */
54
+ compareQuotaHome?(callerHome: string | undefined): "same" | "different" | "unknown" | undefined;
55
+ /** Fixed builtin only. Ask the current process for a bounded quota reading after a saved renewal. */
56
+ readQuotaNow?(): void;
53
57
  /** Live waiting sessions, for display only; ids and pids grant no native identity or authority. */
54
58
  readonly standbySessions?: readonly PeerStandbySession[];
55
59
  /** The current owner's attachment facts, for display only; absent unless a socket is attached and no newer claim is arriving (#1310). */
@@ -110,7 +114,7 @@ export interface PeerAdapter {
110
114
  readonly statusNotice?: { code: "unidentified-cancellation" | "qwen-detached" | "qwen-stalled" | "qwen-deny-quiescence" | "jcode-headless-after-recovery"; message: string };
111
115
  /** Fixed builtins with session.nativeRevert only. Native conversation effects remain in the adapter. */
112
116
  revertTurn?(nativeTurn: string): Promise<void>;
113
- /** #445 C1: what this peer's native source lists right now (a probed version only), or an empty manifest. Never throws for an unprobed version; a transport failure rejects. */
117
+ /** #445 C1: what this peer's native source lists right now (a verified version, or an exact version the person trusted with `ahub agents trust`), or an empty manifest. Never throws for an unprobed version; a transport failure rejects. */
114
118
  capabilityManifest?(): Promise<CapabilityManifest>;
115
119
  /** Leave the roster without stopping a person's terminal. */
116
120
  detachForRoster?(resetMode: PermissionMode): void | Promise<void>;
@@ -1,13 +1,10 @@
1
- import { definitionOf, type ProjectAdapterCatalog, type KindMap } from "../adapters/registry.ts";
2
- import { lstatSync } from "node:fs";
3
- import { isAbsolute, relative, resolve, sep } from "node:path";
4
-
5
- /** Operator-selected approval frequency; agent sandboxes remain separate. */
6
- export const PERMISSION_MODES = ["ask", "ask-when-needed", "never-ask"] as const;
7
- export type PermissionMode = typeof PERMISSION_MODES[number];
1
+ import { builtinPolicyOf as definitionOf } from "../adapters/declaration-data.ts";
2
+ import type { ProjectAdapterCatalog, KindMap } from "../adapters/registry-types.ts";
3
+ import { isPermissionMode, type PermissionMode } from "./permission-paths.ts";
4
+ export * from "./permission-paths.ts";
8
5
  export { KIMI_MODE_IDS } from "../adapters/definitions/kimi-native.ts";
9
6
  export { QWEN_MODE_IDS } from "../adapters/definitions/qwen-native.ts";
10
- export const isPermissionMode = (value: unknown): value is PermissionMode => typeof value === "string" && (PERMISSION_MODES as readonly string[]).includes(value);
7
+
11
8
  export function permissionDefaults(value: unknown, instances?: KindMap, catalog?: ProjectAdapterCatalog): Record<string, PermissionMode> {
12
9
  if (value === undefined) return {};
13
10
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("permission_modes must be an object with ask, ask-when-needed or never-ask values");
@@ -38,36 +35,3 @@ export function permissionGrant(peer: string, mode: PermissionMode, instances?:
38
35
  if (mode === "ask") return "every write, edit and shell command asks";
39
36
  return mode === "never-ask" ? "every tool runs without asking, inside the hub sandbox and path guard" : "write, edit and proven bounded read-only shell commands inside the project run without asking; other shell commands and git writes still ask";
40
37
  }
41
- export const PI_EDIT_TOOLS = new Set(["edit", "write"]);
42
- /** Native agent policy files are never included in scoped automatic file grants. */
43
- export const AGENT_CONFIG_SEGMENTS: ReadonlySet<string> = new Set([".claude", ".codex", ".qwen", ".kimi", ".kimi-code", ".jcode", ".pi", ".mcp.json", ".agents", ".agent", "_agents", "_agent", ".gemini", ".grok", ".claude.json"]);
44
- export const INSTRUCTION_FILES: ReadonlySet<string> = new Set(["agents.md", "claude.md", "qwen.md", "gemini.md"]);
45
- export const isInstructionPath = (path: string): boolean => path.split(/[\\/]/).some(segment => INSTRUCTION_FILES.has(foldSegment(segment)));
46
- export function instructionProtection(value: unknown): boolean {
47
- if (value === undefined) return false;
48
- if (typeof value !== "boolean") throw new Error("protect_instruction_files must be a boolean");
49
- return value;
50
- }
51
- /**
52
- * One spelling per name, as a case-insensitive disk sees it: it opens `.mcp.j\u017Fon` (long s) as `.mcp.json`, and
53
- * HFS+ also ignores the default-ignorable code points (a zero-width joiner inside `.codex` is still `.codex`).
54
- */
55
- export const foldSegment = (segment: string): string => segment.normalize("NFKC").replace(/\p{Default_Ignorable_Code_Point}/gu, "").toLowerCase().toUpperCase().toLowerCase();
56
- /** The hub's and git's own directories: writing them changes what runs outside any agent's control. */
57
- export const HUB_WRITE_SEGMENTS: ReadonlySet<string> = new Set([".git", ".agenthub"]);
58
- export const isHubWritePath = (path: string): boolean => path.split(/[\\/]/).some(segment => HUB_WRITE_SEGMENTS.has(foldSegment(segment)));
59
- export const isAgentConfigPath = (path: string): boolean => path.split(/[\\/]/).some(segment => AGENT_CONFIG_SEGMENTS.has(foldSegment(segment)));
60
- /** A file with a second name somewhere else: a grant for this name would write that one too. */
61
- export function hardLinked(path: string): boolean {
62
- try { const st = lstatSync(path); return st.isFile() && st.nlink > 1; } catch { return false; } // a file that does not exist yet has no other name
63
- }
64
- /**
65
- * Whether a scoped automatic write or edit grant may cover `path` (canonical) in the project at `root` (canonical):
66
- * inside the project, outside every agent's configuration, judged by the path within the project (a project that
67
- * itself lives under `.claude/worktrees/` is still a project), and not a hard link.
68
- */
69
- export function grantablePath(root: string, path: string, originalPath?: string, protectInstructions = false): boolean {
70
- const inside = relative(root, path);
71
- const original = originalPath === undefined ? inside : relative(root, resolve(root, originalPath));
72
- return !!inside && inside !== ".." && !inside.startsWith(`..${sep}`) && !isAbsolute(inside) && !isAgentConfigPath(inside) && !isHubWritePath(inside) && !isAgentConfigPath(original) && !isHubWritePath(original) && !(protectInstructions && (isInstructionPath(inside) || isInstructionPath(original))) && !hardLinked(path);
73
- }
@@ -0,0 +1,41 @@
1
+ import { lstatSync } from "node:fs";
2
+ import { isAbsolute, relative, resolve, sep } from "node:path";
3
+
4
+ /** Operator-selected approval frequency; agent sandboxes remain separate. */
5
+ export const PERMISSION_MODES = ["ask", "ask-when-needed", "never-ask"] as const;
6
+ export type PermissionMode = typeof PERMISSION_MODES[number];
7
+ export const isPermissionMode = (value: unknown): value is PermissionMode => typeof value === "string" && (PERMISSION_MODES as readonly string[]).includes(value);
8
+
9
+ export const PI_EDIT_TOOLS = new Set(["edit", "write"]);
10
+ /** Native agent policy files are never included in scoped automatic file grants. */
11
+ export const AGENT_CONFIG_SEGMENTS: ReadonlySet<string> = new Set([".claude", ".codex", ".qwen", ".kimi", ".kimi-code", ".jcode", ".pi", ".mcp.json", ".agents", ".agent", "_agents", "_agent", ".gemini", ".grok", ".claude.json"]);
12
+ export const INSTRUCTION_FILES: ReadonlySet<string> = new Set(["agents.md", "claude.md", "qwen.md", "gemini.md"]);
13
+ export const isInstructionPath = (path: string): boolean => path.split(/[\\/]/).some(segment => INSTRUCTION_FILES.has(foldSegment(segment)));
14
+ export function instructionProtection(value: unknown): boolean {
15
+ if (value === undefined) return false;
16
+ if (typeof value !== "boolean") throw new Error("protect_instruction_files must be a boolean");
17
+ return value;
18
+ }
19
+ /**
20
+ * One spelling per name, as a case-insensitive disk sees it: it opens `.mcp.j\u017Fon` (long s) as `.mcp.json`, and
21
+ * HFS+ also ignores the default-ignorable code points (a zero-width joiner inside `.codex` is still `.codex`).
22
+ */
23
+ export const foldSegment = (segment: string): string => segment.normalize("NFKC").replace(/\p{Default_Ignorable_Code_Point}/gu, "").toLowerCase().toUpperCase().toLowerCase();
24
+ /** The hub's and git's own directories: writing them changes what runs outside any agent's control. */
25
+ export const HUB_WRITE_SEGMENTS: ReadonlySet<string> = new Set([".git", ".agenthub"]);
26
+ export const isHubWritePath = (path: string): boolean => path.split(/[\\/]/).some(segment => HUB_WRITE_SEGMENTS.has(foldSegment(segment)));
27
+ export const isAgentConfigPath = (path: string): boolean => path.split(/[\\/]/).some(segment => AGENT_CONFIG_SEGMENTS.has(foldSegment(segment)));
28
+ /** A file with a second name somewhere else: a grant for this name would write that one too. */
29
+ export function hardLinked(path: string): boolean {
30
+ try { const st = lstatSync(path); return st.isFile() && st.nlink > 1; } catch { return false; } // a file that does not exist yet has no other name
31
+ }
32
+ /**
33
+ * Whether a scoped automatic write or edit grant may cover `path` (canonical) in the project at `root` (canonical):
34
+ * inside the project, outside every agent's configuration, judged by the path within the project (a project that
35
+ * itself lives under `.claude/worktrees/` is still a project), and not a hard link.
36
+ */
37
+ export function grantablePath(root: string, path: string, originalPath?: string, protectInstructions = false): boolean {
38
+ const inside = relative(root, path);
39
+ const original = originalPath === undefined ? inside : relative(root, resolve(root, originalPath));
40
+ return !!inside && inside !== ".." && !inside.startsWith(`..${sep}`) && !isAbsolute(inside) && !isAgentConfigPath(inside) && !isHubWritePath(inside) && !isAgentConfigPath(original) && !isHubWritePath(original) && !(protectInstructions && (isInstructionPath(inside) || isInstructionPath(original))) && !hardLinked(path);
41
+ }
@@ -61,6 +61,26 @@ export interface ProjectContext {
61
61
  stateDir: string;
62
62
  }
63
63
 
64
+ /** #1779 T2: what a daemon knows about its project, passed down explicitly. `env` is the environment its children inherit. */
65
+ export interface DaemonProjectContext extends ProjectContext {
66
+ readonly env: NodeJS.ProcessEnv;
67
+ }
68
+
69
+ /** The one place a daemon takes its project identity and child environment from the process; everything below `startDaemon` reads the returned context. */
70
+ export function daemonProjectContext(root: string, stateDir: string, env: NodeJS.ProcessEnv): DaemonProjectContext {
71
+ return Object.freeze({ root, stateDir, env: Object.freeze({ ...env }) });
72
+ }
73
+
74
+ /** A hosted project's context: the host's environment with this project's own state and project directories, never another project's. */
75
+ export function hostedProjectContext(project: ProjectContext, hostEnv: NodeJS.ProcessEnv): DaemonProjectContext {
76
+ return daemonProjectContext(project.root, project.stateDir, { ...hostEnv, ...projectChildEnv(project) });
77
+ }
78
+
79
+ /** The two variables that bind a child process (a tool server, a hook) to this project. */
80
+ export function projectChildEnv(context: ProjectContext): { AGENTHUB_STATE_DIR: string; AGENTHUB_PROJECT_DIR: string } {
81
+ return { AGENTHUB_STATE_DIR: context.stateDir, AGENTHUB_PROJECT_DIR: context.root };
82
+ }
83
+
64
84
  /** Resolve a project and accept an inherited state directory only with an ownership proof. */
65
85
  export function projectContext(cwd: string, env: NodeJS.ProcessEnv = process.env): ProjectContext {
66
86
  const root = projectRoot(cwd);
@@ -17,3 +17,61 @@ export function negotiateProtocol(local: ProtocolWindow, remote: ProtocolWindow)
17
17
  const highest = Math.min(a.v, b.v);
18
18
  return highest >= Math.max(a.vMin, b.vMin) ? highest : undefined;
19
19
  }
20
+
21
+ export interface BridgeWindowSettings {
22
+ bridge_window_days: number;
23
+ bridge_window_min: number;
24
+ }
25
+
26
+ export const DEFAULT_BRIDGE_WINDOW: Readonly<BridgeWindowSettings> = {
27
+ bridge_window_days: 90,
28
+ bridge_window_min: 3,
29
+ };
30
+
31
+ /** Published stable tags grouped by their literal control protocol; the last release sets the age cutoff. */
32
+ export const BRIDGE_PROTOCOL_RELEASES = [
33
+ [4, "v0.1.0", "2026-09-19", "v0.1.0", "2026-09-19"],
34
+ [5, "v0.2.0", "2026-09-19", "v0.2.0", "2026-09-19"],
35
+ [6, "v0.3.0", "2026-09-19", "v0.3.2", "2026-09-19"],
36
+ [7, "v0.4.0", "2026-09-19", "v0.4.0", "2026-09-19"],
37
+ [8, "v0.5.0", "2026-09-20", "v0.5.0", "2026-09-20"],
38
+ [9, "v0.6.0", "2026-09-20", "v0.6.4", "2026-09-20"],
39
+ [10, "v0.7.0", "2026-09-20", "v0.12.0", "2026-10-01"],
40
+ [11, "v0.12.1", "2026-10-01", "v0.12.2", "2026-10-02"],
41
+ [12, "v0.12.3", "2026-10-02", "v0.12.3", "2026-10-02"],
42
+ [13, "v0.12.4", "2026-10-03", "v0.12.15", "2026-10-07"],
43
+ [14, "v0.12.16", "2026-10-09", "v0.12.16", "2026-10-09"],
44
+ [15, "v0.12.17", "2026-10-09", "v0.12.19", "2026-10-09"],
45
+ [16, "v0.12.20", "2026-10-09", "v0.25.0", "2026-11-01"],
46
+ [17, "v0.26.0", "2026-11-01", "v0.52.0", "2026-12-03"],
47
+ ] as const;
48
+
49
+ export function bridgeWindowSettings(raw: unknown): BridgeWindowSettings {
50
+ if (raw === undefined) return { ...DEFAULT_BRIDGE_WINDOW };
51
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)
52
+ || Object.keys(raw).some(key => !Object.hasOwn(DEFAULT_BRIDGE_WINDOW, key))) {
53
+ throw new Error("upgrade accepts only bridge_window_days and bridge_window_min");
54
+ }
55
+ const settings = { ...DEFAULT_BRIDGE_WINDOW };
56
+ for (const key of Object.keys(settings) as (keyof BridgeWindowSettings)[]) {
57
+ const value = (raw as Record<string, unknown>)[key];
58
+ if (value === undefined) continue;
59
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
60
+ throw new Error(`upgrade.${key} must be a nonnegative integer`);
61
+ }
62
+ settings[key] = value;
63
+ }
64
+ return settings;
65
+ }
66
+
67
+ /** Compute the release-history interval, clamped at the supplied implementation floor. */
68
+ export function bridgeProtocolWindow(settings: BridgeWindowSettings, implementedFloor: number, now: number): ProtocolWindow {
69
+ const current = BRIDGE_PROTOCOL_RELEASES.at(-1)![0];
70
+ if (!protocolWindow(current, implementedFloor) || !Number.isFinite(now)) throw new Error("invalid bridge window boundary");
71
+ const cutoff = now - settings.bridge_window_days * 86_400_000;
72
+ const byAge = settings.bridge_window_days === 0 ? current
73
+ : BRIDGE_PROTOCOL_RELEASES.find(([, , first, , last]) => Date.parse(first) <= now && Date.parse(last) >= cutoff)?.[0] ?? current;
74
+ const countIndex = Math.max(0, BRIDGE_PROTOCOL_RELEASES.length - 1 - settings.bridge_window_min);
75
+ const byCount = BRIDGE_PROTOCOL_RELEASES[countIndex]![0];
76
+ return { v: current, vMin: Math.max(implementedFloor, Math.min(byAge, byCount)) };
77
+ }
@@ -0,0 +1,20 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ /** A host-local ordering mark. Persisted marks name a runtime generation, never an account or path. */
4
+ export interface QuotaStamp {
5
+ runtime: string;
6
+ order: number;
7
+ }
8
+
9
+ const runtime = randomUUID();
10
+ let order = 0;
11
+
12
+ export function stampQuotaBoundary(): QuotaStamp {
13
+ return { runtime, order: ++order };
14
+ }
15
+
16
+ /** A reading must originate in this hub run. An earlier run's durable renewal predates our owned spawns. */
17
+ export function quotaStampAfter(previous: QuotaStamp, observed: QuotaStamp): boolean {
18
+ return observed.runtime === runtime
19
+ && (previous.runtime !== runtime || observed.order > previous.order);
20
+ }
@@ -9,7 +9,7 @@ import { isAbsolute, join, resolve } from "node:path";
9
9
  import { types } from "node:util";
10
10
  import { definitionOf } from "../adapters/registry.ts";
11
11
  import { adapterCeiling, applyRoleCeiling } from "../adapters/role-eligibility.ts";
12
- import type { HubConfig } from "./daemon.ts";
12
+ import type { HubConfig } from "./config.ts";
13
13
  import type { ConfigSourceTexts } from "./config-reload.ts";
14
14
  import { conductorPeer } from "./conductor.ts";
15
15
  import { DEFAULT_ROLES } from "./hub-tools.ts";
@@ -30,8 +30,8 @@ export interface Project {
30
30
  * #226: `pid_signature` holds "<instance id> <signature>". An older daemon's claim rewrites instance_id and pid but not
31
31
  * this column, so a signature counts only for the instance that wrote it: under another instance the claim is unsigned.
32
32
  */
33
- export const PROJECT_COLUMNS = "id, root, state_dir as stateDir, base_port as basePort, instance_id as instanceId, pid";
34
- export function projectFromRow(raw: Record<string, unknown>): Project {
33
+ const PROJECT_COLUMNS = "id, root, state_dir as stateDir, base_port as basePort, instance_id as instanceId, pid";
34
+ function projectFromRow(raw: Record<string, unknown>): Project {
35
35
  const { pid_signature: signed, ...row } = raw;
36
36
  const project = { ...row } as unknown as Project;
37
37
  const prefix = `${project.instanceId} `;
@@ -64,6 +64,8 @@ export class Registry {
64
64
  base_port INTEGER NOT NULL UNIQUE, instance_id TEXT, pid INTEGER, claimed_at INTEGER
65
65
  )`);
66
66
  this.db.run("CREATE TABLE IF NOT EXISTS registry_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)");
67
+ // #1779 T3a: one host process per runtime root, claimed here so a second starter cannot take over a live host's socket.
68
+ this.db.run("CREATE TABLE IF NOT EXISTS host_claims (runtime_root TEXT PRIMARY KEY, host_id TEXT NOT NULL, pid INTEGER NOT NULL, pid_signature TEXT, claimed_at INTEGER NOT NULL)");
67
69
  const columns = this.db.query("PRAGMA table_info(projects)").all() as { name: string }[];
68
70
  if (!columns.some((c) => c.name === "pid_signature")) {
69
71
  try { this.db.run("ALTER TABLE projects ADD COLUMN pid_signature TEXT"); }
@@ -156,6 +158,25 @@ export class Registry {
156
158
  return claimed;
157
159
  }
158
160
 
161
+ /**
162
+ * #1779 T3a: claim the host of a runtime root. Atomic in one immediate transaction: the claim is refused while another host's process is live or uncertain,
163
+ * and taken over only when that process is gone. Only the winner may remove a stale socket file and listen; a loser joins the answering host or fails closed.
164
+ */
165
+ claimHost(runtimeRoot: string, hostId: string, pid: number, signature?: string): { claimed: true } | { claimed: false; holderPid: number } {
166
+ let outcome: { claimed: true } | { claimed: false; holderPid: number } = { claimed: true };
167
+ const tx = this.db.transaction(() => {
168
+ const row = this.db.query("SELECT host_id, pid, pid_signature FROM host_claims WHERE runtime_root = ?").get(runtimeRoot) as { host_id: string; pid: number; pid_signature: string | null } | null;
169
+ if (row && row.host_id !== hostId && processLiveness(row.pid, row.pid_signature) !== "gone") { outcome = { claimed: false, holderPid: row.pid }; return; }
170
+ this.db.query("INSERT OR REPLACE INTO host_claims (runtime_root, host_id, pid, pid_signature, claimed_at) VALUES (?, ?, ?, ?, ?)").run(runtimeRoot, hostId, pid, signature ?? null, Date.now());
171
+ });
172
+ this.runtimeCaptureLocked(tx);
173
+ return outcome;
174
+ }
175
+
176
+ releaseHost(runtimeRoot: string, hostId: string): void {
177
+ this.db.query("DELETE FROM host_claims WHERE runtime_root = ? AND host_id = ?").run(runtimeRoot, hostId);
178
+ }
179
+
159
180
  release(id: string, instanceId: string): void {
160
181
  this.db.query("UPDATE projects SET instance_id = NULL, pid = NULL, pid_signature = NULL, claimed_at = NULL WHERE id = ? AND instance_id = ?").run(id, instanceId);
161
182
  }
@@ -233,3 +254,16 @@ export class Registry {
233
254
  runTx(tx as Tx);
234
255
  }
235
256
  }
257
+
258
+ /** Registry reads for planning must not create a registry or run migrations. */
259
+ export function registeredProjects(home = hubHome()): Project[] {
260
+ const path = join(home, "registry.db");
261
+ if (!existsSync(path)) return [];
262
+ const db = new Database(path, { readonly: true });
263
+ try {
264
+ db.run(`PRAGMA busy_timeout = ${REGISTRY_DB_BUSY_TIMEOUT_MS}`);
265
+ // #226: a registry no current release opened yet has no signature column, and this read never migrates.
266
+ const signed = (db.query("PRAGMA table_info(projects)").all() as { name: string }[]).some((c) => c.name === "pid_signature");
267
+ return (db.query(`SELECT ${PROJECT_COLUMNS}${signed ? ", pid_signature" : ""} FROM projects ORDER BY root`).all() as Record<string, unknown>[]).map(projectFromRow);
268
+ } finally { db.close(); }
269
+ }
@@ -0,0 +1,198 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { lstatSync, mkdirSync, readdirSync, renameSync, rmSync, type Stats } from "node:fs";
3
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { realPath } from "./project.ts";
5
+ import type { Registry } from "./registry.ts";
6
+ import { observeRuntimeReferences, openRuntimeRegistry, underRuntimeReferences, type RuntimeReferences } from "./runtime-capture-prune.ts";
7
+
8
+ /** #1781: what lives under `$AGENTHUB_HOME/releases`, who refers to it, and the explicit removal of what nothing refers to. */
9
+ export const RELEASE_KINDS = ["capture", "coordinator-source", "registry-install"] as const;
10
+ export type ReleaseKind = typeof RELEASE_KINDS[number] | "unknown";
11
+ export interface ReleaseEntry {
12
+ path: string; name: string; kind: ReleaseKind; version: string | null; digest: string | null; bytes: number;
13
+ /** Newest mtime anywhere in the entry's tree, so a file written inside a parent keeps it young. */
14
+ modified: number;
15
+ /** Scan-time identity and direct children, compared again under the lock. */
16
+ identity: { dev: number; ino: number; mtimeMs: number }; children: string[];
17
+ /** Who refers to it (`project <root>`, `recovery operation <id>`, `live manager`, `running process`, `this CLI`). Empty when nothing does. */
18
+ referencedBy: string[];
19
+ /** Why it stays; absent when it is removable. */
20
+ kept?: string;
21
+ }
22
+ export interface ReleaseInventory { home: string; entries: ReleaseEntry[]; complete: boolean; cause?: string; next?: string }
23
+ interface InventoryDeps { processTable?: () => string; now?: () => number; executingRoot?: string; /** test seam: runs after the scan and before each entry's locked recheck */ beforeRecheck?: (entry: ReleaseEntry) => void }
24
+ interface PruneOptions { kinds?: readonly ReleaseKind[]; /** Default: one hour. `0` removes entries of any age. */ olderThanDays?: number; apply: boolean }
25
+ /** An entry written by an upgrade or a stage before its receipt or runtime.json exists has no referrer yet; keep anything this young unless --older-than says otherwise. */
26
+ const DEFAULT_MIN_AGE_MS = 60 * 60 * 1000;
27
+ export interface PruneResult extends ReleaseInventory { candidates: string[]; removed: string[]; quarantined: string[]; skipped: { path: string; why: string }[]; applied: boolean }
28
+
29
+ const VERSION = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/;
30
+ const SOURCE = /^source-([a-f0-9]{64})$/;
31
+ const MAX_WALK = 200_000;
32
+ const RECOVERY_NEXT = "run ahub doctor, fix what it names (ahub recovery status shows an open operation), then run the command again";
33
+
34
+ const contains = (parent: string, child: string) => { const inside = relative(parent, child); return inside === "" || inside !== ".." && !inside.startsWith(`..${sep}`) && !isAbsolute(inside); };
35
+ function optional(path: string): Stats | undefined {
36
+ try { return lstatSync(path); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; throw error; }
37
+ }
38
+ function measure(path: string): { bytes: number; newest: number } {
39
+ let bytes = 0, seen = 0;
40
+ const root = lstatSync(path); bytes += root.size;
41
+ let newest = root.mtimeMs;
42
+ const walk = (directory: string) => {
43
+ for (const name of readdirSync(directory)) {
44
+ if (++seen > MAX_WALK) throw new Error("release entry is too large to measure");
45
+ const info = lstatSync(join(directory, name));
46
+ bytes += info.size; newest = Math.max(newest, info.mtimeMs);
47
+ if (info.isDirectory() && !info.isSymbolicLink()) walk(join(directory, name));
48
+ }
49
+ };
50
+ if (root.isDirectory() && !root.isSymbolicLink()) walk(path);
51
+ return { bytes, newest };
52
+ }
53
+ /** One `ps` read. A failed or empty read is an error: an unknown process table never means "no process". */
54
+ function readProcessTable(): string {
55
+ const result = Bun.spawnSync(["ps", "-axo", "command="], { stdout: "pipe", stderr: "pipe" });
56
+ const text = result.stdout.toString();
57
+ if (result.exitCode !== 0 || !text.trim()) throw new Error("the process table could not be read");
58
+ return text;
59
+ }
60
+
61
+ interface Raw { path: string; name: string; kind: ReleaseKind; version: string | null; digest: string | null; info: Stats; note?: string }
62
+ function scan(home: string): Raw[] {
63
+ const releases = join(home, "releases"), info = optional(releases);
64
+ if (!info) return [];
65
+ if (!info.isDirectory() || info.isSymbolicLink()) throw new Error("the releases directory is a symlink or not a directory");
66
+ const rows: Raw[] = [];
67
+ const add = (path: string, name: string, kind: ReleaseKind, version: string | null, digest: string | null, note?: string) =>
68
+ rows.push({ path, name, kind, version, digest, info: lstatSync(path), ...(note ? { note } : {}) });
69
+ for (const name of readdirSync(releases).sort()) {
70
+ const path = join(releases, name), info = lstatSync(path);
71
+ if (info.isSymbolicLink() || !info.isDirectory()) { add(path, name, "unknown", null, null, info.isSymbolicLink() ? "a symlink is never followed" : "not a directory"); continue; }
72
+ const source = SOURCE.exec(name);
73
+ if (source) { add(path, name, "coordinator-source", null, source[1]!); continue; }
74
+ if (!VERSION.test(name)) { add(path, name, "unknown", null, null, "unrecognized layout"); continue; }
75
+ const children = readdirSync(path).sort();
76
+ const installed = children.includes("verified.json") || children.includes("node_modules");
77
+ const held: string[] = [];
78
+ for (const child of children) {
79
+ const childPath = join(path, child), childInfo = lstatSync(childPath), match = SOURCE.exec(child);
80
+ if (match) {
81
+ if (childInfo.isSymbolicLink() || !childInfo.isDirectory()) add(childPath, `${name}/${child}`, "unknown", name, null, "a symlink is never followed");
82
+ else { add(childPath, `${name}/${child}`, "capture", name, match[1]!); held.push(child); }
83
+ } else if (child === "registry") {
84
+ if (childInfo.isSymbolicLink() || !childInfo.isDirectory()) add(childPath, `${name}/${child}`, "unknown", name, null, "a symlink is never followed");
85
+ else add(childPath, `${name}/${child}`, "registry-install", name, null);
86
+ } else if (!installed || !["verified.json", "node_modules", "package.json", "bun.lock", "bun.lockb"].includes(child)) {
87
+ add(childPath, `${name}/${child}`, "unknown", name, null, "unrecognized layout");
88
+ }
89
+ }
90
+ if (installed) add(path, name, "registry-install", name, null, held.length ? "holds captures; remove those first" : undefined);
91
+ }
92
+ return rows;
93
+ }
94
+
95
+ function holders(row: Raw, references: RuntimeReferences | undefined, table: string | undefined, executing: string): string[] {
96
+ const who: string[] = [];
97
+ if (references) {
98
+ for (const [root, names] of references.referrers) if (contains(row.path, root) || contains(root, row.path)) for (const name of names) who.push(name);
99
+ if (references.managerRoot && (contains(row.path, references.managerRoot) || contains(references.managerRoot, row.path))) who.push("live manager");
100
+ }
101
+ if (contains(row.path, executing)) who.push("this CLI");
102
+ if (table !== undefined && table.includes(row.path)) who.push("running process");
103
+ return [...new Set(who)].sort();
104
+ }
105
+
106
+ /** Classification and references only; nothing is changed. A reference check that cannot complete keeps every entry and says why. */
107
+ export function listReleases(homeInput: string, deps: InventoryDeps = {}): ReleaseInventory {
108
+ let home = homeInput;
109
+ try { home = realPath(homeInput); } catch { /* the registry open below names the cause */ }
110
+ let rows: Raw[];
111
+ try { rows = scan(home); }
112
+ catch (error) { return { home, entries: [], complete: false, cause: `the releases directory could not be read completely: ${(error as Error).message}`, next: "inspect the directory with ls -la, then run the command again" }; }
113
+ let references: RuntimeReferences | undefined, table: string | undefined, cause: string | undefined, next: string | undefined;
114
+ let registry: Registry | undefined;
115
+ try {
116
+ if (rows.length) {
117
+ const opened = openRuntimeRegistry(home); registry = opened.registry;
118
+ references = observeRuntimeReferences(opened.home, registry);
119
+ }
120
+ } catch (error) { cause = `references could not be read completely: ${(error as Error).message}`; next = RECOVERY_NEXT; }
121
+ finally { registry?.close(); }
122
+ if (!cause && rows.length) {
123
+ try { table = (deps.processTable ?? readProcessTable)(); }
124
+ catch (error) { cause = `references could not be read completely: ${(error as Error).message}`; next = "check that ps works for this user, then run the command again"; }
125
+ }
126
+ const executing = deps.executingRoot ?? resolve(import.meta.dir, "../..");
127
+ const entries = rows.map((row): ReleaseEntry => {
128
+ const referencedBy = holders(row, references, table, executing);
129
+ let bytes = 0, newest = row.info.mtimeMs, kept: string | undefined = row.note, children: string[] = [];
130
+ try { const measured = measure(row.path); bytes = measured.bytes; newest = measured.newest; } catch (error) { kept ??= `size unreadable: ${(error as Error).message}`; }
131
+ try { children = readdirSync(row.path).sort(); } catch (error) { kept ??= `entries unreadable: ${(error as Error).message}`; }
132
+ if (row.kind === "unknown") kept ??= "unknown layout";
133
+ else if (cause) kept ??= cause;
134
+ else if (referencedBy.length) kept ??= `referenced by ${referencedBy.join(", ")}`;
135
+ return { path: row.path, name: row.name, kind: row.kind, version: row.version, digest: row.digest, bytes, modified: newest,
136
+ identity: { dev: row.info.dev, ino: row.info.ino, mtimeMs: row.info.mtimeMs }, children, referencedBy, ...(kept ? { kept } : {}) };
137
+ });
138
+ // AC5: an entry that holds an unknown or kept entry (a legacy install with a quarantine, a symlinked source, a referenced capture) stays whole.
139
+ for (const entry of entries) {
140
+ if (entry.kept) continue;
141
+ const inside = entries.find(other => other !== entry && other.path.startsWith(entry.path + sep) && (other.kind === "unknown" || other.kept));
142
+ if (inside) entry.kept = `holds ${inside.kind === "unknown" ? "an unknown entry" : "a kept entry"}: ${relative(entry.path, inside.path)}`;
143
+ }
144
+ return { home, entries, complete: !cause, ...(cause ? { cause } : {}), ...(next ? { next } : {}) };
145
+ }
146
+
147
+ /** Entries the rule allows removing, after the kind and age filters. `unknown` never qualifies. */
148
+ function pruneCandidates(inventory: ReleaseInventory, options: Pick<PruneOptions, "kinds" | "olderThanDays">, now: number): ReleaseEntry[] {
149
+ const floor = options.olderThanDays === undefined ? DEFAULT_MIN_AGE_MS : options.olderThanDays * 86_400_000;
150
+ return inventory.entries.filter(entry => entry.kind !== "unknown" && !entry.kept && (!options.kinds?.length || options.kinds.includes(entry.kind))
151
+ && entry.modified <= now - floor);
152
+ }
153
+
154
+ /**
155
+ * Preview by default. With `apply`, each entry is rechecked immediately before it moves: fresh references and process table, then, under the
156
+ * registry writer lock the background worker uses, the observed references are re-proved unchanged and the entry's identity is confirmed.
157
+ * Only the atomic rename is locked; recursive removal runs on the reserved quarantine name outside it. Never touches a path that is not a
158
+ * direct, non-symlink child under the home's releases directory.
159
+ */
160
+ export function pruneReleases(homeInput: string, options: PruneOptions, deps: InventoryDeps = {}): PruneResult {
161
+ const now = (deps.now ?? Date.now)();
162
+ const inventory = listReleases(homeInput, deps);
163
+ const candidates = pruneCandidates(inventory, options, now);
164
+ const result: PruneResult = { ...inventory, candidates: candidates.map(entry => entry.path), removed: [], skipped: [], quarantined: [], applied: options.apply };
165
+ if (!options.apply || !candidates.length) return result;
166
+ const releases = join(inventory.home, "releases");
167
+ let registry: Registry | undefined;
168
+ try {
169
+ registry = openRuntimeRegistry(inventory.home).registry;
170
+ for (const entry of candidates) {
171
+ const skip = (why: string) => { result.skipped.push({ path: entry.path, why }); };
172
+ try {
173
+ const fresh = observeRuntimeReferences(inventory.home, registry);
174
+ const table = (deps.processTable ?? readProcessTable)();
175
+ const row: Raw = { path: entry.path, name: entry.name, kind: entry.kind, version: entry.version, digest: entry.digest, info: lstatSync(entry.path) };
176
+ const now = holders(row, fresh, table, deps.executingRoot ?? resolve(import.meta.dir, "../.."));
177
+ if (now.length) { skip(`now referenced by ${now.join(", ")}`); continue; }
178
+ deps.beforeRecheck?.(entry);
179
+ const staged = underRuntimeReferences(registry, fresh, () => {
180
+ const info = lstatSync(entry.path);
181
+ if (info.isSymbolicLink() || !info.isDirectory() || info.dev !== entry.identity.dev || info.ino !== entry.identity.ino || info.mtimeMs !== entry.identity.mtimeMs
182
+ || JSON.stringify(readdirSync(entry.path).sort()) !== JSON.stringify(entry.children)) throw new Error("the entry changed since it was listed; list again");
183
+ if (info.mtimeMs > Date.now() - (options.olderThanDays === undefined ? DEFAULT_MIN_AGE_MS : options.olderThanDays * 86_400_000)) throw new Error("the entry is newer than the age floor");
184
+ if (realPath(entry.path) !== entry.path || !contains(releases, entry.path) || entry.path === releases) throw new Error("the entry does not resolve under the releases directory");
185
+ const parent = resolve(entry.path, ".."), container = join(parent, `.runtime-prune-${randomUUID()}`);
186
+ mkdirSync(container, { mode: 0o700 });
187
+ renameSync(entry.path, join(container, "entry"));
188
+ return container;
189
+ });
190
+ result.removed.push(entry.path);
191
+ try { rmSync(staged, { recursive: true }); }
192
+ catch (error) { result.quarantined.push(staged); skip(`removed from releases but the quarantine ${staged} could not be deleted (${(error as Error).message}); delete it by hand, ahub doctor names it`); }
193
+ } catch (error) { skip((error as Error).message); }
194
+ }
195
+ } catch (error) { for (const entry of candidates) if (!result.removed.includes(entry.path) && !result.skipped.some(item => item.path === entry.path)) result.skipped.push({ path: entry.path, why: (error as Error).message }); }
196
+ finally { registry?.close(); }
197
+ return result;
198
+ }
package/src/hub/report.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { definitionOf } from "../adapters/registry.ts";
1
+ import { builtinDeclarationOf as definitionOf } from "../adapters/declaration-catalog.ts";
2
2
  import type { StampedEvent } from "./events.ts";
3
3
  import { addPersonEvent, emptyPersonCounts, isPersonEvent, personCoverage, personFigures, personTask, startsAttribution, UNKNOWN_PERSON_FIGURES, type PersonCounts, type PersonFigures } from "./person-figures.ts";
4
4
 
@@ -5,7 +5,7 @@ import { join } from "node:path";
5
5
  import { isModelEvidence, MODEL_EVIDENCE, parseEventLine, turnEdits, type TurnEdits, readEvents, scanEventLines, type ModelEvidence, type RoleIdentity, type StampedEvent } from "./events.ts";
6
6
  import { safeModelLabel } from "../omniroute/usage.ts";
7
7
  import { hubHome } from "./project.ts";
8
- import { ADDONS, addonState, type Addon, type AddonName } from "./tooling.ts";
8
+ import { ADDONS, addonState, type Addon, type AddonName } from "./addons.ts";
9
9
  import { MIN_ATTEMPTS, mulberry32 } from "./bench.ts";
10
10
  import { UNKNOWN_MEMORY_FIGURES } from "./research-memory.ts";
11
11
  import { addPersonEvent, emptyPersonCounts, isPersonEvent, personCoverage, personFigures, personTask, startsAttribution, type PersonCounts } from "./person-figures.ts";