@staix/agent-hub 0.50.0 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (350) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +1 -1
  3. package/docs/adding-an-ai-tool.md +26 -4
  4. package/docs/agent-notes/README.md +1 -0
  5. package/docs/agent-notes/adapters.md +4 -3
  6. package/docs/agent-notes/budget.md +8 -2
  7. package/docs/agent-notes/daemon.md +13 -8
  8. package/docs/agent-notes/local-worker.md +3 -3
  9. package/docs/agent-notes/security-review.md +6 -5
  10. package/docs/agent-notes/tasks.md +10 -3
  11. package/docs/agent-notes/tests.md +4 -3
  12. package/docs/cooperbench.md +1 -1
  13. package/docs/design/adapters.md +21 -0
  14. package/docs/design/cli-output-inventory.md +165 -150
  15. package/docs/design/cli-output.md +4 -3
  16. package/docs/design/guidance-probes.md +1 -0
  17. package/docs/design/roadmap.md +3 -1
  18. package/docs/design/task-board.md +35 -0
  19. package/docs/dogfood.md +21 -3
  20. package/docs/events.md +4 -2
  21. package/docs/memory.md +5 -3
  22. package/docs/operations.md +259 -19
  23. package/docs/quickstart.md +29 -2
  24. package/docs/roadmap.json +20 -20
  25. package/docs/roadmap.md +2 -2
  26. package/docs/roles.md +1 -1
  27. package/docs/sdlc.md +29 -5
  28. package/docs/security.md +11 -5
  29. package/docs/specs/2026-09-19-agent-hub-design.md +44 -0
  30. package/docs/specs/2026-09-19-multi-project-design.md +4 -0
  31. package/docs/specs/2026-09-20-upgrade-recovery-design.md +17 -0
  32. package/docs/specs/mcp-endpoint.md +63 -0
  33. package/docs/verification/2026-11-29-agy-1.5.20.md +33 -0
  34. package/docs/verification/2026-11-29-claude-profile-hook.md +12 -0
  35. package/docs/verification/2026-11-29-idle-daemon-footprint.md +75 -0
  36. package/docs/verification/2026-11-29-kimi-281-reviewer-compat.md +38 -0
  37. package/docs/verification/2026-11-29-kimi-tui-281.md +12 -0
  38. package/docs/verification/2026-11-30-0.51.0.md +91 -0
  39. package/docs/verification/2026-11-30-account-switch-1806.md +445 -0
  40. package/docs/verification/2026-11-30-capability-listing-shape-1808.md +45 -0
  41. package/docs/verification/2026-11-30-upgrade-keep-1807.md +174 -0
  42. package/docs/verification/2026-12-01-1811-confirmation-receipt.md +19 -0
  43. package/docs/verification/2026-12-01-1811-orca-agent-list.md +20 -0
  44. package/docs/verification/2026-12-01-1811-orca-pane-key.md +21 -0
  45. package/docs/verification/2026-12-02-1819-claude-process-after-renewal.md +54 -0
  46. package/docs/verification/2026-12-02-agy-1.5.21.md +74 -0
  47. package/docs/verification/2026-12-02-claude-implementer-2.1.334.md +44 -0
  48. package/docs/verification/2026-12-02-cli-import-graph.md +33 -0
  49. package/docs/verification/2026-12-03-0.52.0.md +150 -0
  50. package/docs/verification/2026-12-03-codex-0173-reviewer-isolation.md +53 -0
  51. package/docs/verification/2026-12-03-codex-0173-reviewer-tool-call.md +34 -0
  52. package/docs/verification/2026-12-03-jcode-1.3.0.md +25 -0
  53. package/docs/verification/agy/README.md +17 -0
  54. package/docs/verification/agy/cli-surface.ts +68 -0
  55. package/docs/verification/agy/interactive-bridge.ts +92 -0
  56. package/docs/verification/agy/interactive-session.ts +131 -0
  57. package/docs/verification/agy/launcher-nonce.ts +215 -0
  58. package/docs/verification/agy/native-hooks.ts +210 -0
  59. package/docs/verification/agy/originals/agent-hub-681/cli-surface.ts +87 -0
  60. package/docs/verification/agy/originals/agent-hub-681/native-hooks-adapted.ts +91 -0
  61. package/docs/verification/agy/originals/agent-hub-681/tui-actual.ts +200 -0
  62. package/docs/verification/agy/originals/agent-hub-684/probe.ts +107 -0
  63. package/docs/verification/agy/originals.json +25 -0
  64. package/docs/verification/agy/permission-new-functions.ts +128 -0
  65. package/docs/verification/agy/run-probe.py +108 -0
  66. package/docs/verification/agy/runtime.ts +171 -0
  67. package/docs/verification/agy/tmux-helper-control.ts +6 -0
  68. package/docs/verification/agy/tmux-session.ts +235 -0
  69. package/docs/verified.json +87 -42
  70. package/package.json +3 -3
  71. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  72. package/plugins/agent-hub/compat.json +157 -0
  73. package/plugins/agent-hub/kimi-hook.js +1416 -24985
  74. package/plugins/agent-hub/server.js +17415 -32755
  75. package/scripts/check-docs.mjs +1 -1
  76. package/src/adapters/acp.ts +13 -13
  77. package/src/adapters/agy/definition.ts +9 -26
  78. package/src/adapters/agy/entry.ts +2 -0
  79. package/src/adapters/channel-peer.ts +3 -1
  80. package/src/adapters/claude-channel-evidence.ts +7 -3
  81. package/src/adapters/claude-channel.ts +38 -257
  82. package/src/adapters/claude-implementer.ts +3 -1
  83. package/src/adapters/codex-appserver.ts +77 -15
  84. package/src/adapters/compat.ts +78 -14
  85. package/src/adapters/configured-acp.ts +23 -163
  86. package/src/adapters/configured-adapter-policy.ts +160 -0
  87. package/src/adapters/configured-pull-entry.ts +53 -0
  88. package/src/adapters/configured-pull.ts +38 -0
  89. package/src/adapters/conformance/fakes/app-server.ts +9 -2
  90. package/src/adapters/declaration-catalog.ts +25 -0
  91. package/src/adapters/declaration-data.ts +342 -0
  92. package/src/adapters/declaration-resolution.ts +53 -0
  93. package/src/adapters/definitions/builtin-metadata.ts +62 -84
  94. package/src/adapters/definitions/jcode-launch.ts +13 -0
  95. package/src/adapters/definitions/native-adapter-policy.ts +390 -0
  96. package/src/adapters/definitions/native-cli-claude-launch.ts +6 -3
  97. package/src/adapters/definitions/native-cli-codex-launch.ts +2 -1
  98. package/src/adapters/definitions/native-cli-entry-claude.ts +17 -2
  99. package/src/adapters/definitions/native-cli-entry-codex.ts +2 -0
  100. package/src/adapters/definitions/native-cli-entry-jcode.ts +6 -2
  101. package/src/adapters/definitions/native-cli-entry-kimi.ts +2 -0
  102. package/src/adapters/definitions/native-cli-entry-pi.ts +2 -0
  103. package/src/adapters/definitions/native-cli-entry-qwen.ts +2 -0
  104. package/src/adapters/definitions/native-cli-entry-types.ts +12 -3
  105. package/src/adapters/definitions/native-cli-jcode-home-init.ts +1 -1
  106. package/src/adapters/definitions/native-cli-launch-common.ts +2 -2
  107. package/src/adapters/definitions/native-cli-preview-common.ts +1 -1
  108. package/src/adapters/definitions/native-cli-retained.ts +1 -1
  109. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  110. package/src/adapters/definitions/native-configuration.ts +18 -0
  111. package/src/adapters/definitions/native-help.ts +24 -0
  112. package/src/adapters/definitions/native-launch-declarations.ts +34 -0
  113. package/src/adapters/definitions/native-launch-policy.ts +4 -0
  114. package/src/adapters/definitions/native-launch-settings.ts +72 -0
  115. package/src/adapters/definitions/native-light-cli.ts +18 -0
  116. package/src/adapters/definitions/native-light-preview.ts +10 -0
  117. package/src/adapters/definitions/native-wrapper-launch.ts +10 -0
  118. package/src/adapters/definitions/qwen.ts +6 -29
  119. package/src/adapters/definitions/reviewer-variants.ts +7 -8
  120. package/src/adapters/external-declarations.ts +31 -0
  121. package/src/adapters/external-modules.ts +4 -29
  122. package/src/adapters/jcode.ts +19 -12
  123. package/src/adapters/native-capabilities.ts +18 -8
  124. package/src/adapters/native-facts-hooks.ts +12 -0
  125. package/src/adapters/native-proof-ports.ts +1 -1
  126. package/src/adapters/presets.ts +136 -0
  127. package/src/adapters/qwen-dual.ts +2 -2
  128. package/src/adapters/registry-types.ts +3 -0
  129. package/src/adapters/registry.ts +20 -81
  130. package/src/adapters/reviewer-print.ts +26 -9
  131. package/src/adapters/role-eligibility.ts +2 -1
  132. package/src/cli/accounts-import.ts +72 -0
  133. package/src/cli/agents-latest-table.ts +88 -0
  134. package/src/cli/agents-latest.ts +22 -0
  135. package/src/cli/agents-output.ts +10 -0
  136. package/src/cli/agents-presets.ts +100 -0
  137. package/src/cli/agents.ts +1 -1
  138. package/src/cli/attention.ts +3 -2
  139. package/src/cli/autonomy-homes.ts +7 -2
  140. package/src/cli/autonomy-offline.ts +1 -1
  141. package/src/cli/bench.ts +1 -1
  142. package/src/cli/budget-renew-guidance.ts +129 -0
  143. package/src/cli/claude-homes.ts +9 -5
  144. package/src/cli/claude-profile-hook.ts +31 -11
  145. package/src/cli/command-context.ts +3 -0
  146. package/src/cli/command-table.ts +123 -0
  147. package/src/cli/commands/accounts.ts +8 -0
  148. package/src/cli/commands/agents.ts +18 -0
  149. package/src/cli/commands/answer.ts +28 -0
  150. package/src/cli/commands/ask.ts +17 -0
  151. package/src/cli/commands/autonomy.ts +83 -0
  152. package/src/cli/commands/backlog.ts +46 -0
  153. package/src/cli/commands/bench.ts +60 -0
  154. package/src/cli/commands/board.ts +48 -0
  155. package/src/cli/commands/broker.ts +9 -0
  156. package/src/cli/commands/budget.ts +96 -0
  157. package/src/cli/commands/capabilities.ts +12 -0
  158. package/src/cli/commands/check-path.ts +55 -0
  159. package/src/cli/commands/completion.ts +8 -0
  160. package/src/cli/commands/console.ts +12 -0
  161. package/src/cli/commands/daemon.ts +8 -0
  162. package/src/cli/commands/deliverables.ts +25 -0
  163. package/src/cli/commands/doctor.ts +249 -0
  164. package/src/cli/commands/down.ts +3 -0
  165. package/src/cli/commands/export.ts +15 -0
  166. package/src/cli/commands/facts.ts +15 -0
  167. package/src/cli/commands/goal.ts +22 -0
  168. package/src/cli/commands/guidance.ts +102 -0
  169. package/src/cli/commands/help.ts +17 -0
  170. package/src/cli/commands/host.ts +45 -0
  171. package/src/cli/commands/init.ts +121 -0
  172. package/src/cli/commands/instructed.ts +19 -0
  173. package/src/cli/commands/instruction-hook.ts +15 -0
  174. package/src/cli/commands/intake.ts +24 -0
  175. package/src/cli/commands/kill.ts +15 -0
  176. package/src/cli/commands/learn.ts +23 -0
  177. package/src/cli/commands/lineage.ts +30 -0
  178. package/src/cli/commands/logs.ts +21 -0
  179. package/src/cli/commands/manager.ts +15 -0
  180. package/src/cli/commands/memory.ts +21 -0
  181. package/src/cli/commands/model.ts +25 -0
  182. package/src/cli/commands/models.ts +40 -0
  183. package/src/cli/commands/native.ts +39 -0
  184. package/src/cli/commands/pause.ts +5 -0
  185. package/src/cli/commands/peer.ts +32 -0
  186. package/src/cli/commands/permission.ts +26 -0
  187. package/src/cli/commands/permit.ts +12 -0
  188. package/src/cli/commands/pet.ts +24 -0
  189. package/src/cli/commands/projects.ts +49 -0
  190. package/src/cli/commands/queue.ts +70 -0
  191. package/src/cli/commands/recovery-run.ts +13 -0
  192. package/src/cli/commands/recovery.ts +130 -0
  193. package/src/cli/commands/release.ts +23 -0
  194. package/src/cli/commands/releases.ts +91 -0
  195. package/src/cli/commands/remember.ts +6 -0
  196. package/src/cli/commands/report.ts +27 -0
  197. package/src/cli/commands/research.ts +53 -0
  198. package/src/cli/commands/reset.ts +89 -0
  199. package/src/cli/commands/restart.ts +5 -0
  200. package/src/cli/commands/results.ts +31 -0
  201. package/src/cli/commands/resume.ts +5 -0
  202. package/src/cli/commands/review.ts +24 -0
  203. package/src/cli/commands/roadmap.ts +21 -0
  204. package/src/cli/commands/role.ts +34 -0
  205. package/src/cli/commands/roles.ts +30 -0
  206. package/src/cli/commands/room.ts +14 -0
  207. package/src/cli/commands/roster.ts +48 -0
  208. package/src/cli/commands/route.ts +9 -0
  209. package/src/cli/commands/say.ts +21 -0
  210. package/src/cli/commands/schedule.ts +17 -0
  211. package/src/cli/commands/sdlc.ts +321 -0
  212. package/src/cli/commands/settings.ts +148 -0
  213. package/src/cli/commands/setup.ts +89 -0
  214. package/src/cli/commands/shared-refusals.ts +25 -0
  215. package/src/cli/commands/smoke.ts +44 -0
  216. package/src/cli/commands/source.ts +64 -0
  217. package/src/cli/commands/specs.ts +13 -0
  218. package/src/cli/commands/status.ts +28 -0
  219. package/src/cli/commands/stop.ts +17 -0
  220. package/src/cli/commands/structure.ts +60 -0
  221. package/src/cli/commands/study.ts +39 -0
  222. package/src/cli/commands/tail.ts +19 -0
  223. package/src/cli/commands/task.ts +114 -0
  224. package/src/cli/commands/title.ts +17 -0
  225. package/src/cli/commands/turns.ts +10 -0
  226. package/src/cli/commands/ui.ts +47 -0
  227. package/src/cli/commands/undo.ts +77 -0
  228. package/src/cli/commands/up.ts +39 -0
  229. package/src/cli/commands/upgrade.ts +5 -0
  230. package/src/cli/commands/usage.ts +33 -0
  231. package/src/cli/commands/version.ts +5 -0
  232. package/src/cli/commands/watch.ts +30 -0
  233. package/src/cli/commands/worktrees.ts +31 -0
  234. package/src/cli/conductor-recovery.ts +1 -1
  235. package/src/cli/console-state.ts +5 -138
  236. package/src/cli/console-versions.ts +1 -1
  237. package/src/cli/facts-hook.ts +11 -4
  238. package/src/cli/help.ts +44 -20
  239. package/src/cli/identity.ts +27 -4
  240. package/src/cli/init-prompt.ts +1 -1
  241. package/src/cli/init-settings.ts +4 -35
  242. package/src/cli/init.ts +1 -1
  243. package/src/cli/json-text-spans.ts +57 -0
  244. package/src/cli/launch-check.ts +156 -0
  245. package/src/cli/launch.ts +19 -70
  246. package/src/cli/light-dispatch.ts +29 -0
  247. package/src/cli/main.js +8 -1
  248. package/src/cli/main.ts +257 -2799
  249. package/src/cli/memory.ts +1 -1
  250. package/src/cli/orca-probe.ts +119 -0
  251. package/src/cli/output.ts +45 -3
  252. package/src/cli/preview.ts +11 -6
  253. package/src/cli/recovery-launch.ts +1 -1
  254. package/src/cli/recovery-version-preflight.ts +28 -9
  255. package/src/cli/replace-process.ts +22 -0
  256. package/src/cli/report-layout.ts +142 -0
  257. package/src/cli/roadmap-usage.ts +16 -0
  258. package/src/cli/roadmap.ts +3 -16
  259. package/src/cli/sdlc-doctor.ts +27 -0
  260. package/src/cli/sdlc-output.ts +55 -1
  261. package/src/cli/setup-homes.ts +2 -2
  262. package/src/cli/start-agents-run.ts +85 -7
  263. package/src/cli/start-check.ts +28 -0
  264. package/src/cli/statusline-tee.ts +25 -4
  265. package/src/cli/terminal-recovery.ts +53 -10
  266. package/src/cli/upgrade-interactive.ts +1 -0
  267. package/src/cli/upgrade-runtime.ts +12 -1
  268. package/src/cli/upgrade.ts +4 -15
  269. package/src/cli/warn-line.ts +1 -1
  270. package/src/hub/accounts.ts +148 -0
  271. package/src/hub/addons.ts +20 -0
  272. package/src/hub/agent-drift.ts +2 -1
  273. package/src/hub/budget-projection.ts +39 -7
  274. package/src/hub/budget.ts +231 -16
  275. package/src/hub/channel-project.ts +3 -3
  276. package/src/hub/ci-watch.ts +311 -79
  277. package/src/hub/conductor-peer.ts +24 -0
  278. package/src/hub/conductor.ts +2 -21
  279. package/src/hub/config-apply.ts +25 -14
  280. package/src/hub/config-edit.ts +1 -1
  281. package/src/hub/config-tier.ts +2 -0
  282. package/src/hub/config.ts +535 -0
  283. package/src/hub/control-client.ts +49 -1
  284. package/src/hub/daemon.ts +492 -569
  285. package/src/hub/delivery-public.ts +11 -0
  286. package/src/hub/events.ts +3 -0
  287. package/src/hub/home-tag.ts +12 -0
  288. package/src/hub/host.ts +217 -0
  289. package/src/hub/hub-check.ts +125 -0
  290. package/src/hub/hub-tools.ts +2 -1
  291. package/src/hub/instance-budget.ts +2 -2
  292. package/src/hub/instance-config.ts +15 -126
  293. package/src/hub/instances.ts +22 -6
  294. package/src/hub/instruction-receipt.ts +2 -2
  295. package/src/hub/kimi-usage.ts +38 -11
  296. package/src/hub/lifecycle.ts +86 -4
  297. package/src/hub/mcp-bridge-core.ts +98 -0
  298. package/src/hub/mcp-channel-push.ts +20 -0
  299. package/src/hub/mcp-endpoint-serve.ts +178 -0
  300. package/src/hub/mcp-endpoint.ts +226 -0
  301. package/src/hub/mcp-tool-call.ts +181 -0
  302. package/src/hub/operational-settings.ts +2 -0
  303. package/src/hub/orca-env.ts +6 -0
  304. package/src/hub/orca-state.ts +84 -0
  305. package/src/hub/path-policy.ts +1 -1
  306. package/src/hub/peers.ts +5 -1
  307. package/src/hub/permission-mode.ts +5 -41
  308. package/src/hub/permission-paths.ts +41 -0
  309. package/src/hub/project.ts +20 -0
  310. package/src/hub/protocol-window.ts +58 -0
  311. package/src/hub/quota-origin.ts +20 -0
  312. package/src/hub/recovery-policy.ts +1 -1
  313. package/src/hub/registry.ts +36 -2
  314. package/src/hub/releases-inventory.ts +198 -0
  315. package/src/hub/report.ts +1 -1
  316. package/src/hub/research.ts +1 -1
  317. package/src/hub/review-brief.ts +47 -2
  318. package/src/hub/roster.ts +6 -3
  319. package/src/hub/routing.ts +9 -2
  320. package/src/hub/runtime-capture-prune.ts +25 -3
  321. package/src/hub/runtime-prune-health.ts +8 -1
  322. package/src/hub/sdlc-check.ts +205 -0
  323. package/src/hub/sdlc-release-authorization.ts +42 -21
  324. package/src/hub/sdlc-release-diagnostics.ts +5 -0
  325. package/src/hub/sdlc-release-policy.ts +21 -7
  326. package/src/hub/sdlc-release.ts +80 -20
  327. package/src/hub/sdlc-sync.ts +146 -0
  328. package/src/hub/sdlc.ts +38 -5
  329. package/src/hub/settings.ts +7 -4
  330. package/src/hub/start-agents.ts +1 -1
  331. package/src/hub/start-mode.ts +11 -4
  332. package/src/hub/structure-budget.ts +131 -0
  333. package/src/hub/structure-scan.ts +149 -0
  334. package/src/hub/tasks-experiment.ts +455 -0
  335. package/src/hub/tasks-guidance.ts +606 -0
  336. package/src/hub/tasks-roadmap-plan.ts +419 -0
  337. package/src/hub/tasks-roadmap.ts +491 -0
  338. package/src/hub/tasks-study.ts +661 -0
  339. package/src/hub/tasks-survey.ts +192 -0
  340. package/src/hub/tasks.ts +457 -2584
  341. package/src/hub/terminal-open.ts +5 -3
  342. package/src/hub/tooling.ts +3 -19
  343. package/src/hub/usage-rollup.ts +9 -3
  344. package/src/local/tools.ts +5 -0
  345. package/src/ui/index.html +1 -1
  346. package/src/ui/needs.ts +17 -5
  347. package/src/ui/peer-palette.ts +2 -4
  348. package/src/ui/plugin.ts +1 -1
  349. package/templates/presets/agents.json +60 -0
  350. package/templates/presets/confirmation-matrix.json +8 -8
package/src/hub/daemon.ts CHANGED
@@ -7,7 +7,7 @@ import { parseGuidanceCreateInput, parseGuidanceIdQuery } from "./guidance-varia
7
7
  import { GuidanceProbeStore } from "./guidance-probe-store.ts";
8
8
  import { GuidanceProbeError, probeSessionGeneration, probeSha256, type ProbePublicReceipt, type ProbePublicStatus, type ProbeReceiptExport } from "./guidance-probes.ts";
9
9
  import { executionText, EXECUTION_REFERENCE_LIMITS } from "./execution-reference.ts";
10
- import { publicDeliveryBodies } from "./delivery-public.ts";
10
+ import { publicDeliveryBodies, publicDeliveryReason } from "./delivery-public.ts";
11
11
  import { GeneratedNoteRegistry, type GeneratedNoteProof } from "../memory/record-provenance.ts";
12
12
  import { RecordCapture, type RecordCapturePolicy } from "../memory/records.ts";
13
13
  import { VisualStore, validateVisualInput, validateVisualPayload, VISUAL_ID_PATTERN, type VisualRecord, type VisualSummary } from "./visual.ts";
@@ -22,7 +22,7 @@ import type { ActionMeta } from "@staix/agent-console/contract";
22
22
  import { isReviewObserverExcluded, reviewCaptureExcluded } from "./memory-policy.ts";
23
23
  import { RoomStoreError } from "../rooms/store.ts";
24
24
  import { RoomCommands, RoomRotationHoldError, type RoomPreview } from "../rooms/commands.ts";
25
- import { queueBackpressurePolicy, type QueueBackpressurePolicy } from "./queue-backpressure.ts";
25
+ import { queueBackpressurePolicy } from "./queue-backpressure.ts";
26
26
  import { RoomChat, type RoomInvocationIngress } from "../rooms/service.ts";
27
27
  import { RoomInvocations, roomInvocationHash } from "./room-invocations.ts";
28
28
  import { parseRemotePeerId, roomInvocationArgs, encodeRoomInvocationBody, type RoomReadInvocationRequest } from "../rooms/application.ts";
@@ -44,15 +44,17 @@ import { createClaudeFailureTrace, type ClaudeFailureTrace } from "./claude-fail
44
44
  import { buildNativePermissionProbe, NATIVE_PERMISSION_PROBE_MAX_PER_LAUNCH, validateNativePermissionRequest } from "./native-permission-request.ts";
45
45
  import { createClaudeLaunchProof, readClaudeLaunchProof } from "./claude-launch-proof.ts";
46
46
  import { InboxPolling } from "./inbox-polling.ts";
47
- import { ActionBudgets, actionPolicyConfig, floorEnforcement, floorReads, type ActionPolicyConfig } from "./action-policy.ts";
47
+ import { ActionBudgets, floorEnforcement, floorReads } from "./action-policy.ts";
48
48
  import { actionGate, claudeActionClasses } from "./action-enforce.ts";
49
49
  import type { FloorFacts } from "./action-class.ts";
50
50
  import { ReleaseAuthorizations, releaseAuthorizationError } from "./sdlc-release-authorization.ts";
51
51
  import { readCommittedReleasePolicy } from "./sdlc-release-policy.ts";
52
52
  import { parseReleaseGuardArgv, parseReleasePushUpdates } from "../cli/sdlc-release-guard.ts";
53
53
  import type { DocEvidence, ReleaseReportPolicy } from "./sdlc-release.ts";
54
- import { loadExternalAdapterDefinitions, readAdapterModuleDeclarations, externalModuleIdentity, externalModuleIdentityCurrent, type AdapterModuleDeclaration } from "../adapters/external-modules.ts";
54
+ import { loadExternalAdapterDefinitions, readAdapterModuleDeclarations, externalModuleIdentity, externalModuleIdentityCurrent } from "../adapters/external-modules.ts";
55
55
  import { WsPeer, isWsPeer } from "../adapters/channel-peer.ts";
56
+ import { homeTag } from "./home-tag.ts";
57
+ import { accountKey, accountKeyFor, baseAccount, handoffEvents, handoffSiblings, instanceAccountEnv as instanceAccountEnvOf, isClaudeAccountKind, isDeclaredReading, DEFAULT_ACCOUNT_LABEL, labelForHome } from "./accounts.ts";
56
58
  import { ownerToolEffect, canonicalWriteUnknown } from "./no-writes.ts";
57
59
  import { NativeHookLaunches, type NativeHookLaunch } from "./native-hook-launch.ts";
58
60
  import { InstructionReceipts, MAX_PROMPT_BYTES } from "./instruction-receipt.ts";
@@ -60,7 +62,7 @@ import { Registry } from "./registry.ts";
60
62
  import { usedClaudeHomes } from "../cli/autonomy-homes.ts";
61
63
  import { readReleaseHostAdmission, type ReleaseHostAdmission } from "./release-admission.ts";
62
64
  import { MERGE_READBACK_INTERVAL_MS } from "./sdlc-merge.ts";
63
- import { ContainerRunner, RemoteRunner, remoteRunnerConfig, type RemoteRunnerConfig, type RunnerOptions, type RunnerState, type RunReceipt } from "./check-runner.ts";
65
+ import { ContainerRunner, RemoteRunner, type RunnerOptions, type RunnerState, type RunReceipt } from "./check-runner.ts";
64
66
  import { fetchSpec, specAvailable, specRefs } from "./spec-read.ts";
65
67
  import { readbackAcceptField } from "./spec-readback.ts";
66
68
  import { isDenied, sbplString } from "../local/deny.ts";
@@ -72,41 +74,50 @@ import { correctionInput, MemoryTelemetry } from "./memory-candidates.ts";
72
74
  import { MemoryObservations } from "./memory-observations.ts";
73
75
  import { createStalenessProbe } from "./memory-staleness.ts";
74
76
  import { matchingPlanFails, planGuardNodes, taskMemoryQueryNodes } from "./memory-plan-guard.ts";
75
- import { planningWipLimits } from "./planning.ts";
76
77
  import { ToolWriteRegistry, toolWriteOperation, toolWriteUnknownReply } from "./tool-request.ts";
77
78
  import { ControlWriteTelemetry, controlWriteMetadata, controlWriteSpan } from "./control-write-trace.ts";
78
79
  import { projectedDiff } from "./projected-diff.ts";
79
80
  import { listenWithoutPortCollision } from "./listen.ts";
80
81
  import { needs, type NeedsInput } from "../ui/needs.ts";
81
82
  import { overviewModel } from "../ui/overview-model.ts";
82
- import { loadPetConfig, PET_WINDOW_RETIRED_NOTICE, stripLegacyPetWindow } from "../pet/config.ts";
83
- import { projectionConfig, TextProjections, type ProjectionConfig } from "./text-projection.ts";
83
+ import { loadPetConfig } from "../pet/config.ts";
84
+ import { TextProjections } from "./text-projection.ts";
84
85
  import { policyPaths, policyRealPath, matchesPolicy } from "./path-policy.ts";
85
86
  import { CodeFacts, type CodeFactResult, type CodeSymbol } from "./code-facts.ts";
86
87
  import { gitAuditSource, checkoutAuditSource } from "./audit-source.ts";
87
88
  import { buildReviewBrief, withCodeSymbols } from "./review-brief.ts";
88
- import { profileName, projectProfile, resolveProfile, mergeProfileOverrides, type ProfileName } from "./profiles.ts";
89
+ import { structureNotice } from "./structure-budget.ts";
90
+ import { readStructureBaseline, scanStructure } from "./structure-scan.ts";
91
+ import { profileName, projectProfile, resolveProfile } from "./profiles.ts";
89
92
  import { catalogAssignments, loadRoleCatalog, selectedRoles, roleIdentity } from "./roles.ts";
90
93
  import { ActivityRing } from "./activity.ts";
91
- import { JcodeOptionMismatch, JcodeTuiRefusal, isJcodePeer, jcodeDetachedNotice, jcodeToolCeilingCause, jcodeVersionAsync, type JcodePeer } from "../adapters/jcode.ts";
94
+ import { buildHubCheck, expectedHubLink } from "./hub-check.ts";
95
+ import { JcodeOptionMismatch, JcodeTuiRefusal, isJcodePeer, jcodeDetachedNotice, jcodeToolCeilingCause, jcodeVersionAsync, refusedHelloProcess, type JcodePeer } from "../adapters/jcode.ts";
92
96
  import { VERSION_REFUSAL, configuredCommands, describe, isCompatId } from "../adapters/compat.ts";
93
97
  import { agentVersionsAsync, type AgentVersionRow } from "../cli/agents.ts";
94
98
  import { driftedAgents, noticeDrift, type DriftedAgent } from "./agent-drift.ts";
95
99
  import { jcodeMcpReady } from "../cli/jcode-mcp.ts";
96
- import { loadSdlc, readSpecEdit, sdlcGh, type SdlcConfig, type SdlcGh } from "./sdlc.ts";
100
+ import { loadSdlc, readSpecEdit, sdlcConfig, sdlcGh, type SdlcConfig, type SdlcGh } from "./sdlc.ts";
101
+ import { runSdlcCheck } from "./sdlc-check.ts";
102
+ import { planSdlcSync } from "./sdlc-sync.ts";
103
+ import { startMcpEndpoint, type McpEndpoint, type McpHello, type McpSessionServer } from "./mcp-endpoint.ts";
104
+ import { ListedTools, PushBuffers, serveMcpSession } from "./mcp-endpoint-serve.ts";
105
+ import { requiredChecksFor } from "./sdlc-merge.ts";
106
+ import { discoverInitChecks } from "../cli/init-required-checks.ts";
97
107
  import { claudePeer as defaultChannelPeer, claudeStateFile, isClaudeSessionUuid, ownTerminalRow, pathEvidence, transcriptPersisted } from "./claude-state.ts";
98
108
  import { peerRosterConfig, rosterAllows, staleInstanceKey, type PeerRoster } from "./roster.ts";
99
109
  import { KNOWN_PEERS, OPTIONAL_PEERS, PLANNER_PEERS, SUPPORTED_PEERS, START_MODE_PEERS, isSupportedPeer, STARTABLE_PEERS, isStartablePeer } from "../adapters/registry.ts";
100
110
  import { RecoveryDeferredHubError } from "./deferred-hub.ts";
101
111
  import { databaseBusySite, isDatabaseBusy, RecoveryDatabaseBusy } from "./recovery-error.ts";
102
- import { ADAPTERS, DEFAULT_REVIEW_POOL, REVIEW_POOL_KINDS, QUOTA_HANDOFF_PLATFORMS, NATIVE_CONFIG_BLOCKS, nativeConfigurationDefaults, mergeNativeConfiguration, retainNativeRouting, DAEMON_PORTS, definitionOf, createProjectAdapterCatalog, isFixedBuiltinDefinition } from "../adapters/registry.ts";
112
+ import { ADAPTERS, DEFAULT_REVIEW_POOL, REVIEW_POOL_KINDS, QUOTA_HANDOFF_PLATFORMS, retainNativeRouting, DAEMON_PORTS, definitionOf, createProjectAdapterCatalog, isFixedBuiltinDefinition } from "../adapters/registry.ts";
103
113
  import { isSupportedPeer as registrySupportedPeer, definitionOf as builtinDefinitionOf, KNOWN_PEERS as BASE_KNOWN_PEERS, SUPPORTED_PEERS as BASE_SUPPORTED_PEERS, STARTABLE_PEERS as BASE_STARTABLE_PEERS } from "../adapters/registry.ts";
104
114
  import type { NativeFactsTranscript } from "../adapters/registry-types.ts";
105
115
  import type { ReviewScope } from "./review-scope.ts";
106
116
  import { checkJcodeInstanceHomes, instanceDefinitionOf, effectiveInstanceRoles, isPlannerOnly, instancePeerIds, validateInstances, type InstancesConfig } from "./instances.ts";
107
- import { INSTANCE_CONFIG_FILES, readInstanceConfig, withoutInertInstancePolicy, readInstanceConfigLayers, readInstanceRoleConfig } from "./instance-config.ts";
117
+ import { readInstanceConfig, readInstanceConfigLayers, readInstanceRoleConfig } from "./instance-config.ts";
108
118
  import { instanceBudgetHooks, projectBudgetHeadroom } from "./instance-budget.ts";
109
119
  import { resolveInstanceExecutionCwd } from "./instance-execution.ts";
120
+ import { presetStatusById } from "../adapters/presets.ts";
110
121
  import { ProgressObserver, normalizeCodexObservation, normalizeClaudeObservation } from "./progress.ts";
111
122
  import type { NativeToolObservation as ToolObservation } from "./progress.ts";
112
123
  import { createHash, randomBytes, randomUUID } from "node:crypto";
@@ -116,14 +127,13 @@ import { homedir } from "node:os";
116
127
  import { spawn } from "node:child_process";
117
128
  import { childEnv, personEnv } from "./child-process.ts";
118
129
  import { runCheck } from "./checks.ts";
119
- import { DEFAULT_TASK_SWEEP, taskSweepConfig, type TaskSweepConfig } from "./task-sweep.ts";
120
- import { CONTRADICTION_WINDOW_SETTING, DEMOTE_AT_SETTING, DEMOTION_HALF_LIFE_SETTING, GROOM_FYI_WINDOW_SETTING, RESCREEN_MAX_SETTING, SPLIT_FAILURE_SHARE_SETTING, SPLIT_MIN_SETTING, taskOperationalReaders } from "./operational-settings.ts";
121
- import { CONSOLE_POLL_SETTING, CONSOLE_NOTICE_SETTING, CONSOLE_HISTORY_SETTING, CONSOLE_PENDING_STREAM_SETTING, CONSOLE_ATTENTION_SETTING, type ConsoleOperationalConfig } from "./operational-settings.ts";
122
- import { MODEL_COOLDOWN_FAILURES_SETTING, MODEL_COOLDOWN_SETTING, MODEL_COOLDOWN_CAP_SETTING, MODEL_TERMINAL_HISTORY_SETTING, modelOperationalReaders, type ModelOperationalConfig } from "./operational-settings.ts";
123
- import { ACP_TOOL_CEILING_SETTING, ACP_ACTIVITY_BATCH_SETTING, JCODE_STEER_TIMEOUT_SETTING, adapterOperationalReaders, type AdapterTimingConfig } from "./operational-settings.ts";
124
- import { BUS_ACCEPTED_SETTLE_MS_SETTING, BUS_DIGEST_MAX_SETTING, BUS_MAX_ATTEMPTS_SETTING, BUS_NOTES_KEPT_SETTING, BUS_PULL_BUDGET_BYTES_SETTING, BUS_TERMINAL_HISTORY_LIMIT_SETTING, busOperationalReaders, RECOVERY_CONTROL_TIMEOUT_SETTING, RECOVERY_RECONNECT_WAIT_SETTING, RECOVERY_SHUTDOWN_WAIT_SETTING, RECOVERY_TERMINAL_IDLE_WAIT_SETTING, RECOVERY_UNMANAGED_RECONNECT_WAIT_SETTING } from "./operational-settings.ts";
125
- import { foldersConfig, scheduleKeyOf, scheduleViews, schedulesConfig, ScheduleStore, type FolderEntry, type ScheduleEntry } from "./schedules.ts";
126
- import { MEMORY_REVIEW_DEFAULTS, MEMORY_REVIEW_SCHEDULE_ID, memoryReviewConfig, memoryReviewCountLine, memoryReviewEntry, memoryReviewScope, memoryReviewTask, reviewBudgetNote, reviewBudgetStop, reviewCheckpointRequest, type MemoryReviewConfig, type ReviewSpend } from "./memory-review.ts";
130
+ import { taskSweepConfig } from "./task-sweep.ts";
131
+ import { GROOM_FYI_WINDOW_SETTING, taskOperationalReaders } from "./operational-settings.ts";
132
+ import { modelOperationalReaders } from "./operational-settings.ts";
133
+ import { adapterOperationalReaders } from "./operational-settings.ts";
134
+ import { busOperationalReaders } from "./operational-settings.ts";
135
+ import { scheduleKeyOf, scheduleViews, ScheduleStore, type ScheduleEntry } from "./schedules.ts";
136
+ import { MEMORY_REVIEW_DEFAULTS, MEMORY_REVIEW_SCHEDULE_ID, memoryReviewCountLine, memoryReviewEntry, memoryReviewScope, memoryReviewTask, reviewBudgetNote, reviewBudgetStop, reviewCheckpointRequest, type ReviewSpend } from "./memory-review.ts";
127
137
  import { FolderStore, registerScanned, scanFolder, type FolderPolicy } from "./folder-trigger.ts";
128
138
  import { QuestionStore, QUESTION_SURFACES, questionView } from "./questions.ts";
129
139
  import { RunTracker, outcomeOf, settleVerdict, type Run } from "./completions.ts";
@@ -131,15 +141,13 @@ import { resultDetail, type ResultDetail } from "./completion-detail.ts";
131
141
  import { CompletionStore } from "./completions-store.ts";
132
142
  import { QuestionDesk } from "./question-desk.ts";
133
143
  import type { ScannedFile } from "./schedules.ts";
134
- import { corpusConfig } from "./corpus-config.ts";
135
- import { roadmapConfig, type MilestoneLinkKind, type MilestoneState, type RoadmapConfig } from "./roadmap.ts";
136
- import { mcpAllowNames } from "./instances.ts";
137
- import { ALL_MACHINE_LOCAL, configRefusal, configRepositoryPresent, configTracked, stripUntrusted } from "./config-trust.ts";
138
- import { instructedMode, parseExactInstruction, exactForm, instructedExecution, INSTRUCTION_CHILD_TIMEOUT_MS, type ExactForm, type InstructedExecution } from "./instructed-exact.ts";
144
+ import { roadmapConfig, type MilestoneLinkKind, type MilestoneState } from "./roadmap.ts";
145
+ import { ALL_MACHINE_LOCAL, configRefusal, configRepositoryPresent, configTracked } from "./config-trust.ts";
146
+ import { parseExactInstruction, exactForm, instructedExecution, INSTRUCTION_CHILD_TIMEOUT_MS, type ExactForm, type InstructedExecution } from "./instructed-exact.ts";
139
147
  import { intentForm, intentRefusal, literalInstructionIds } from "./instructed-intent.ts";
140
148
  import { instructedRuntimeAllowed } from "./instructed-runtime.ts";
141
149
  import { classifyPeerCommand, cliCommandLabel } from "../cli/identity.ts";
142
- import { authorizeConfigLeaf, configApply, configIdentityScope, configChanges, validateRawConfig, validateEffectiveConfig, validateOperationalConfig, validatePetConfig } from "./config-apply.ts";
150
+ import { authorizeConfigLeaf, configApply, configIdentityScope, configChanges, validateRawConfig, validateEffectiveConfig } from "./config-apply.ts";
143
151
  import { resolveSettledRoles } from "./settled-roles.ts";
144
152
  import { CONFIG_SOURCE_FILES, configFingerprint, configSourceTexts, parseConfigSources, type ConfigSourceTexts, type ConfigSources } from "./config-reload.ts";
145
153
  import { issueConductorRecoveryAuthority, authorizeConductorRecovery, assertConductorRecovery, RecoveryAuthorityError, type ConductorRecoveryBinding } from "./recovery-authority.ts";
@@ -159,13 +167,13 @@ import { budgetNotes, type BudgetPeerNote } from "./budget-notes.ts";
159
167
  import { kimiRowTotal } from "../adapters/kimi-wire-usage.ts";
160
168
  import { ExecutionBudget } from "./execution-budget.ts";
161
169
  import { claudeReportedTokens, readClaudeTranscriptCompletion, readClaudeTranscriptUsage, waitForClaudeCompletion } from "./usage.ts";
162
- import type { ServerWebSocket } from "bun";
170
+ import type { ServerWebSocket, WebSocketHandler } from "bun";
163
171
  import { isAcpPeer, managedAcpLaunch, verifyManagedAcpLaunch, type AcpOptions, type AcpPeer, QwenIdentityError, ACTION_BUDGET_OPTION, type PermissionRequest, type ActionGateVerdict } from "../adapters/acp.ts";
164
- import { isCodexPeer, type CodexPeer } from "../adapters/codex-appserver.ts";
172
+ import { compareNextCodexQuotaHome, isCodexPeer, type CodexPeer } from "../adapters/codex-appserver.ts";
165
173
  import { isPiPeer, PiVersionRefusal, type PiPeer } from "../adapters/pi.ts";
166
174
  import { isQwenDualPeer, qwenDualVersionAsync, type QwenDualPeer } from "../adapters/qwen-dual.ts";
167
175
  import { startModelRelay, type ModelRelay } from "../models/relay.ts";
168
- import { ensureMlx, type MlxOptions } from "../models/mlx.ts";
176
+ import { ensureMlx } from "../models/mlx.ts";
169
177
  import { PiToolReceipts, packPiShellResult } from "../pi/tool-receipts.ts";
170
178
  import { preparePiDependencies } from "../pi/task-dependencies.ts";
171
179
  import { publishPiDependencies } from "../pi/dependency-publish.ts";
@@ -193,28 +201,28 @@ import { isReviewerPrintPeer, reviewerNoVerdictLine, reviewerUnavailableReason,
193
201
  import type { OwnedInputContext } from "../adapters/claude-print-child.ts";
194
202
  import { createReviewerMcpSession, type ReviewerToolName } from "../adapters/reviewer-mcp.ts";
195
203
  import { reviewerPoolConfig } from "./reviewer-pool-config.ts";
196
- import { DEFAULT_REVIEW_GATE, DEFAULT_REVIEW_MAX_MINUTES, DEFAULT_REVIEW_UNKNOWN_QUOTA, reviewBudgetPolicyDescription, type ReviewGate, type ReviewUnknownQuota, reviewerAccountingIntegrity, reviewerAccountingRelevant } from "./review-budget.ts";
204
+ import { DEFAULT_REVIEW_GATE, DEFAULT_REVIEW_MAX_MINUTES, DEFAULT_REVIEW_UNKNOWN_QUOTA, reviewBudgetPolicyDescription, reviewerAccountingIntegrity, reviewerAccountingRelevant } from "./review-budget.ts";
197
205
  import { reviewDiff } from "../adapters/claude-print.ts";
198
206
  import { Capture } from "../memory/capture.ts";
199
- import { DEFAULT_OMNIROUTE, OmniRoute, type OmniRouteConfig } from "../omniroute/client.ts";
207
+ import { OmniRoute } from "../omniroute/client.ts";
200
208
  import { CorpusIndex } from "./corpus.ts";
201
209
  import { corpusEvidence } from "./corpus-evidence.ts";
202
210
  import { Briefs, preferRecordItems, type NativeItem, type BriefTask } from "../memory/brief.ts";
203
211
  import { Board, isClosedTaskState, taskProposalAt, taskHasStarted, CLASSES, type Task, type TaskClass } from "./board.ts";
204
212
  import { UsageRollup, USAGE_GROUPS, LIMITS_MAX, type UsageGroup } from "./usage-rollup.ts";
205
- import { Budget, readNativeQuota, DEFAULT_BUDGET, type BudgetConfig } from "./budget.ts";
206
- import { projectExhaustion, windowLeft, WINDOW_MINS, type ExhaustionProjection } from "./budget-projection.ts";
213
+ import { Budget, readNativeQuota } from "./budget.ts";
214
+ import { earlyBudgetWarning, projectExhaustion, windowLeft, WINDOW_MINS, type ExhaustionProjection } from "./budget-projection.ts";
207
215
  import { remoteEnvelope, HUB } from "./envelope.ts";
208
216
  import { applyTurnAttribution, turnAttribution } from "./turn-attribution.ts";
209
217
  import { recallMemoryLines, trimToTokens, aggregateUse, orderByUse } from "../memory/recall.ts";
210
218
  import { closeSync, constants as fsConstants, openSync, lstatSync, readSync, statSync } from "node:fs";
211
219
  import { basename, isAbsolute } from "node:path";
212
220
  import { fileURLToPath } from "node:url";
213
- import { canonicalPath, realPath, hubHome } from "./project.ts";
221
+ import { canonicalPath, realPath, hubHome, daemonProjectContext, projectChildEnv, type DaemonProjectContext } from "./project.ts";
214
222
  import { HandoffRefusal, checkTarget, handoffAge, handoffCatchUpRow, handoffChunks, handoffConnectFailure, handoffLogGate, handoffOutcomeUnknown, handoffReach, handoffStateGate, handoffTargetStopped, parseHandoff, resolveTarget, handoffEventFor, type HandoffEvent } from "./handoff.ts";
215
223
  import { mainCheckoutBranch, mainCheckoutWarning } from "./main-checkout.ts";
216
224
  import type { BusEvent, PublishResult } from "./bus.ts";
217
- import { QUESTION_TOOLS, CONDUCTOR_TOOLS, CONDUCTOR_TOOL_NAMES, DEFAULT_ROLES, IMPLEMENTER_HUB_TOOL_NAMES, roleContract, TASK_TOOL_NAMES, TASK_TOOLS, BOUNDED_TASK_TOOLS, LINEAGE_TOOL_NAMES, GUIDANCE_TOOL_NAMES, CAPABILITY_TOOLS, profileTaskTools, sessionTitleTools } from "./hub-tools.ts";
225
+ import { QUESTION_TOOLS, CONDUCTOR_TOOLS, CONDUCTOR_TOOL_NAMES, IMPLEMENTER_HUB_TOOL_NAMES, roleContract, TASK_TOOL_NAMES, TASK_TOOLS, BOUNDED_TASK_TOOLS, LINEAGE_TOOL_NAMES, GUIDANCE_TOOL_NAMES, CAPABILITY_TOOLS, DEFAULT_ROLES, profileTaskTools, sessionTitleTools } from "./hub-tools.ts";
218
226
  import { effectiveClass, listedCapabilities, PublishRefusal, readShare, shareView, validatePublished, type CapabilityManifest } from "./capabilities.ts";
219
227
  import { invocationApproval, checkArgs, DEFAULT_TIMEOUT_S, InvocationLedger, invocationRefusal, refusedBy, renderInvocationResult, requestText, type InvocationOutcome, type InvocationRow } from "./invocations.ts";
220
228
  import { Conductor, ConductorHolds, conductorPeer, requireConductor, conductorProgressSink, publicConductorTask, publicPeerBudget, taskShowAllowed, type ConductEvent } from "./conductor.ts";
@@ -224,9 +232,9 @@ import { ProposalStore, SupervisionProposals, type SupervisionProposal } from ".
224
232
  import { drainCliAudits } from "../cli/identity-audit.ts";
225
233
  import { launcherPreview } from "../cli/preview.ts";
226
234
  import { AssignmentUndeliveredError, ESCALATE_AFTER, Tasks } from "./tasks.ts";
227
- import { DEFAULT_INFERENCE, DIGEST, Inference, SCREEN_MAX_BYTES, SCREEN_TIMEOUT_MS, screenPii, type InferenceConfig, type PiiVerdict } from "./inference.ts";
235
+ import { DIGEST, Inference, SCREEN_MAX_BYTES, SCREEN_TIMEOUT_MS, screenPii, type PiiVerdict } from "./inference.ts";
228
236
  import { taskEvidencePrivacy, type TaskEvidencePrivacy, ask, ASK_NOTE_TITLE, RUN_START } from "./ask.ts";
229
- import { currentRouting, loadRouting, detectSignals, OVERLAY_FILE, overlayToml, parseRouting, routingText, type Routing } from "./routing.ts";
237
+ import { currentRouting, detectSignals, OVERLAY_FILE, overlayToml, parseRouting, routingText, type Routing } from "./routing.ts";
230
238
  import { withChecklistLine, withoutChecklistLine } from "./learning.ts";
231
239
  import { FOLLOWUP_DEFAULTS } from "./learn-followup.ts";
232
240
  import { autonomyConsentStateDir, createAutonomyConsent, type AutonomyConsentValues } from "./autonomy-consent.ts";
@@ -246,40 +254,39 @@ import { assertHubDbCompatible } from "./db-schema.ts";
246
254
  import { startDashboard, dashboardView, type DashboardSession } from "./ui.ts";
247
255
  import { codeGroup } from "./task-code-group.ts";
248
256
  import { ControlClient, DAEMON_FEATURES, HANDOFF_CONNECT_MS, HANDOFF_LOOKUP_CONNECT_MS, HANDOFF_LOOKUP_REQUEST_MS, HANDOFF_REQUEST_MS, PROTOCOL, PROTOCOL_MIN, readControl, stateDirFor } from "./control-client.ts";
249
- import { negotiateProtocol, protocolWindow } from "./protocol-window.ts";
257
+ import { BRIDGE_PROTOCOL_RELEASES, DEFAULT_BRIDGE_WINDOW, bridgeProtocolWindow, bridgeWindowSettings, negotiateProtocol, protocolWindow } from "./protocol-window.ts";
250
258
  import { attachEvent, originOf, type Origin } from "./provenance.ts";
251
259
  import { mintSessionId, sessionGate } from "./session-identity.ts";
252
260
  import { MAX_HOP, isInvocationKind, newEnvelope, parseMarker, replyParent, sanitize, USER, type Envelope, type PeerId, type Priority } from "./envelope.ts";
253
- import { BasePeer, DEFAULT_WATCHDOG_MS, type FrontendProxyPort, type PeerAdapter, type PeerTakeoverClaim } from "./peers.ts";
261
+ import { BasePeer, type FrontendProxyPort, type PeerAdapter, type PeerTakeoverClaim } from "./peers.ts";
254
262
  import { ClaudeTodoSource, DoingTracker, readAiTitle, DOING_STUB, SESSION_TITLE_HINT, sessionTitleText, sessionTitleBindings, unnamedSessionLabel, type DoingKind, type PeerDoing, type TitleCursor } from "./peer-doing.ts";
255
263
  import { MemoryClient } from "../memory/client.ts";
256
264
  import { VERSION, displayVersion } from "../version.ts";
257
265
  import { appendRecords, ResearchTail, taskRecords } from "./research.ts";
258
266
  import { readEvidence } from "./research-record.ts";
259
267
  import { memoryFigures, onlyTaskMemory, UNKNOWN_MEMORY_FIGURES, type MemoryFigures } from "./research-memory.ts";
260
- import { parseResearchRunners, type RegisteredRunnerV1 } from "./research-runner.ts";
268
+ import { parseResearchRunners } from "./research-runner.ts";
261
269
  import { benchReport, MIN_ATTEMPTS, readRuns, runSummary, type Measures, type RunSummary } from "./bench.ts";
262
270
  import { projectChain } from "@staix/agent-mem";
263
271
  import { recallFor } from "../memory/recall.ts";
264
272
  import { conflictsOf } from "./conflicts.ts";
265
273
  import { Facts, FACTS_PREFIX, type FactScope } from "./facts.ts";
266
- import { EditEvidence, editGuard, parseEditGovernance, type EditGuardArm } from "./edit-guard.ts";
274
+ import { EditEvidence, editGuard } from "./edit-guard.ts";
267
275
  import { crashPlan, lossNotice, openCrashNotices, readSessions, removeSessions, writeSessions, type CrashNotice, type SessionsFile } from "./crash.ts";
268
276
  import type { JournalDelivery } from "./delivery-journal.ts";
269
- import { DEFAULT_LIMITS, Limiter, PROJECT_LIMITS, type LimitsConfig } from "./limits.ts";
277
+ import { Limiter, PROJECT_LIMITS, type LimitsConfig } from "./limits.ts";
270
278
  import { soleWorktree, branchHeads, changedPaths, dirtySubmodules, submodulePaths, knownChangedPaths, hasTree, headState, headMoveCursor, incomingHeadPaths, repoOf, snapshot, SnapshotBudgetExceeded, SnapshotCooldown, budgetNow, Turns, type SnapshotBudget, type HeadMoveCursor, type Repo, type TurnRecord } from "./snapshots.ts";
271
279
  import { archiveRestartSnapshot, compactRestartBus, readRecoveryWaivers, readRestartSnapshot, removeRestartSnapshot, restartPath, writeRestartSnapshot, type RecoveryPhase, type RestartPeerSnapshot, type RestartSnapshot } from "./restart.ts";
272
280
  import { consumeRecoveryContinuity, readRecoveryContinuity, retireRecoveryContinuity } from "./recovery-continuity.ts";
273
- import { shellQuote, publishTerminalLaunch, terminalLaunchCandidate, launcherOf } from "../cli/terminal-recovery.ts";
281
+ import { shellQuote, publishTerminalLaunch, terminalLaunchCandidate, launcherOf, orcaExecutable } from "../cli/terminal-recovery.ts";
282
+ import { OrcaPaneWatch, orcaAgentRunner } from "./orca-state.ts";
274
283
  import { TerminalLaunches, terminalOwnerReads } from "./terminal-launch.ts";
275
284
 
276
- import { START_AGENTS_DEFAULT, checkStartAgents } from "./start-agents.ts";
277
- import { adapterCeiling, applyRoleCeiling } from "../adapters/role-eligibility.ts";
278
- import { peerStartConfig, PEER_START_RETRY_MS, startModeOf, terminalTemplate, type PeerStartConfig, type StartMode } from "./start-mode.ts";
285
+ import { peerStartConfig, PEER_START_RETRY_MS, startModeOf, type PeerStartConfig, type StartMode } from "./start-mode.ts";
279
286
  import { hasKimiHubMcp } from "../cli/kimi-mcp.ts";
280
287
  import type { TerminalOpener } from "./terminal-open.ts";
281
- import { isHubWritePath, grantablePath, instructionProtection, isPermissionMode, permissionBoundary, permissionDefaults, permissionGrant, PI_EDIT_TOOLS, type PermissionMode } from "./permission-mode.ts";
282
- import { ContextWindows, DEFAULT_CONTEXT, readNativeContext, type ContextConfig } from "./context-window.ts";
288
+ import { isHubWritePath, grantablePath, isPermissionMode, permissionBoundary, permissionDefaults, permissionGrant, PI_EDIT_TOOLS, type PermissionMode } from "./permission-mode.ts";
289
+ import { ContextWindows, readNativeContext } from "./context-window.ts";
283
290
  import { projectFileTool, scopedWriteBlocked } from "../cli/facts-hook.ts";
284
291
  import { detectTooling } from "./tooling.ts";
285
292
  import { CaptureStore, configuredPolicy, recordsEnabled, looksSecret, DEFAULT_LEASE_MS, memoryHome, SUGGESTED, taskKey, type CandidateStore, type MemoryStore, type GoalView, type Suggested, type View as MemoryView } from "@staix/agent-mem";
@@ -294,179 +301,15 @@ import { promotionScreen, withoutPii, mentionsPrivatePath } from "./memory-polic
294
301
  import { hostPlacementAttestation, memorySyncErrorText, writerRefusalOf, type WriterRefusal } from "./memory-sync-attestation.ts";
295
302
  import { classifyMemorySyncFailure, initialMemorySyncState, memorySyncDeclinedDetails, memorySyncFailureDetailHash, memorySyncView, memorySyncNextStep, memorySyncPlacementCounts, reduceMemorySync } from "./memory-sync-state.ts";
296
303
  import { createMemorySyncPolicy, inspectDeclinedMemoryRows } from "./memory-sync-policy.ts";
297
- import { DEFAULT_SPECS_CONFIG, parseSpecsConfig, type SpecsConfig } from "./specs-config.ts";
298
304
 
299
- export interface HubConfig {
300
- adapter_modules?: readonly AdapterModuleDeclaration[];
301
- adapters?: Readonly<Record<string, import("../adapters/configured-acp.ts").ConfiguredAdapterConfig>>;
302
- /** Person-owned declarations, read only from an untracked machine-local file. Bound for this daemon lifetime. */
303
- instances?: InstancesConfig;
304
- watchdog_ms: number;
305
- kimi_cmd: string[];
306
- qwen_cmd: string[];
307
- jcode_cmd: string[];
308
- jcode_home: string;
309
- /** Machine-local names of jcode MCP servers `ahub doctor` accepts for the hub-owned jcode (#1621). Names only; launch is unchanged. */
310
- jcode_mcp_allow?: string[];
311
- jcode_provider_profile: string;
312
- action_policy?: ActionPolicyConfig;
313
- permission_modes: Record<string, PermissionMode>;
314
- protect_instruction_files: boolean;
315
- instructed?: { mode: "off" | "exact" | "intent" };
316
- /** Loader-owned provenance of requested defaults, before machine-local filtering. */
317
- permission_default_sources?: Record<string, { mode: PermissionMode; source: string }>;
318
- codex_bin: string;
319
- batch_max: number;
320
- batch_ms: number;
321
- queue_cap: number;
322
- /** #489 H3: accepted delivery policy, read at the next delivery operation without rewriting queued work. */
323
- bus?: { max_attempts?: number; digest_max?: number; pull_budget_bytes?: number; notes_kept?: number; terminal_history_limit?: number; accepted_settle_ms?: number };
324
- /** #489 H5: accepted timing captured only when a new native adapter is constructed. */
325
- adapter_timing?: AdapterTimingConfig["adapter_timing"];
326
- /** #489 H6: relay policy is captured from restart-bound accepted configuration. */
327
- model_relay?: ModelOperationalConfig["model_relay"];
328
- /** #489 H7: accepted presentation preferences read by a new console through settings_get. */
329
- console?: ConsoleOperationalConfig["console"];
330
- /** `native` (#258): the hub's own store in ~/.agenthub/memory, on with any project config; `short_ttl_days`: short-term lifetime after approval; `sync_interval_min`: machine sync while a remote is set (default 10, 0 off); `preface_unused_after` (#1330): a long-term preface line delivered at least this many times and never cited moves to the end of its section, so the cap cuts it first (default 20, 0 keeps the store order). */
331
- memory: { enabled: boolean; worker_url?: string; inject_tokens: number; brief_items: number; native?: boolean; short_ttl_days?: number; sync_interval_min?: number; suggest_edges?: boolean; preface_unused_after?: number; review?: MemoryReviewConfig };
332
- roster: PeerRoster;
333
- roles: Record<string, string[]>;
334
- /** #455: the one peer that holds the planner role; unset, the `roles` planners stand, or the hub assigns one. */
335
- planner?: string | string[];
336
- profile?: ProfileName;
337
- profile_overrides?: Record<string, unknown>;
338
- pii?: { paths: string[] };
339
- data?: { readonly: string[] };
340
- text_projection?: ProjectionConfig;
341
- /** #510: machine-local folders of plain notes the hub may index, read-only; vault folders are refused when the index reads them. */
342
- corpus: { paths: string[] };
343
- roadmap?: RoadmapConfig;
344
- specs: SpecsConfig;
345
- catalog_roles?: Record<string, string[]>;
346
- conductor: { feed: "own" | "all" | "off"; approval_wait_s: number };
347
- /** #1221 T2: what the supervision queue may do. `off` evaluates nothing, `shadow` stores bounded proposals with no inbox row or notice, `advisory` may also show a pending one in the console inbox. Machine-local and off by default. */
348
- supervision: { mode: "off" | "shadow" | "advisory" };
349
- edit_governance?: { arm: EditGuardArm };
350
- budget: BudgetConfig;
351
- context: ContextConfig;
352
- inference: InferenceConfig;
353
- omniroute: OmniRouteConfig;
354
- pi: { enabled: boolean; auto_start: boolean; cmd: string[]; backend: "auto" | "dgx" | "mlx"; dgx_coding: string; dgx_fast: string; max_steps: number; max_continuations: number };
355
- mlx: { enabled: boolean } & Pick<MlxOptions, "provider" | "host" | "runtimeDir" | "modelPath" | "port" | "model" | "sourceModel" | "contextWindow" | "maxInputTokens" | "maxTokens" | "maxConcurrency">;
356
- /** `bash_network`: true is network through the egress proxy to `network_allow` (#65); "direct" is everything, until 0.13.0 (#83). */
357
- local: { deny: string[]; bash_network: boolean | "direct"; network_allow: string[]; max_steps: number; read_allow: string[]; /** #515: offer the local worker `doc_read` (PDF, DOCX, HWPX through `text_projection`); off by default, machine-local. */ doc_read: boolean; /** #515b: the hosts the local worker's `web_fetch` may read; empty (the default) means the tool does not exist. Machine-local. */ web_fetch: { allow: string[] } };
358
- /** Pending permission requests: how long they wait, and whether the desktop is told (issue #5). */
359
- approvals: { timeout_s: number; notify: boolean };
360
- /** An owner offline this long loses its open tasks back to routing; 0 turns it off (issue #6). */
361
- tasks: { release_after_min: number; wip_limits?: Record<string, number>; escalate_after: number; groom_fyi_window_min?: number; demote_at?: number; demotion_half_life_h?: number; contradiction_window_days?: number; rescreen_max?: number; split_min_observations?: number; split_max_failure_share?: number; /** #785 P1c: pull the top explicitly reserved ready card when a slot frees; machine-local, default off. */ auto_pull?: boolean; queue_backpressure?: Partial<QueueBackpressurePolicy> };
362
- /** Between-turn task escalation, disabled unless explicitly enabled (#186). */
363
- task_sweep: TaskSweepConfig;
364
- /** #512a: machine-local schedules; checked by `schedulesConfig`, never set from a committed file. */
365
- schedules: ScheduleEntry[];
366
- /** #512c: machine-local folder triggers, polled on the schedules timer; checked by `foldersConfig`, never set from a committed file. */
367
- folder_triggers: FolderEntry[];
368
- /** A command per task class run when the owner marks the task done, and its timeout (issue #7). */
369
- checks: { timeout_s: number; runner?: "container" | "remote"; remote?: RemoteRunnerConfig; [cls: string]: string | number | RemoteRunnerConfig | undefined };
370
- /** A git tree at each turn boundary for `ahub turns` and `ahub undo`, the last `keep` per peer (issue #33). */
371
- snapshots: { enabled: boolean; keep: number };
372
- /** Unbound visuals expire; task-bound records retain the task lifetime. */
373
- visuals: { retention_days: number };
374
- /** #1057: the worktree shelf. `quiet_days` shelves a worktree idle that long (0 = never); `alert_over` is the settled count that raises one inbox alert (0 = never). */
375
- worktrees: { quiet_days: number; alert_over: number };
376
- /** #1053: `ttl_s` expires an unanswered question (default 86400); `wait_ms` overrides an adapter definition's `questionWaitMs` per kind. */
377
- questions: { ttl_s: number; wait_ms: Record<string, number> };
378
- /** #247: opt-in research records of each approved task in ~/.agenthub/research (ids, counts and tokens only). */
379
- research: { enabled: boolean; runners?: Record<string, RegisteredRunnerV1> };
380
- /** #251: a project kept for benchmarks: `ahub bench run` resets its work tree between attempts. */
381
- bench: { enabled: boolean };
382
- /** #269: per peer, how a start comes up when nothing more specific was asked: `tui` (the default) or `headless`. Pi and Codex only. */
383
- peers: PeerStartConfig;
384
- /** #269: a machine-local argv that opens a terminal for a hub-made TUI start; `{command}` in one element is the command to run. */
385
- terminal: { open: string[] };
386
- /** #608: the peers `ahub up` asks the hub to start, machine-local. Read by the CLI at a person's `ahub up` and by the dashboard manager's start; the daemon itself never starts one from it. */
387
- start: { agents: string[] };
388
- /** Per-sender rate limits and repeat suppression for what agents send (issue #38). */
389
- limits: LimitsConfig;
390
- /** Reviewer choice from recorded review outcomes, once a reviewer has `min_reviews` of an implementer (issue #35). */
391
- review: { adaptive: boolean; min_reviews: number; pool?: string[]; rerotate?: boolean; same_family?: "fallback" | "never"; gate?: ReviewGate; unknown_quota?: ReviewUnknownQuota; max_minutes?: number };
392
- /** After an unplanned stop, start Kimi, Pi and the local worker again with their recorded sessions (issue #37). */
393
- /** #489 H4: the five waits the upgrade coordinator reads from this project's config at the start of each wait; the daemon itself only validates and carries them. */
394
- recovery: { auto_resume_after_crash: boolean; reconnect_wait_s?: number; unmanaged_reconnect_wait_s?: number; control_timeout_s?: number; shutdown_wait_s?: number; terminal_idle_wait_s?: number };
395
- /** Per peer, the hub-tool capabilities it has (issue #39); a peer not listed has all of them. */
396
- capabilities: Record<string, string[]>;
397
- /** #445 C1: machine-local invocation settings. `share` is the person's allowlist of native capabilities by peer id, each pinned by digest (`src/hub/capabilities.ts`). */
398
- invocation?: { share?: Record<string, Record<string, { digest: string; class?: string }>>; /** Seconds a request may wait for its result, 10 to 86400, default 600 (#445 C2). */ timeout_s?: number };
399
- /**
400
- * How owners of overlapping tasks coordinate (issue #107): "advisory" lets them message each other; "turn-free" has
401
- * them work without messages while the hub derives what they need to know. Anything else is advisory.
402
- */
403
- coordination: "advisory" | "turn-free";
404
- /** Switches for controlled ablations only (issue #110): `stale_notices: "deliver"` turns #106's dropping off. */
405
- experiments?: { stale_notices?: "drop" | "deliver" };
406
- /** Console-local terminal presentation (#280, #483); grants no authority. */
407
- pet?: false | Record<string, unknown>;
408
- /** Machine-local fields a config file set but git could not vouch for, and why (issue #17). */
409
- ignored?: string[];
410
- /** Reporting-only notice that machine-local release policy was ignored; never part of accepted policy authority. */
411
- releasePolicyNotices?: string[];
412
- /** Settings that were removed or are about to be (issue #83): what each does now, for `hub.log` and `ahub doctor`. */
413
- retired?: string[];
305
+ import { CONFIG_FILES, DEFAULT_CONFIG as declarationDefaults, loadConfig as loadDeclarationConfig, loadConductorPolicy, mlxLaunchProblem, type HubConfig } from "./config.ts";
306
+
307
+ export { loadConductorPolicy, type ConfigLayer, type HubConfig } from "./config.ts";
308
+ export const DEFAULT_CONFIG: HubConfig = { ...declarationDefaults, roles: DEFAULT_ROLES };
309
+ export function loadConfig(...[cwd, layers, routingRetired, externalDefinitions]: Parameters<typeof loadDeclarationConfig>): HubConfig {
310
+ const loaded = loadDeclarationConfig(cwd, layers, routingRetired, externalDefinitions, DEFAULT_ROLES);
311
+ return loaded === declarationDefaults ? DEFAULT_CONFIG : loaded;
414
312
  }
415
- const nativeDefaults = nativeConfigurationDefaults({ home: homedir(), env: process.env, networkAllow: DEFAULT_NETWORK_ALLOW });
416
- export const DEFAULT_CONFIG: HubConfig = {
417
- watchdog_ms: DEFAULT_WATCHDOG_MS,
418
- ...nativeDefaults.commands,
419
- action_policy: actionPolicyConfig(),
420
- permission_modes: {},
421
- protect_instruction_files: false,
422
- instructed: { mode: "intent" },
423
- ...nativeDefaults.proxy,
424
- batch_max: 3,
425
- batch_ms: 15_000,
426
- queue_cap: 200,
427
- bus: { max_attempts: BUS_MAX_ATTEMPTS_SETTING.defaultValue, digest_max: BUS_DIGEST_MAX_SETTING.defaultValue, pull_budget_bytes: BUS_PULL_BUDGET_BYTES_SETTING.defaultValue, notes_kept: BUS_NOTES_KEPT_SETTING.defaultValue, terminal_history_limit: BUS_TERMINAL_HISTORY_LIMIT_SETTING.defaultValue, accepted_settle_ms: BUS_ACCEPTED_SETTLE_MS_SETTING.defaultValue },
428
- adapter_timing: { acp_tool_ceiling_min: ACP_TOOL_CEILING_SETTING.defaultValue, acp_activity_batch_ms: ACP_ACTIVITY_BATCH_SETTING.defaultValue, jcode_steer_timeout_s: JCODE_STEER_TIMEOUT_SETTING.defaultValue },
429
- memory: { enabled: true, inject_tokens: 2000, brief_items: 8, preface_unused_after: 20, review: MEMORY_REVIEW_DEFAULTS },
430
- roster: {},
431
- roles: DEFAULT_ROLES,
432
- conductor: { feed: "own", approval_wait_s: 30 },
433
- supervision: { mode: "off" },
434
- edit_governance: { arm: "baseline" },
435
- budget: DEFAULT_BUDGET,
436
- context: DEFAULT_CONTEXT,
437
- model_relay: { cooldown_failures: MODEL_COOLDOWN_FAILURES_SETTING.defaultValue, cooldown_s: MODEL_COOLDOWN_SETTING.defaultValue, cooldown_cap_s: MODEL_COOLDOWN_CAP_SETTING.defaultValue, terminal_history_limit: MODEL_TERMINAL_HISTORY_SETTING.defaultValue },
438
- console: { poll_ms: CONSOLE_POLL_SETTING.defaultValue, notice_ms: CONSOLE_NOTICE_SETTING.defaultValue, history_limit: CONSOLE_HISTORY_SETTING.defaultValue, pending_stream_limit: CONSOLE_PENDING_STREAM_SETTING.defaultValue, attention_limit: CONSOLE_ATTENTION_SETTING.defaultValue },
439
- inference: DEFAULT_INFERENCE,
440
- omniroute: DEFAULT_OMNIROUTE,
441
- ...nativeDefaults.rpc,
442
- mlx: { enabled: true, provider: "ollama", model: "agenthub-fast-mlx:4b-8k", sourceModel: "qwen3.5:4b-mlx", contextWindow: 8192, maxInputTokens: 6000, maxTokens: 2048, maxConcurrency: 1 },
443
- ...nativeDefaults.sandbox,
444
- // Off here, so tests and a hub without a config file stay silent; a project's config defaults it on for macOS.
445
- approvals: { timeout_s: 120, notify: false },
446
- tasks: { release_after_min: 30, escalate_after: ESCALATE_AFTER, groom_fyi_window_min: GROOM_FYI_WINDOW_SETTING.defaultValue, demote_at: DEMOTE_AT_SETTING.defaultValue, demotion_half_life_h: DEMOTION_HALF_LIFE_SETTING.defaultValue, contradiction_window_days: CONTRADICTION_WINDOW_SETTING.defaultValue, rescreen_max: RESCREEN_MAX_SETTING.defaultValue, split_min_observations: SPLIT_MIN_SETTING.defaultValue, split_max_failure_share: SPLIT_FAILURE_SHARE_SETTING.defaultValue, auto_pull: false },
447
- task_sweep: DEFAULT_TASK_SWEEP,
448
- schedules: [],
449
- folder_triggers: [],
450
- corpus: { paths: [] },
451
- roadmap: roadmapConfig(undefined),
452
- specs: { ...DEFAULT_SPECS_CONFIG, roots: [] },
453
- checks: { timeout_s: 600 },
454
- // Off here like approvals.notify, so tests (whose cwd is this repository) write no objects; a project's config turns it on.
455
- snapshots: { enabled: false, keep: 20 },
456
- worktrees: { quiet_days: 7, alert_over: 10 },
457
- questions: { ttl_s: 86_400, wait_ms: {} },
458
- visuals: { retention_days: 30 },
459
- research: { enabled: false },
460
- bench: { enabled: false },
461
- peers: {},
462
- terminal: { open: [] },
463
- start: { agents: [...START_AGENTS_DEFAULT] },
464
- limits: DEFAULT_LIMITS,
465
- review: { adaptive: false, min_reviews: 5, gate: DEFAULT_REVIEW_GATE, unknown_quota: DEFAULT_REVIEW_UNKNOWN_QUOTA, max_minutes: DEFAULT_REVIEW_MAX_MINUTES },
466
- recovery: { auto_resume_after_crash: false, reconnect_wait_s: RECOVERY_RECONNECT_WAIT_SETTING.defaultValue, unmanaged_reconnect_wait_s: RECOVERY_UNMANAGED_RECONNECT_WAIT_SETTING.defaultValue, control_timeout_s: RECOVERY_CONTROL_TIMEOUT_SETTING.defaultValue, shutdown_wait_s: RECOVERY_SHUTDOWN_WAIT_SETTING.defaultValue, terminal_idle_wait_s: RECOVERY_TERMINAL_IDLE_WAIT_SETTING.defaultValue },
467
- capabilities: {},
468
- coordination: "advisory",
469
- };
470
313
 
471
314
  export { stateDirFor };
472
315
 
@@ -475,11 +318,6 @@ const READ_ONLY_HUB_TOOLS = new Set(["hub_roadmap_list", "hub_roadmap_show", "hu
475
318
  const BASE_RESERVED_IDS = new Set<string>([USER, ...SUPPORTED_PEERS.filter(peer => definitionOf(peer)?.attach?.externalHello !== true), HUB, DIGEST]);
476
319
  const PEER_ID = /^[a-z][a-z0-9-]{0,31}$/;
477
320
 
478
- /** The shared project config, then the machine's own file, which overrides it block by block (issue #17). */
479
- const CONFIG_FILES = INSTANCE_CONFIG_FILES;
480
- export interface ConfigLayer { name: typeof CONFIG_FILES[number]; raw: Record<string, any> }
481
- const CONFIG_BLOCKS = ["instructed", "action_policy", "memory", "roster", "roles", "catalog_roles", "pii", "data", "conductor", "budget", "context", "inference", "omniroute", ...NATIVE_CONFIG_BLOCKS, "approvals", "tasks", "task_sweep", "bus", "adapter_timing", "model_relay", "console", "corpus", "specs", "checks", "snapshots", "worktrees", "visuals", "research", "bench", "limits", "review", "recovery", "capabilities", "mlx", "permission_modes", "peers", "terminal", "start", "pet", "questions"];
482
-
483
321
  /** Older targets parse raw keys before placement/trust checks, so even an empty or refused declaration needs the floor. */
484
322
  function rawResearchRunnersPresent(cwd: string): boolean {
485
323
  const texts = configSourceTexts(cwd);
@@ -507,294 +345,6 @@ function rawVisualsPresent(cwd: string): boolean {
507
345
  return false;
508
346
  }
509
347
 
510
- /** Connection-time policy refresh reads role/feed fields only, never launches or machine-local configuration. */
511
- export function loadConductorPolicy(cwd: string, layers?: readonly ConfigLayer[], scope: Pick<ReturnType<typeof readInstanceConfig>, "instances" | "catalog"> = readInstanceConfig(cwd, layers)): { roles: Record<string, string[]>; conductor: HubConfig["conductor"]; planner?: string | string[]; notices?: string[] } {
512
- const roles: Record<string, string[]> = { ...DEFAULT_ROLES };
513
- const conductor = { ...DEFAULT_CONFIG.conductor };
514
- const notices: string[] = [];
515
- // #1063: what the layers declare after the adapter ceiling and before the #1408 eligibility drop. At most one conductor is checked on this map (as on main), so an eligible-ceiling kind that cannot conduct is refused, never ignored, and a conductor the ceiling never allowed does not count.
516
- const declaredRoles: Record<string, string[]> = { ...DEFAULT_ROLES };
517
- let planner: string | string[] | undefined;
518
- // #1408 R2: the conductor role needs an interactive session, so the loader reads each peer's effective start mode (config.local.json wins per peer) before it reads roles.
519
- const startModes: Record<string, StartMode> = {};
520
- for (const name of CONFIG_FILES) {
521
- const raw = layers ? layers.find(layer => layer.name === name)?.raw : (() => { try { return JSON.parse(readFileSync(join(cwd, ".agenthub", name), "utf8")) as Record<string, unknown>; } catch { return undefined; } })();
522
- const peers = raw?.peers;
523
- if (peers && typeof peers === "object" && !Array.isArray(peers)) for (const [peer, block] of Object.entries(peers)) {
524
- const mode = block && typeof block === "object" ? (block as { start_mode?: unknown }).start_mode : undefined;
525
- if (mode === "tui" || mode === "headless") startModes[peer] = mode;
526
- }
527
- }
528
- for (const name of CONFIG_FILES) {
529
- let file: Record<string, unknown>;
530
- if (layers && !layers.some(layer => layer.name === name)) continue;
531
- try { file = layers ? structuredClone(layers.find(layer => layer.name === name)!.raw) : JSON.parse(readFileSync(join(cwd, ".agenthub", name), "utf8")); }
532
- catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
533
- if (file.roles !== undefined) {
534
- if (!file.roles || typeof file.roles !== "object" || Array.isArray(file.roles)) throw new Error("roles must be an object of peer role lists");
535
- for (const [peer, assigned] of Object.entries(file.roles)) {
536
- conductorPeer({ [peer]: assigned });
537
- const declared = assigned as string[];
538
- declaredRoles[peer] = adapterCeiling(peer, declared);
539
- // #525 R1: planner needs a kind that can plan; #1408 R2: conductor needs an eligible kind in an interactive form. Such an entry is dropped with a notice, never thrown, and nobody else gains it.
540
- // The builtin registry only, exactly as before: a project-configured ACP kind keeps the roles it is given (#525, #735).
541
- const kept = applyRoleCeiling(peer, declared, startModes[peer]);
542
- roles[peer] = kept.roles;
543
- notices.push(...kept.notices);
544
- }
545
- }
546
- if (file.planner !== undefined) {
547
- if (file.planner === null) throw new Error("planner takes a peer id or a nonempty list of up to eight ids");
548
- const def = instanceSettingDef("planner", scope.instances, scope.catalog);
549
- if (typeof def === "string") throw new Error(def);
550
- const normalized = checkSettingValue(def, file.planner) as string | string[];
551
- planner = Array.isArray(file.planner) ? [...file.planner] as string[] : normalized;
552
- }
553
- if (file.conductor !== undefined) {
554
- if (!file.conductor || typeof file.conductor !== "object" || Array.isArray(file.conductor)) throw new Error("conductor must be an object");
555
- const block = file.conductor as Record<string, unknown>;
556
- if (block.feed !== undefined) {
557
- if (!["own", "all", "off"].includes(String(block.feed))) throw new Error("conductor.feed must be own, all or off");
558
- conductor.feed = block.feed as "own" | "all" | "off";
559
- }
560
- if (block.approval_wait_s !== undefined) {
561
- if (typeof block.approval_wait_s !== "number" || !Number.isFinite(block.approval_wait_s) || block.approval_wait_s < 0) throw new Error("conductor.approval_wait_s must be a nonnegative number");
562
- conductor.approval_wait_s = block.approval_wait_s;
563
- }
564
- }
565
- }
566
- conductorPeer(declaredRoles);
567
- conductorPeer(roles);
568
- return { roles, conductor, ...(planner ? { planner } : {}), ...(notices.length ? { notices } : {}) };
569
- }
570
-
571
- /** `memory.short_ttl_days`: a whole number of days from 1 to 3650; anything else would make every short-term deadline invalid. */
572
- function ttlDays(v: unknown): number {
573
- if (typeof v !== "number" || !Number.isInteger(v) || v < 1 || v > 3650) throw new Error("memory.short_ttl_days must be a whole number of days from 1 to 3650");
574
- return v;
575
- }
576
- /** `memory.sync_interval_min`: 0 (off) or a whole number of minutes up to a day. */
577
- function syncMinutes(v: unknown): number {
578
- if (typeof v !== "number" || !Number.isInteger(v) || v < 0 || v > 1440) throw new Error("memory.sync_interval_min must be 0 (off) or a whole number of minutes up to 1440");
579
- return v;
580
- }
581
-
582
- /** Routing diagnostics must not make independent config reads depend on valid routing. */
583
- function retiredRoutingSettings(cwd: string): readonly string[] {
584
- try { return loadRouting(cwd).retired ?? []; }
585
- catch { return []; } // Routing admission and reload report parse errors using their own last-good state.
586
- }
587
-
588
- /** #1057: a whole non-negative number of days or alert count; anything else (a negative, a fraction, a string) is the default, so a bad value never changes the shelf. The reload schema refuses it by name. */
589
- const wholeDays = (value: unknown, fallback: number): number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= 100_000 ? value : fallback;
590
- /** #1053: `questions.ttl_s` (60 s to 30 days) and a per-kind `wait_ms` (1 s to 10 min); anything else keeps the default, so a bad value never changes what the person is asked. */
591
- const questionsConfig = (value: unknown): HubConfig["questions"] => {
592
- const raw = value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
593
- const ttl = typeof raw.ttl_s === "number" && Number.isSafeInteger(raw.ttl_s) && raw.ttl_s >= 60 && raw.ttl_s <= 2_592_000 ? raw.ttl_s : DEFAULT_CONFIG.questions.ttl_s;
594
- const wait: Record<string, number> = {};
595
- if (raw.wait_ms && typeof raw.wait_ms === "object" && !Array.isArray(raw.wait_ms)) for (const [kind, ms] of Object.entries(raw.wait_ms as Record<string, unknown>)) if (/^[a-z][a-z0-9-]{0,31}$/.test(kind) && typeof ms === "number" && Number.isSafeInteger(ms) && ms >= 1000 && ms <= 600_000) wait[kind] = ms;
596
- return { ttl_s: ttl, wait_ms: wait };
597
- };
598
- export function loadConfig(cwd: string, layers?: readonly ConfigLayer[], routingRetired: readonly string[] = retiredRoutingSettings(cwd), externalDefinitions?: readonly import("../adapters/registry-types.ts").AdapterDefinition[]): HubConfig {
599
- const captured = layers ?? readInstanceConfigLayers(cwd);
600
- const instanceConfig = readInstanceConfig(cwd, captured, externalDefinitions);
601
- const instances = instanceConfig.instances;
602
- const adapterCatalog = instanceConfig.catalog;
603
- const ignored: string[] = [...instanceConfig.ignored];
604
- const releasePolicyNotices: string[] = [];
605
- const inertModuleRoster = !!instanceConfig.adapter_modules?.length;
606
- const appliedPermissionSources: NonNullable<HubConfig["permission_default_sources"]> = {};
607
- let retiredPetWindow = false;
608
- const files = CONFIG_FILES.flatMap((name) => {
609
- let file: Record<string, any>; // parsed JSON, checked field by field below
610
- if (!captured.some(layer => layer.name === name)) return [];
611
- try {
612
- file = withoutInertInstancePolicy(structuredClone(captured.find(layer => layer.name === name)!.raw), instanceConfig.declaredExternalInstances);
613
- } catch (error) {
614
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
615
- throw error;
616
- }
617
- delete file.adapter_modules; // Code provenance is captured separately and never evaluated by configuration reads.
618
- delete file.adapters; // Adapter provenance is compiled by the same project-local loader.
619
- delete file.instances; // Declaration authority was checked against its exact captured origin above.
620
- peerRosterConfig(file.roster, instances, adapterCatalog, inertModuleRoster);
621
- catalogAssignments(file.catalog_roles);
622
- profileName(file.profile);
623
- resolveProfile(file.profile, file.profile_overrides);
624
- projectionConfig(file.text_projection);
625
- corpusConfig(file.corpus);
626
- roadmapConfig(file.roadmap);
627
- if (file.specs !== undefined) parseSpecsConfig(file.specs);
628
- queueBackpressurePolicy(file.tasks?.queue_backpressure);
629
- validateOperationalConfig(file);
630
- for (const [block, key] of [["pii", "paths"], ["data", "readonly"]] as const) {
631
- const raw = file[block];
632
- if (raw !== undefined && (!raw || typeof raw !== "object" || Array.isArray(raw) || Object.keys(raw).some(k => k !== key))) throw new Error(block + " must be a bounded path policy block");
633
- policyPaths(raw?.[key], block + "." + key);
634
- }
635
- if (file.jcode_cmd !== undefined && (!Array.isArray(file.jcode_cmd) || !file.jcode_cmd.length || file.jcode_cmd.some((word: unknown) => typeof word !== "string" || !word))) throw new Error("jcode_cmd must be a nonempty executable argv");
636
- if (file.jcode_home !== undefined && (typeof file.jcode_home !== "string" || !isAbsolute(file.jcode_home))) throw new Error("jcode_home must be an absolute path");
637
- if (file.jcode_mcp_allow !== undefined) mcpAllowNames(file.jcode_mcp_allow, "jcode_mcp_allow");
638
- for (const key of ["jcode_home", "jcode_provider_profile"]) if (file[key] !== undefined && typeof file[key] !== "string") throw new Error(`${key} must be a string`);
639
- if (file.qwen_cmd !== undefined && (!Array.isArray(file.qwen_cmd) || !file.qwen_cmd.length || file.qwen_cmd.some((word: unknown) => typeof word !== "string" || !word))) throw new Error("qwen_cmd must be a nonempty executable argv");
640
- actionPolicyConfig(file.action_policy);
641
- if (file.edit_governance !== undefined) parseEditGovernance(file.edit_governance);
642
- instructionProtection(file.protect_instruction_files);
643
- if (file.instructed !== undefined) {
644
- if (!file.instructed || typeof file.instructed !== "object" || Array.isArray(file.instructed) || Object.keys(file.instructed).some(key => key !== "mode")) throw new Error("instructed must contain only mode");
645
- instructedMode(file.instructed.mode);
646
- }
647
- permissionDefaults(file.permission_modes, instances, adapterCatalog); // malformed declarations fail even when trust would drop them
648
- peerStartConfig(file.peers, instances, adapterCatalog);
649
- if (file.terminal != null && (typeof file.terminal !== "object" || Array.isArray(file.terminal))) throw new Error("terminal must be an object");
650
- terminalTemplate(file.terminal?.open);
651
- if (file.start != null && (typeof file.start !== "object" || Array.isArray(file.start) || Object.keys(file.start).some((key: string) => key !== "agents"))) throw new Error("start must be an object with an agents list");
652
- if (file.start?.agents !== undefined) checkStartAgents(file.start.agents);
653
- const pet = stripLegacyPetWindow(file.pet);
654
- if (pet !== file.pet) { retiredPetWindow = true; if (pet && typeof pet === "object" && !Object.keys(pet).length) delete file.pet; else file.pet = pet; }
655
- if (file.pet !== undefined) validatePetConfig(file.pet, "config.pet");
656
- if (file.pet && typeof file.pet === "object" && !Object.keys(file.pet).length) delete file.pet;
657
- delete file.declaredExternalInstances; // host-derived refusal rows, never a file claim
658
- delete file.permission_default_sources; // provenance is loader-owned, never a file claim
659
- delete file._autonomy; // Inert restoration metadata, never policy or approval provenance.
660
- if (file.checks?.runner === "remote" || file.checks?.remote !== undefined) {
661
- if (name !== "config.local.json" || configTracked(cwd, name) !== false) throw new Error("remote checks require untracked config.local.json");
662
- if (file.checks.remote !== undefined) remoteRunnerConfig(file.checks.remote);
663
- }
664
- if (file.research !== undefined && (!file.research || typeof file.research !== "object" || Array.isArray(file.research))) throw new Error("research must be an object");
665
- const hasRunners = file.research && Object.hasOwn(file.research, "runners"), runnerDeclarations: unknown = hasRunners ? file.research.runners : undefined;
666
- const why = stripUntrusted(file, DEFAULT_CONFIG, cwd, name);
667
- if (why) {
668
- const notices = why.split("; ");
669
- releasePolicyNotices.push(...notices.filter(notice => notice.startsWith("release in .agenthub/config.local.json ignored:")));
670
- const existingNotices = notices.filter(notice => !notice.startsWith("release in .agenthub/config.local.json ignored:"));
671
- if (existingNotices.length) ignored.push(existingNotices.join("; "));
672
- }
673
- if (file.edit_governance && !Object.keys(file.edit_governance).length) delete file.edit_governance;
674
- // Release policy is read directly from the candidate commit by the S6 host reader, never runtime config.
675
- delete file.release;
676
- if (hasRunners) file.research.runners = parseResearchRunners(runnerDeclarations);
677
- for (const [peer, mode] of Object.entries(permissionDefaults(file.permission_modes, instances, adapterCatalog))) appliedPermissionSources[peer] = { mode, source: `.agenthub/${name}` };
678
- return [file];
679
- });
680
- if (!files.length) return routingRetired.length ? { ...DEFAULT_CONFIG, retired: [...routingRetired] } : DEFAULT_CONFIG;
681
- const file = files.reduce((a, b) => ({ ...a, ...b, ...Object.fromEntries(CONFIG_BLOCKS.filter((k) => a[k] !== undefined && b[k] !== undefined).map((k) => [k, { ...a[k], ...b[k] }])) }));
682
- const pressureLayers = files.filter(layer => layer.tasks?.queue_backpressure !== undefined);
683
- if (pressureLayers.length) file.tasks = { ...file.tasks, queue_backpressure: pressureLayers.reduce((prior, layer) => ({ ...prior, ...layer.tasks.queue_backpressure }), {}) };
684
- const wipLayers = files.filter(layer => layer.tasks?.wip_limits !== undefined);
685
- if (wipLayers.length) file.tasks = { ...file.tasks, wip_limits: wipLayers.reduce((prior, layer) => ({ ...prior, ...planningWipLimits(layer.tasks.wip_limits) }), {} as Record<string, number>) };
686
- const overrides = files.reduce<unknown>((prior, layer) => mergeProfileOverrides(prior, layer.profile_overrides), undefined);
687
- if (overrides !== undefined) file.profile_overrides = overrides;
688
- resolveProfile(file.profile, file.profile_overrides);
689
- delete file.ignored; // the hub's own record, never a file's
690
- delete file.retired;
691
- // Escape hatches with a stated end (issue #83). A removed one is ignored, never an error: an old config.local.json
692
- // must not stop a hub from starting.
693
- const retired: string[] = [...routingRetired];
694
- if (retiredPetWindow && !retired.includes(PET_WINDOW_RETIRED_NOTICE)) retired.push(PET_WINDOW_RETIRED_NOTICE);
695
- if (file.local?.sandbox !== undefined) {
696
- if (file.local.sandbox === "allow-default") retired.push('local.sandbox "allow-default" was removed in 0.12.0: the deny-default sandbox applies (local.read_allow adds paths)');
697
- file.local = { ...file.local };
698
- delete file.local.sandbox;
699
- }
700
- if (file.local?.bash_network === "direct") retired.push('local.bash_network "direct" (the open network) goes in 0.13.0: set it to true and list the hosts in local.network_allow');
701
- if (file.mlx != null && (typeof file.mlx !== "object" || Array.isArray(file.mlx))) throw new Error("mlx configuration must be an object");
702
- if (file.mlx?.enabled !== undefined && typeof file.mlx.enabled !== "boolean") throw new Error("mlx.enabled must be a boolean");
703
- if (file.mlx?.provider !== undefined && !["ollama", "legacy"].includes(file.mlx.provider)) throw new Error("mlx.provider must be ollama or legacy");
704
- if (file.mlx?.provider === undefined && (file.mlx?.modelPath || file.mlx?.runtimeDir || file.mlx?.bin || file.mlx?.port)) {
705
- throw new Error("legacy MLX configuration requires explicit mlx.provider=legacy; migrate to provider=ollama to avoid Python serving");
706
- }
707
- const mlx = { ...(file.mlx?.provider === "legacy" ? { enabled: true, provider: "legacy" as const, maxInputTokens: 16_000, maxTokens: 2048 } : DEFAULT_CONFIG.mlx), ...file.mlx };
708
- const conductorPolicy = loadConductorPolicy(cwd, captured, instanceConfig);
709
- retired.push(...conductorPolicy.notices ?? []);
710
- const configuredRoles = Object.fromEntries(adapterCatalog.definitions.filter(d => !definitionOf(d.kind)).map(d => [d.kind, [...d.roles]]));
711
- const extraRoles = Object.fromEntries(Object.keys(instances ?? {}).map(id => [id, effectiveInstanceRoles(id, instances, conductorPolicy.roles, adapterCatalog)]));
712
- const instancePermissions: Record<string, PermissionMode> = {};
713
- const instanceModes: PeerStartConfig = {};
714
- for (const [id, declaration] of Object.entries(instances ?? {})) {
715
- instanceModes[id] = { start_mode: declaration.start_mode ?? "headless" };
716
- if (declaration.permission_mode !== undefined) {
717
- instancePermissions[id] = declaration.permission_mode;
718
- appliedPermissionSources[id] = { mode: declaration.permission_mode, source: ".agenthub/config.local.json" };
719
- }
720
- }
721
- if (!mlx.enabled && file.pi?.backend === "mlx") throw new Error("Pi backend mlx conflicts with mlx.enabled=false");
722
- if (typeof mlx.runtimeDir === "string" && mlx.runtimeDir) mlx.runtimeDir = resolve(cwd, mlx.runtimeDir);
723
- if (typeof mlx.modelPath === "string" && mlx.modelPath) mlx.modelPath = resolve(cwd, mlx.modelPath);
724
- // #1329 part 1: the scheduled memory review is derived from `memory.review` at every read (`scheduleEntries` below)
725
- // rather than copied into `config.schedules`, because a config reload applies per-key deltas to this live object: a copy
726
- // would go stale the moment a person flips the switch.
727
- const memoryReview = memoryReviewConfig(file.memory?.review);
728
- return {
729
- ...DEFAULT_CONFIG,
730
- ...file,
731
- ...(instanceConfig.adapters ? { adapters: instanceConfig.adapters } : {}),
732
- ...(instanceConfig.adapter_modules ? { adapter_modules: instanceConfig.adapter_modules } : {}),
733
- ...(instances ? { instances } : {}),
734
- ...(file.text_projection !== undefined ? { text_projection: projectionConfig(file.text_projection) } : {}),
735
- ...(file.pii !== undefined ? { pii: { paths: policyPaths(file.pii.paths, "pii.paths") } } : {}),
736
- ...(file.data !== undefined ? { data: { readonly: policyPaths(file.data.readonly, "data.readonly") } } : {}),
737
- action_policy: actionPolicyConfig(file.action_policy),
738
- ...(file.edit_governance !== undefined ? { edit_governance: parseEditGovernance(file.edit_governance) } : {}),
739
- permission_modes: { ...instancePermissions, ...permissionDefaults(file.permission_modes, instances, adapterCatalog) },
740
- protect_instruction_files: instructionProtection(file.protect_instruction_files),
741
- instructed: { mode: instructedMode(file.instructed?.mode) },
742
- permission_default_sources: appliedPermissionSources,
743
- memory: { ...DEFAULT_CONFIG.memory, native: true, ...file.memory, ...(file.memory?.short_ttl_days !== undefined ? { short_ttl_days: ttlDays(file.memory.short_ttl_days) } : {}),
744
- ...(file.memory?.sync_interval_min !== undefined ? { sync_interval_min: syncMinutes(file.memory.sync_interval_min) } : {}), review: memoryReview }, // the native store is on with any project config (#258)
745
- roster: peerRosterConfig(file.roster, instances, adapterCatalog, inertModuleRoster),
746
- roles: Object.fromEntries(Object.entries({ ...configuredRoles, ...conductorPolicy.roles, ...extraRoles }).filter(([id]) => !instanceConfig.declaredExternalInstances?.some(row => row.id === id || row.kind === id))),
747
- planner: conductorPolicy.planner,
748
- conductor: conductorPolicy.conductor,
749
- budget: { ...DEFAULT_CONFIG.budget, wait_max_min: 30, ...file.budget }, // on with any project config (issue #36)
750
- context: { ...DEFAULT_CONTEXT, ...file.context },
751
- inference: { ...DEFAULT_CONFIG.inference, ...file.inference },
752
- omniroute: { ...DEFAULT_CONFIG.omniroute, ...file.omniroute },
753
- ...mergeNativeConfiguration(file, DEFAULT_CONFIG),
754
- approvals: {
755
- timeout_s: file.approvals?.timeout_s ?? DEFAULT_CONFIG.approvals.timeout_s,
756
- notify: typeof file.approvals?.notify === "boolean" ? file.approvals.notify : process.platform === "darwin",
757
- },
758
- tasks: { ...DEFAULT_CONFIG.tasks, ...file.tasks, ...(file.tasks?.wip_limits !== undefined ? { wip_limits: planningWipLimits(file.tasks.wip_limits) } : {}) },
759
- bus: { ...DEFAULT_CONFIG.bus, ...file.bus },
760
- adapter_timing: { ...DEFAULT_CONFIG.adapter_timing, ...file.adapter_timing },
761
- model_relay: { ...DEFAULT_CONFIG.model_relay, ...file.model_relay },
762
- console: { ...DEFAULT_CONFIG.console, ...file.console },
763
- task_sweep: taskSweepConfig(file.task_sweep),
764
- schedules: schedulesConfig(file.schedules),
765
- folder_triggers: foldersConfig(file.folder_triggers),
766
- corpus: corpusConfig(file.corpus),
767
- roadmap: roadmapConfig(file.roadmap),
768
- specs: parseSpecsConfig(file.specs),
769
- checks: { ...DEFAULT_CONFIG.checks, ...file.checks, runner: file.checks?.runner === "remote" ? "remote" : file.checks?.runner === "container" ? "container" : undefined,
770
- ...(file.checks?.remote !== undefined || file.checks?.runner === "remote" ? { remote: remoteRunnerConfig(file.checks?.remote) } : {}) },
771
- snapshots: { ...DEFAULT_CONFIG.snapshots, enabled: true, ...file.snapshots },
772
- worktrees: { quiet_days: wholeDays(file.worktrees?.quiet_days, DEFAULT_CONFIG.worktrees.quiet_days), alert_over: wholeDays(file.worktrees?.alert_over, DEFAULT_CONFIG.worktrees.alert_over) },
773
- questions: questionsConfig(file.questions),
774
- visuals: { retention_days: typeof file.visuals?.retention_days === "number" && Number.isSafeInteger(file.visuals.retention_days) && file.visuals.retention_days >= 1 && file.visuals.retention_days <= 3650 ? file.visuals.retention_days : DEFAULT_CONFIG.visuals.retention_days },
775
- research: { enabled: file.research?.enabled === true, ...(file.research?.runners !== undefined ? { runners: parseResearchRunners(file.research.runners) } : {}) }, // opt-in: anything but true is off
776
- bench: { enabled: file.bench?.enabled === true }, // opt-in: a run resets this project's work tree
777
- peers: { ...instanceModes, ...peerStartConfig(file.peers, instances, adapterCatalog) },
778
- terminal: { open: terminalTemplate(file.terminal?.open) },
779
- start: { agents: file.start?.agents === undefined ? [...START_AGENTS_DEFAULT] : checkStartAgents(file.start.agents) },
780
- limits: { ...PROJECT_LIMITS, ...file.limits }, // on with any project config (issue #38)
781
- review: { ...DEFAULT_CONFIG.review, ...file.review },
782
- recovery: { ...DEFAULT_CONFIG.recovery, ...file.recovery },
783
- capabilities: { ...file.capabilities },
784
- mlx,
785
- ...(ignored.length ? { ignored } : {}),
786
- ...(releasePolicyNotices.length ? { releasePolicyNotices } : {}),
787
- ...(retired.length ? { retired } : {}),
788
- };
789
- }
790
-
791
- /** Explicit launch choices are never replaced when the local capability is disabled. */
792
- export function mlxLaunchProblem(config: HubConfig, args: { backend?: unknown; model?: unknown }): string | undefined {
793
- if (config.mlx.enabled !== false) return undefined;
794
- if (args.backend === "mlx" || args.model === "mlx/fast") return "Pi MLX launch conflicts with mlx.enabled=false; select auto or a DGX alias";
795
- return undefined;
796
- }
797
-
798
348
  /** Shipped defaults remain capability-aware; operator-written MLX pins require an explicit migration. */
799
349
  function disabledMlxPolicyProblem(config: HubConfig, cwd: string): string | undefined {
800
350
  if (config.mlx.enabled !== false) return undefined;
@@ -809,6 +359,10 @@ function mlxPinProblem(routing: Routing, project: boolean): string | undefined {
809
359
  }
810
360
 
811
361
  export interface DaemonOptions {
362
+ /** Explicit project context; defaults to `cwd`, `stateDir` and the process environment at start. */
363
+ context?: DaemonProjectContext;
364
+ /** #1779 T3a: set by a host process; reported in `status.json` and the status reply. */
365
+ hostId?: string;
812
366
  /** Host-only fixture override; production reads the active memory home's and execution repository's public Record policy. */
813
367
  effectiveRecordPolicy?: (cwd: string) => { enabled: boolean; version: string } | undefined;
814
368
  /** Host-only test trigger; production schedules its own unreferenced settlement interval. */
@@ -849,12 +403,22 @@ export interface DaemonOptions {
849
403
  kimiHome?: string;
850
404
  /** Host-only delayed-drain scheduler; tests fire it explicitly. Production leaves it unset and uses unreferenced timers. */
851
405
  kimiUsageScheduler?: KimiUsageScheduler;
406
+ /** Test seam for the Claude usage-file poll only. Production uses the default interval. */
407
+ claudeUsagePollMs?: number;
852
408
  /** Host-only replay-window test ceiling (1..512); never read from project config or a tool. */
853
409
  toolWriteReplayMaxEntries?: number;
854
410
  /** Host-only evidence seam; never supplied by project config or control messages. */
855
411
  releaseDocEvidence?: (root: string) => Promise<DocEvidence | undefined>;
856
412
  projectId?: string;
413
+ /** #1780 T1: the hub home that holds `run/<projectId>/mcp.sock`. Only the lifecycle passes it, so a test daemon never writes into the person's hub home. */
414
+ mcpHome?: string;
415
+ /** #1780 T2a-2c: serve MCP on that socket. Off by default and set by no production caller until the relay and channel pushes land (T2b, T4); without it a valid hello still gets -32601. */
416
+ mcpServe?: boolean;
417
+ /** #1780 T2b: the channel evidence of an endpoint session, from the hub's own check of the reported parent (T3 supplies it). Without it every session reads "unknown" and is pull-only, as a bridge without proof is (AC3). */
418
+ mcpChannelEvidence?: (hello: McpHello) => "development-channel-launch" | "inherited-marker" | "launch-unverified" | "unknown";
857
419
  instanceId?: string;
420
+ /** #1811 T2: how often a peer with an unaccepted delivery is checked for a pane that waits for the person; default 30 s. */
421
+ orcaPaneEveryMs?: number;
858
422
  cwd: string;
859
423
  stateDir: string;
860
424
  controlPort: number;
@@ -964,6 +528,8 @@ interface Client {
964
528
  channel?: boolean;
965
529
  channelEvidence?: "development-channel-launch" | "inherited-marker" | "launch-unverified" | "unknown" | "unreported";
966
530
  clientPid?: number;
531
+ /** #1810: the declared account label of the session home; absent for an undeclared home. Never a path. */
532
+ accountLabel?: string;
967
533
  /** #1385: the agent-hub version the client's hello reported, kept only when `displayVersion` accepts it. Display only. */
968
534
  clientVersion?: string;
969
535
  cwd?: string;
@@ -1030,6 +596,8 @@ export async function startDaemon(opts: DaemonOptions) {
1030
596
  // Refuse unknown formats before logs, session cleanup, module factories or any writable store is opened.
1031
597
  assertHubDbCompatible(join(opts.stateDir, "hub.db"));
1032
598
  startupTimings.mark("schema");
599
+ // #1779 T2: the project's identity and child environment, taken once; nothing below reads them from the process.
600
+ const ctx = opts.context ?? daemonProjectContext(opts.cwd, opts.stateDir, process.env);
1033
601
  if (opts.toolWriteReplayMaxEntries !== undefined && (!Number.isSafeInteger(opts.toolWriteReplayMaxEntries) || opts.toolWriteReplayMaxEntries < 1 || opts.toolWriteReplayMaxEntries > 512)) throw new Error("invalid host tool write replay capacity");
1034
602
  const resolveExecutionCwd = (peer: string, currentDeclarations: InstancesConfig | undefined, currentRoles: readonly string[], catalog: ReturnType<typeof createProjectAdapterCatalog>): string =>
1035
603
  resolveInstanceExecutionCwd(opts.cwd, peer, currentDeclarations, currentRoles, catalog, undefined, undefined, opts.instanceExecutionGit);
@@ -1079,6 +647,22 @@ export async function startDaemon(opts: DaemonOptions) {
1079
647
  const lifecycleConfig = opts.sdlc ?? loadSdlc(opts.cwd, VERSION);
1080
648
  /** The file's lifecycle as the status and settings views report it; a supplied fixture config stands in for it. */
1081
649
  const readSdlcFile = () => opts.sdlc ?? loadSdlc(opts.cwd, VERSION);
650
+ function planStructureNotice(task: Task): string | undefined {
651
+ try {
652
+ const rules = readSdlcFile().structure;
653
+ if (!rules) return;
654
+ const plan = tasks.publicView(task).plan as { paths?: string[] } | undefined;
655
+ if (!plan?.paths?.length) return;
656
+ const baseline = readStructureBaseline(join(opts.cwd, rules.baseline));
657
+ if (!baseline) return;
658
+ const paths = plan.paths.filter(path => Object.hasOwn(baseline.sizes, path));
659
+ if (!paths.length) return;
660
+ return structureNotice(rules, baseline, scanStructure(opts.cwd, { ...rules, roots: paths, shared: [] }), paths);
661
+ } catch {
662
+ return;
663
+ }
664
+ }
665
+
1082
666
  // Preserve embedding-owned policy references, but never publish reloads into shared defaults.
1083
667
  const ownedConfig = Object.fromEntries(Object.entries(loadedConfig).map(([key, value]) => [key, !opts.config || value === (DEFAULT_CONFIG as unknown as Record<string, unknown>)[key] ? structuredClone(value) : value])) as unknown as HubConfig;
1084
668
  const adapterCatalog = createProjectAdapterCatalog(loadedConfig.adapters, externalDefinitions);
@@ -1142,6 +726,13 @@ export async function startDaemon(opts: DaemonOptions) {
1142
726
  peers: { ...startModesFromInstances, ...peerStartConfig(loadedConfig.peers, declarations, adapterCatalog) },
1143
727
  ...(extraIds.length ? { permission_default_sources: { ...instancePermissionSources, ...loadedConfig.permission_default_sources } } : {}),
1144
728
  roles, conductor: { ...DEFAULT_CONFIG.conductor, ...loadedConfig.conductor } };
729
+ const [[oldestBridgeProtocol]] = BRIDGE_PROTOCOL_RELEASES;
730
+ const bridgeSettings = bridgeWindowSettings(config.upgrade);
731
+ const requestedBridgeWindow = bridgeProtocolWindow(bridgeSettings, oldestBridgeProtocol, Date.now());
732
+ const bridgeProtocolFloorLimited = requestedBridgeWindow.vMin < PROTOCOL_MIN
733
+ && (bridgeSettings.bridge_window_days > DEFAULT_BRIDGE_WINDOW.bridge_window_days
734
+ || bridgeSettings.bridge_window_min > DEFAULT_BRIDGE_WINDOW.bridge_window_min);
735
+ const acceptedBridgeWindow = { v: PROTOCOL, vMin: Math.max(PROTOCOL_MIN, requestedBridgeWindow.vMin) };
1145
736
  // The resolver and catalogs are bound to this daemon, never published into the process-global builtin registry.
1146
737
  const definitionOf = (peer: string) => adapterCatalog.definitionOf(peer, declarations);
1147
738
  const externalInstanceIds = extraIds.filter(id => externalIds.has(declarations[id]!.kind));
@@ -1185,7 +776,7 @@ export async function startDaemon(opts: DaemonOptions) {
1185
776
  const current = readInstanceConfig(opts.cwd, undefined, externalDefinitions);
1186
777
  const declaration = current.instances?.[peer];
1187
778
  if (!declaration || declaration.kind !== declarations[peer]?.kind) throw new Error("external instance declaration changed");
1188
- const policy = loadConductorPolicy(opts.cwd, undefined, current);
779
+ const policy = loadConductorPolicy(opts.cwd, undefined, current, DEFAULT_ROLES);
1189
780
  const currentRoles = effectiveInstanceRoles(peer, current.instances, policy.roles, current.catalog);
1190
781
  const cwd = resolveExecutionCwd(peer, current.instances, currentRoles, current.catalog);
1191
782
  const binding = externalInstanceBinding(identity, peer, declaration, currentRoles, cwd);
@@ -1209,7 +800,8 @@ export async function startDaemon(opts: DaemonOptions) {
1209
800
  const STARTABLE_PEERS: readonly string[] = [...BASE_STARTABLE_PEERS, ...configuredIds, ...extraIds.filter(id => !channelExtras.includes(id))];
1210
801
  const isSupportedPeer = (peer: unknown): peer is string => adapterCatalog.isSupportedPeer(peer, declarations);
1211
802
  const isStartablePeer = (peer: unknown): peer is string => typeof peer === "string" && !channelExtras.includes(peer) && definitionOf(peer)?.start.conductorStartable === true;
1212
- const RESERVED_IDS = new Set([...BASE_RESERVED_IDS, ...configuredIds, ...extraIds.filter(id => !channelExtras.includes(id))]);
803
+ // #1809: a configured pull kind attaches from the person's terminal (externalHello), so its id is no more reserved than a builtin pull peer's.
804
+ const RESERVED_IDS = new Set([...BASE_RESERVED_IDS, ...configuredIds.filter(id => definitionOf(id)?.attach?.externalHello !== true), ...extraIds.filter(id => !channelExtras.includes(id))]);
1213
805
  // #223 R2: a declared instance whose effective roles are exactly reviewer gets review requests and its own task notices only.
1214
806
  const reviewOnlyPeer = (peer: string): boolean => Object.hasOwn(declarations, peer) && config.roles[peer]?.length === 1 && config.roles[peer]![0] === "reviewer";
1215
807
  /** Display the same runtime form/role ceilings used by declarations; these fields grant no authority. */
@@ -1264,8 +856,17 @@ export async function startDaemon(opts: DaemonOptions) {
1264
856
  };
1265
857
  // #514b: undo resolves the managed checklist key, which is not a settings row, and every other key through the project-scoped lookup above (declared instances, the adapter catalog, a stale roster key).
1266
858
  const undoableDef = (key: unknown): SettingDef | string => key === AUTONOMY_UNDO.key ? AUTONOMY_UNDO : key === LEARN_CHECKLIST.key ? LEARN_CHECKLIST : settingDef(key);
1267
- const accountOf = (peer: string) => definitionOf(peer)?.budget?.account ?? peer;
1268
- const accountMembers = (account: string) => SUPPORTED_PEERS.filter(peer => accountOf(peer) === account);
859
+ // #1810: the budget key of a peer is its account, plus `:<label>` when its session runs under a declared account. An undeclared home keeps the bare key (today's), a key built here
860
+ // resolves to itself (the budget requires an idempotent resolver), and no peer id contains a colon.
861
+ // Any peer that carries an `accountLabel` (the channel peer does) reports it; this is a read of a display label, not a host branch on the peer class.
862
+ // A session's label comes from its home; a daemon-owned instance's from its declared `account` (#1810 AC3), so both budget under `<kind>:<label>`.
863
+ const peerAccountLabel = (peer: string): string | undefined => (bus.peers.get(peer) as { accountLabel?: string } | undefined)?.accountLabel ?? declarations[peer]?.account;
864
+ const accountOf = (peer: string): string => accountKeyFor(peer, definitionOf(peer)?.budget?.account, declarations[peer]?.kind, peerAccountLabel(peer));
865
+ // The account a handoff compares: the budget key, or just its kind when `budget.cross_account_handoff` is off (two labels of one kind are then siblings).
866
+ const handoffAccountOf = (peer: string): string => config.budget.cross_account_handoff === false ? baseAccount(accountOf(peer)) : accountOf(peer);
867
+ // #1810 AC3: a daemon-owned instance that names an account starts with that account's home in its kind's own variable. The home is read here from the loaded config and goes only into the child's environment.
868
+ const instanceAccountEnv = (peer: string): NodeJS.ProcessEnv | undefined => instanceAccountEnvOf(declarations[peer]?.account, config.accounts, definitionOf(peer)?.session.configDirEnv);
869
+ const accountMembers = (account: string) => [...new Set([...SUPPORTED_PEERS, ...Object.keys(declarations)])].filter(peer => accountOf(peer) === account);
1269
870
  let rosterChanging: string | undefined;
1270
871
  let kimiSessionMode: StartMode | undefined;
1271
872
  let kimiAdmissionId: string | undefined;
@@ -1483,6 +1084,8 @@ export async function startDaemon(opts: DaemonOptions) {
1483
1084
  const token = randomBytes(24).toString("hex");
1484
1085
  const nativeHookLaunches = new NativeHookLaunches();
1485
1086
 
1087
+ // #1780 T2a-2c: the control handlers by name, so an MCP endpoint session's Sock-shaped link runs the same `message` and `close` code a WebSocket does.
1088
+ let controlWebsocket!: WebSocketHandler<Client>;
1486
1089
  const server = listenWithoutPortCollision(() => Bun.serve<Client>({
1487
1090
  hostname: "127.0.0.1",
1488
1091
  port: opts.controlPort,
@@ -1491,7 +1094,7 @@ export async function startDaemon(opts: DaemonOptions) {
1491
1094
  if (new URL(req.url).pathname === "/healthz") return new Response("ok");
1492
1095
  return srv.upgrade(req, { data: { authed: false } }) ? undefined : new Response("agent-hub control");
1493
1096
  },
1494
- websocket: {
1097
+ websocket: controlWebsocket = {
1495
1098
  message(sock, data) {
1496
1099
  let parsed: any;
1497
1100
  try {
@@ -1684,6 +1287,12 @@ export async function startDaemon(opts: DaemonOptions) {
1684
1287
  * #685: the provider, model and profile names an extra Jcode instance was declared with, for status, doctor and the dashboard,
1685
1288
  * exactly as the person wrote them (they authenticate inside Jcode). Never a URL, a token or the native home path.
1686
1289
  */
1290
+ // #1809: a configured kind written from a preset shows that preset and its status in `ahub status`.
1291
+ const presetStatusRow = (id: string): { preset?: { id: string; status: "verified" | "untested" } } => {
1292
+ const declared = config.adapters?.[id];
1293
+ const preset = declared && "preset" in declared ? declared.preset : undefined;
1294
+ return preset ? { preset: { id: preset, status: presetStatusById(preset) } } : {};
1295
+ };
1687
1296
  const jcodeModelSource = (id: string): { modelSource?: string } => {
1688
1297
  const instance = declarations[id];
1689
1298
  if (!instance) return {};
@@ -2383,6 +1992,10 @@ export async function startDaemon(opts: DaemonOptions) {
2383
1992
  * hello is refused; a durable record would need a state file the refusal path does not own.
2384
1993
  */
2385
1994
  const jcodeDetached = new Map<string, { cause: string; command: string }>();
1995
+ /** #1795: the last hub-tools hello refused while that peer's owned launch was live and attached. One entry per peer, display only; it never marks the peer detached. */
1996
+ const jcodeRefusedHello = new Map<string, { at: number; pid?: number; command?: string }>();
1997
+ // #1795: the refused-hello record means "the owned launch is serving and a stray process was refused"; it is shown only while that holds.
1998
+ const ownedLaunchServing = (id: string): boolean => { const owner = jcodeLaunches.get(id); return !!owner && owner.ownedLaunchId !== undefined && bus.peers.get(id) === owner && ["idle", "busy", "paused"].includes(bus.stateOf(id)); };
2386
1999
  const globalModelRelay = (relay: ModelRelay) => { modelRelay = relay; };
2387
2000
  const nativeStateDir = (peer: string) => declarations[peer] ? join(opts.stateDir, "instances", peer) : opts.stateDir;
2388
2001
  const instanceAppPorts = new Map<string, number>();
@@ -3349,8 +2962,10 @@ export async function startDaemon(opts: DaemonOptions) {
3349
2962
  offerPullOnly: (id) => { const peer = bus.peers.get(id); return peer?.pullOnly === true; },
3350
2963
  stallNotice: stall => { supervision.taskStalled(stall); },
3351
2964
  get roles() {
3352
- if (!configuredIds.some(id => definitionOf(id)?.start.daemonPort === "configured-print")) return config.roles;
3353
- return Object.fromEntries(Object.entries(config.roles).filter(([id]) => definitionOf(id)?.start.daemonPort !== "configured-print"));
2965
+ // #1809: a kind that declares `tasks: false` (a configured pull kind) is read by the board as having no role at all, so no ownership check can admit it.
2966
+ const owns = (id: string): boolean => definitionOf(id)?.start.daemonPort !== "configured-print" && definitionOf(id)?.tasks !== false;
2967
+ if (configuredIds.every(id => owns(id))) return config.roles;
2968
+ return Object.fromEntries(Object.entries(config.roles).filter(([id]) => owns(id)));
3354
2969
  },
3355
2970
  turnFree,
3356
2971
  coordination: () => config.coordination === "turn-free",
@@ -3570,6 +3185,7 @@ export async function startDaemon(opts: DaemonOptions) {
3570
3185
  const briefPolicy = (root: string) => ({
3571
3186
  privatePath: (path: string) => isDenied(path, config.local.deny) || matchesPolicy(root, path, config.pii?.paths ?? [], true),
3572
3187
  nameable: tasks.nameable,
3188
+ structureRules: (config: unknown) => sdlcConfig(config, VERSION).structure,
3573
3189
  });
3574
3190
  const projectionsFor = (peer: string): TextProjections => {
3575
3191
  const root = executionRoot(peer);
@@ -4245,6 +3861,7 @@ export async function startDaemon(opts: DaemonOptions) {
4245
3861
  const quotaEvents = new QuotaEventFilter(event);
4246
3862
  const budget = new Budget(join(opts.stateDir, "hub.db"), config.budget, instanceBudgetHooks({
4247
3863
  definitionOf,
3864
+ allowSwitchedReading: (peer, _at, origin) => definitionOf(peer)?.start.daemonPort === "codex-appserver" && !!origin?.processStamp,
4248
3865
  pause: (peer) => bus.pause(peer),
4249
3866
  resume: (peer) => {
4250
3867
  if (!manualPaused.has(peer) && !conductorHolds.has(peer)) bus.resume(peer);
@@ -4259,13 +3876,19 @@ export async function startDaemon(opts: DaemonOptions) {
4259
3876
  },
4260
3877
  attached: (peer) => bus.peers.has(peer),
4261
3878
  // Somebody other than the paused peer has to be there, or the handoff would only leave its tasks without an owner.
4262
- canHandOff: (peer) => ![...unsettledReviewerQuota.values()].some(row => row.account === accountOf(peer)) && [...bus.peers.keys()].some((id) => accountOf(id) !== accountOf(peer) && ["idle", "busy"].includes(bus.stateOf(id))),
3879
+ canHandOff: (peer) => ![...unsettledReviewerQuota.values()].some(row => row.account === accountOf(peer)) && [...bus.peers.keys()].some((id) => handoffAccountOf(id) !== handoffAccountOf(peer) && ["idle", "busy"].includes(bus.stateOf(id))),
4263
3880
  // A reading that arrived through a file carries the file's time; a stale one must not look fresh in the export.
4264
3881
  // #683 U1: pauses, resumes and derived resets go to the event log, ids and numbers only.
4265
3882
  ledger: entry => event(entry),
4266
3883
  reading: (peer, windows, hard, at) => { queueMicrotask(() => tasks.refreshReviewerQuotaWaits()); quotaEvents.record(peer, windows.map((w) => ({ id: w.id, used: w.used, ...(w.resetsAt ? { resetsAt: w.resetsAt } : {}) })), hard, at); },
4267
- handoff: (peer, context, urgentOnly) => tasks.reassignForPause(peer, context, urgentOnly),
4268
- resumed: (record) => {
3884
+ handoff: async (peer, context, urgentOnly) => {
3885
+ // #1810: with `budget.cross_account_handoff` off, a peer of the same kind on another declared account is a sibling and never a target (owner or reviewer work).
3886
+ const siblings = handoffSiblings(peer, [...bus.peers.keys()], accountOf, config.budget.cross_account_handoff !== false);
3887
+ const moves = (await tasks.reassignForPause(peer, context, urgentOnly, siblings)).map(move => ({ ...move, from: peer }));
3888
+ for (const entry of handoffEvents(peer, moves, peerAccountLabel, accountOf)) event(entry);
3889
+ return moves;
3890
+ },
3891
+ resumed: (record, renewal) => {
4269
3892
  // Coalesce unread notices without forgetting the public moves they carried.
4270
3893
  const moves = new Map<string, typeof record.moved[number]>();
4271
3894
  const earlier: string[] = [];
@@ -4280,9 +3903,9 @@ export async function startDaemon(opts: DaemonOptions) {
4280
3903
  }
4281
3904
  for (const move of record.moved) moves.set(JSON.stringify([move.id, move.role, move.to, move.title]), move);
4282
3905
  const unreadMoves = [...moves.values()];
4283
- if (definitionOf(record.peer)?.budget?.resetSoftTokensOnResume) kimiUsage.reset(); // a new window: the old counts would pause it again at once
3906
+ if (!renewal && definitionOf(record.peer)?.budget?.resetSoftTokensOnResume) kimiUsage.reset(); // a new window: the old counts would pause it again at once
4284
3907
  const moved = unreadMoves.length ? `While you were paused these moved: ${unreadMoves.map((m) => `${m.title} (${m.role} -> ${m.to ?? "nobody"})`).join("; ")}. They stay where they are; ask the user if you should take one back.` : earlier.length ? "Moves from earlier pauses are preserved in the unread notices below." : "Nothing was moved while you were paused.";
4285
- bus.publish(newEnvelope(HUB, `Your quota window has reset and the hub has resumed you (paused since ${new Date(record.since).toLocaleTimeString()}, ${record.reason}). ${moved}${earlier.length ? ` Earlier unread resume notices: ${earlier.join("\n")}` : ""} Messages queued for you follow.`, { to: [record.peer], kind: "budget", priority: "important", refs: { budgetResume: record.peer, budgetResumeMoves: unreadMoves, ...(earlier.length ? { budgetResumeEarlier: earlier } : {}) } }));
3908
+ bus.publish(newEnvelope(HUB, `${renewal ? "Your quota readings were renewed and the hub has resumed you" : "Your quota window has reset and the hub has resumed you"} (paused since ${new Date(record.since).toLocaleTimeString()}, ${record.reason}). ${moved}${earlier.length ? ` Earlier unread resume notices: ${earlier.join("\n")}` : ""} Messages queued for you follow.`, { to: [record.peer], kind: "budget", priority: "important", refs: { budgetResume: record.peer, budgetResumeMoves: unreadMoves, ...(earlier.length ? { budgetResumeEarlier: earlier } : {}) } }));
4286
3909
  // Publish the complete replacement before removing its evidence. A failed write keeps the old notices.
4287
3910
  for (const id of superseded) bus.withdraw(id);
4288
3911
  },
@@ -4294,12 +3917,15 @@ export async function startDaemon(opts: DaemonOptions) {
4294
3917
  const startupEvents = startupSeeds.events;
4295
3918
  budget.seedResets(startupEvents.flatMap(e => e.type === "quota_reset" ? [{ peer: e.peer, window: e.window, ...(e.resetsAt !== undefined ? { resetsAt: e.resetsAt } : {}) }] : []));
4296
3919
  // #285 phase 2: Kimi's consumption is the hub's own count of its session wire log (`src/adapters/kimi-wire-usage.ts`), not an ACP total.
4297
- const softTokenAccount = (peer: string): boolean => definitionOf(accountOf(peer))?.budget?.resetSoftTokensOnResume === true;
3920
+ const softTokenAccount = (peer: string): boolean => definitionOf(baseAccount(accountOf(peer)))?.budget?.resetSoftTokensOnResume === true;
3921
+ const softTokenBudget = adapterCatalog.definitions.find(def => def.budget?.resetSoftTokensOnResume)?.budget;
3922
+ const softTokenRenewalAt = () => softTokenBudget && budget.renewalAt(softTokenBudget.account);
4298
3923
  const kimiEvents = new KimiEventWriter({ append: event, read: () => readEvents(join(opts.stateDir, "events.jsonl")) }, startupEvents);
4299
3924
  const kimiUsage = new KimiUsage({
4300
3925
  home: opts.kimiHome ?? process.env.KIMI_CODE_HOME ?? join(homedir(), ".kimi-code"),
4301
3926
  now: () => Date.now(),
4302
3927
  ceiling: () => config.budget.kimi_tokens_5h,
3928
+ renewalAt: softTokenRenewalAt,
4303
3929
  session: peer => contextSession(peer),
4304
3930
  schedule: opts.kimiUsageScheduler ?? ((delay, run) => {
4305
3931
  const timer = setTimeout(run, delay); timer.unref?.();
@@ -4309,12 +3935,13 @@ export async function startDaemon(opts: DaemonOptions) {
4309
3935
  kimiEvents.write(peer, row, counted, attributed);
4310
3936
  applyKimiTokens(peer, counted, attributed);
4311
3937
  },
4312
- report: (peer, window) => budget.report(peer, [{ id: "tokens", kind: "count", used: window.used, resetsAt: window.resetsAt, source: `hub count, kimi wire log, of kimi_tokens_5h ${window.ceiling}` }]),
3938
+ report: (peer, window) => budget.reportKimiCount(peer, window),
4313
3939
  forget: peer => budget.forget(peer, "tokens", "count"),
4314
3940
  notice: line => notify(line),
4315
3941
  });
4316
3942
  startupCleanup.push(() => kimiUsage.stop());
4317
- kimiUsage.seed(kimiSeedRows(startupEvents, Math.max(0, ...startupEvents.flatMap(e => e.type === "budget_resume" && definitionOf(e.peer)?.budget?.resetSoftTokensOnResume ? [Date.parse(e.at)] : []).filter(Number.isFinite))));
3943
+ const kimiResumedAt = Math.max(0, ...startupEvents.flatMap(e => e.type === "budget_resume" && definitionOf(e.peer)?.budget?.resetSoftTokensOnResume ? [Date.parse(e.at)] : []).filter(Number.isFinite));
3944
+ kimiUsage.seed(kimiSeedRows(startupEvents, kimiResumedAt, softTokenRenewalAt()));
4318
3945
  if (!reviewerJournalComplete) {
4319
3946
  // ponytail: a damaged journal cannot prove which owned attempts settled. Keep soft counts unknown;
4320
3947
  // recovery needs a verified settlement, not a guessed expiry from a host start/cap timestamp.
@@ -4407,13 +4034,15 @@ export async function startDaemon(opts: DaemonOptions) {
4407
4034
  const windowStart = resetsAt !== null && windowMins > 0 ? resetsAt - windowMins * 60_000 : null;
4408
4035
  // A stale reading is no usable reading, so its forecast is never served from the cache, never cached, and never
4409
4036
  // computed from points it would not look at (the page polls every second, and a stale row is what a pause leaves).
4410
- const key = `${peer}\0${window.id}\0${window.at}`;
4037
+ const renewedAt = budget.renewalAt(peer);
4038
+ const key = `${peer}\0${window.id}\0${window.kind}\0${window.at}\0${window.used}\0${resetsAt ?? ""}\0${renewedAt ?? ""}\0${budget.forecastReadingVersion(window) ?? ""}`;
4411
4039
  const cached = window.stale ? undefined : projectionCache.get(key);
4412
4040
  const projection = cached && now - cached.at < PROJECTION_TTL_MS ? cached.value : (() => {
4413
4041
  const value = projectExhaustion({
4414
- used: window.used, windowStart, resetsAt, now, stale: window.stale,
4042
+ used: window.used, windowStart, resetsAt, now, stale: window.stale, renewedAt, baseline: budget.forecastBaseline(peer, window),
4415
4043
  lookbackMs: windowMins > 0 ? Math.min(PROJECTION_LOOKBACK_MS, windowMins * 60_000) : PROJECTION_LOOKBACK_MS,
4416
- points: windowStart === null || window.stale ? [] : usageRollup.points(peer, windowStart, now),
4044
+ points: windowStart === null || window.stale || (renewedAt !== undefined && windowStart < renewedAt)
4045
+ ? [] : usageRollup.points(peer, windowStart, now),
4417
4046
  });
4418
4047
  /* ponytail: the cache is per reading and cleared whole past 256 entries; a per-window expiry is the upgrade if a project ever holds more. */
4419
4048
  if (!window.stale) {
@@ -4426,7 +4055,16 @@ export async function startDaemon(opts: DaemonOptions) {
4426
4055
  }
4427
4056
  /** The same view for one peer's row and for a whole status: `left` and the projection ride each window, never the summary. */
4428
4057
  function windowRow(peer: string, row: BudgetRowStatus) {
4429
- return { ...row, windows: row.windows.map(window => windowView(peer, window)) };
4058
+ const now = Date.now();
4059
+ const windows = row.windows.map(window => windowView(peer, window));
4060
+ const warnings = row.paused ? [] : windows.flatMap(window => {
4061
+ if (window.stale || window.superseded) return [];
4062
+ const at = earlyBudgetWarning(window.projection, window.resetsAt, now);
4063
+ return at === undefined ? [] : [{ window: window.id, at }];
4064
+ });
4065
+ const def = definitionOf(peer);
4066
+ return { ...row, windows, ...(warnings.length ? { warnings } : {}),
4067
+ ...(def?.budget && !def.budget.quotaExempt ? { renewable: true } : {}) };
4430
4068
  }
4431
4069
  function budgetViews(status: ReturnType<Budget["status"]>): ReturnType<Budget["status"]> {
4432
4070
  return Object.fromEntries(Object.entries(status).map(([peer, row]) => [peer, windowRow(peer, row)]));
@@ -5102,6 +4740,26 @@ export async function startDaemon(opts: DaemonOptions) {
5102
4740
  };
5103
4741
  // Claude's numbers arrive through the status line tee `ahub claude` installs (src/cli/statusline-tee.ts).
5104
4742
  let claudeUsageSeen = 0;
4743
+ const accountUsageSeen = new Map<string, number>();
4744
+ const pollAccountUsage = () => {
4745
+ // #1810: one reading per declared claude account, from the file its home's sessions tee. Keyed `claude:<label>`; a reading for an undeclared home stays with the bare key above.
4746
+ for (const [label, declared] of Object.entries(config.accounts ?? {})) {
4747
+ if (!isClaudeAccountKind(declared.kind)) continue;
4748
+ try {
4749
+ const file = join(opts.stateDir, `claude-usage.${homeTag(declared.home)}.json`);
4750
+ const mtime = statSync(file).mtimeMs;
4751
+ if (accountUsageSeen.get(label) === mtime) continue;
4752
+ accountUsageSeen.set(label, mtime);
4753
+ const usage = JSON.parse(readFileSync(file, "utf8"));
4754
+ for (const adapter of ADAPTERS.filter(adapter => adapter.transport === "claude-channel")) {
4755
+ const windows = readNativeQuota(adapter, usage.rate_limits);
4756
+ if (windows) budget.report(accountKey(adapter.kind, label), windows, false, Number(usage.at) || mtime, undefined);
4757
+ }
4758
+ } catch {
4759
+ // this account has no session yet, or a half-written file: next round
4760
+ }
4761
+ }
4762
+ };
5105
4763
  let bandsRevision = ""; // #481 S7: the board revision and band configuration the last band evaluation that ran saw
5106
4764
  let bandEvaluations = 0; // evaluations that ran (not skipped for an unchanged board); read by tests through the daemon
5107
4765
  const claudeContextSeen = new Map<string, string>();
@@ -5190,7 +4848,26 @@ export async function startDaemon(opts: DaemonOptions) {
5190
4848
  if (mergeReadbackTimer) clearInterval(mergeReadbackTimer);
5191
4849
  };
5192
4850
  startupCleanup.push(async () => { stopMergeReadbackSchedule(); await mergeReadbackPass; });
4851
+ // #1811 T2: a delivery unaccepted for two minutes in a peer's recorded Orca pane asks Orca for that pane's state, at most once a minute per peer.
4852
+ const paneWatch = new OrcaPaneWatch({ run: orcaAgentRunner(orcaExecutable) });
4853
+ const paneTick = async () => {
4854
+ if (stopping || recoveryActive()) return;
4855
+ const before = JSON.stringify(paneWatch.blocked());
4856
+ for (const id of [...bus.peers.keys()]) {
4857
+ const oldest = bus.queueSummary(id).oldestQueuedAt;
4858
+ let pane: { handle: string; paneKey: string; worktreeId: string } | undefined;
4859
+ if (stopping || recoveryActive()) return;
4860
+ if (paneWatch.due(oldest)) {
4861
+ const found = await launcherOf(id, opts.cwd, { stateDir: opts.stateDir, instanceId }).catch(() => undefined);
4862
+ const record = found?.state === "live" ? found.record : undefined;
4863
+ if (record?.paneKey) pane = { handle: record.handle, paneKey: record.paneKey, worktreeId: record.worktreeId };
4864
+ }
4865
+ await paneWatch.check(id, oldest, pane);
4866
+ }
4867
+ if (before !== JSON.stringify(paneWatch.blocked())) writeStatus();
4868
+ };
5193
4869
  const intervals = [
4870
+ setInterval(() => { void paneTick().catch(() => log("orca pane check failed; the item keeps its state")); }, opts.orcaPaneEveryMs ?? 30_000),
5194
4871
  setInterval(() => {
5195
4872
  try { sweepInvocations(); } catch { log("invocation deadline sweep failed; the rows keep their state"); }
5196
4873
  try { sweepAcceptedChannelDeliveries(); } catch { log("accepted channel delivery sweep failed; the rows keep their state"); }
@@ -5269,21 +4946,24 @@ export async function startDaemon(opts: DaemonOptions) {
5269
4946
  // A verified context path whose hooks stopped altogether has no boundary left to notice it at (issue #108).
5270
4947
  setInterval(() => { for (const peer of [...capable]) checkCapability(peer); }, 30_000),
5271
4948
  setInterval(() => {
4949
+ pollAccountUsage();
5272
4950
  try {
5273
4951
  const file = join(opts.stateDir, "claude-usage.json");
5274
4952
  const mtime = statSync(file).mtimeMs;
5275
4953
  if (mtime === claudeUsageSeen) return;
5276
4954
  claudeUsageSeen = mtime;
5277
4955
  const usage = JSON.parse(readFileSync(file, "utf8"));
4956
+ if (isDeclaredReading(usage.home, config.accounts, homeTag)) return; // a declared home has its own key; it must not pause the default one
5278
4957
  // The file's own timestamp, not "now": a file left behind by yesterday's session is a stale reading, not a fresh one.
5279
4958
  for (const adapter of ADAPTERS.filter(adapter => adapter.transport === "claude-channel")) {
5280
4959
  const windows = readNativeQuota(adapter, usage.rate_limits);
5281
- if (windows) budget.report(adapter.kind, windows, false, Number(usage.at) || mtime);
4960
+ if (windows) budget.report(adapter.kind, windows, false, Number(usage.at) || mtime, undefined,
4961
+ { forecastSession: { sessionId: usage.sessionId, launchId: usage.launchId } });
5282
4962
  }
5283
4963
  } catch {
5284
4964
  // no tee in this session, or a half-written file: next round
5285
4965
  }
5286
- }, 5_000),
4966
+ }, opts.claudeUsagePollMs ?? 5_000),
5287
4967
  ];
5288
4968
  let sweepTimer: ReturnType<typeof setInterval> | undefined;
5289
4969
  const rescheduleSweep = () => {
@@ -5388,7 +5068,7 @@ export async function startDaemon(opts: DaemonOptions) {
5388
5068
  // names are answered by the hub; every call still passes daemon role/capability checks before its effects.
5389
5069
  const HUB_TOOLS = ["hub_send", ...[...TASK_TOOL_NAMES].filter(name => name !== "hub_set_title" && (!["hub_evidence_record", "hub_evidence_read"].includes(name) || resolvedProfile.name === "research")), ...CONDUCTOR_TOOLS.map((t) => t.name)];
5390
5070
  const HUB_TOOL_TITLES = new Set(HUB_TOOLS.map((name) => `mcp__agent-hub__${name}`));
5391
- const toolEnv = (peer: PeerId, deliveryOnly = false) => ({ ...(deliveryOnly ? { AGENTHUB_DELIVERY_ONLY: "true" } : {}), AGENTHUB_MODE: "tools", AGENTHUB_PEER_ID: peer, AGENTHUB_STATE_DIR: opts.stateDir, AGENTHUB_PROJECT_DIR: opts.cwd });
5071
+ const toolEnv = (peer: PeerId, deliveryOnly = false) => ({ ...(deliveryOnly ? { AGENTHUB_DELIVERY_ONLY: "true" } : {}), AGENTHUB_MODE: "tools", AGENTHUB_PEER_ID: peer, ...projectChildEnv(ctx) });
5392
5072
 
5393
5073
  /** One entry point for the task tools, whoever calls them: MCP clients, the local worker, the console. */
5394
5074
  // A task op can write the board across awaits (triage, briefs, the dependents an approval releases): a recovery
@@ -6104,7 +5784,7 @@ export async function startDaemon(opts: DaemonOptions) {
6104
5784
  return { ok: true, guidance: excluded || stopping || recoveryActive() || bus.isRecoveryHeld ? { state: "unavailable" }
6105
5785
  : op === "list" ? tasks.guidanceVariantList(by, input) : tasks.guidanceVariantDiff(by, input) };
6106
5786
  }
6107
- async function taskOpBody(by: PeerId, op: string, a: Record<string, any>, inProcess = false, piiTurn = false): Promise<string> {
5787
+ async function taskOpBody(by: PeerId, op: string, a: Record<string, any>, inProcess = false, piiTurn = false, toolSocket?: Sock): Promise<string> {
6108
5788
  if (startupSpecPending() && specRoutingOps.has(op)) {
6109
5789
  await firstSpecProbe;
6110
5790
  // refusal:by-design world-action: routing is held by the hub until it finishes stopping or recovering.
@@ -6577,20 +6257,22 @@ export async function startDaemon(opts: DaemonOptions) {
6577
6257
  const repoHint = tasks.refsRepoHint(t); // #723: advice only; never part of the write
6578
6258
  const submodules = tasks.submoduleNotice(t); // #798 D1: advice only too
6579
6259
  const specs = tasks.specNotice(t, by);
6580
- if (t.state === "backlog") return [line(t), specs, repoHint, submodules].filter(Boolean).join("\n");
6260
+ const structure = planStructureNotice(t);
6261
+ if (t.state === "backlog") return [line(t), specs, structure, repoHint, submodules].filter(Boolean).join("\n");
6581
6262
  const overlap = tasks.overlaps(t, t.owner === by);
6582
6263
  if (t.owner === by && tasks.silentFor(t.id) && factsOn()) factsFor(by).sawPlans(by, tasks.overlapTasks(t)); // as for an accept
6583
- return [line(t), specs, tasks.namedOwnerNote(t, a.owner as PeerId | undefined, by), overlap, tasks.claimRoleGuidance(t, by), t.owner === by ? tasks.planGuardText(t) : "", repoHint, submodules].filter(Boolean).join("\n");
6264
+ return [line(t), specs, structure, tasks.namedOwnerNote(t, a.owner as PeerId | undefined, by), overlap, tasks.claimRoleGuidance(t, by), t.owner === by ? tasks.planGuardText(t) : "", repoHint, submodules].filter(Boolean).join("\n");
6584
6265
  }
6585
6266
  case "hub_task_accept": {
6586
6267
  // S1 spec acceptance and S9 plan review are checked against one task snapshot before acceptance.
6587
6268
  const t = await tasks.acceptReviewed(by, a.id, a.plan, a.refs);
6588
6269
  const specs = tasks.specNotice(t, by);
6270
+ const structure = planStructureNotice(t);
6589
6271
  // A silent cohort (issue #107): the owners' plans come with every accept, as what the newcomer works from.
6590
6272
  const silent = tasks.silentFor(t.id);
6591
6273
  const overlap = a.plan == null && a.refs == null && !silent ? "" : tasks.overlaps(t);
6592
6274
  if (silent && factsOn()) factsFor(by).sawPlans(by, tasks.overlapTasks(t)); // the plans in this answer need no fact later
6593
- return [line(t), specs, overlap, tasks.planGuardText(t), tasks.submoduleNotice(t), tasks.worktreeNote(t, by)].filter(Boolean).join("\n"); // #798 D1
6275
+ return [line(t), specs, structure, overlap, tasks.planGuardText(t), tasks.submoduleNotice(t), tasks.worktreeNote(t, by)].filter(Boolean).join("\n"); // #798 D1
6594
6276
  }
6595
6277
  case "hub_task_cancel": {
6596
6278
  if (!a || typeof a !== "object" || Array.isArray(a) || Object.keys(a).some(key => !["id", "reason", "superseded_by", "revision"].includes(key))
@@ -6648,7 +6330,12 @@ export async function startDaemon(opts: DaemonOptions) {
6648
6330
  }
6649
6331
  case "hub_remember": {
6650
6332
  const reviewCard = reviewTurnCard(by);
6651
- const { message: saved, outcome } = await tasks.rememberOutcome(by, a, reviewCard);
6333
+ const owner = by === USER ? undefined : bus.peers.get(by);
6334
+ // Socket-owned sessions must come from the active attachment. The native adapters publish their session through host-owned metadata.
6335
+ const writerSession = owner && owner.state !== "offline" && (!owner.ownsSocket || (toolSocket && owner.ownsSocket(toolSocket)))
6336
+ ? recordOwners.get(owner)?.session() ?? owner.nativeSession
6337
+ : undefined;
6338
+ const { message: saved, outcome } = await tasks.rememberOutcome(by, a, reviewCard, writerSession);
6652
6339
  // #1329 AC4: on a review card a note is a proposal, and the done report counts it by kind.
6653
6340
  if (reviewCard && outcome === "candidate") reviewCount(reviewCard.id, "remembered");
6654
6341
  // #1279: a saved note that names another entry cites it. `tasks.remember` already refused a PII task, a private path and a secret, so only a note it saved gets here.
@@ -7949,6 +7636,7 @@ export async function startDaemon(opts: DaemonOptions) {
7949
7636
  if (crashLostIds.size) { try { for (const row of bus.queueList(undefined, true)) if (row.state === "needs_review" && crashLostIds.has(row.id)) inFlight++; } catch { inFlight = crashLostIds.size; } }
7950
7637
  return openCrashNotices(crashNotices, { attached, inFlight });
7951
7638
  };
7639
+ let mcpEndpoint: McpEndpoint | undefined;
7952
7640
  const status = (includeAttentionItems = false, includeAttentionInput = false, includeDoing = false, includeIncomingLabels = false, includeActivity = false) => {
7953
7641
  const taskNeeds = board.statusTasks();
7954
7642
  const ownerIsolation = ownerIsolationProjection();
@@ -7968,6 +7656,7 @@ export async function startDaemon(opts: DaemonOptions) {
7968
7656
  ...(crashLines.length ? { crash: crashLines } : {}),
7969
7657
  projectId,
7970
7658
  instanceId,
7659
+ ...(opts.hostId ? { hostId: opts.hostId } : {}), // #1779: the host process this project runs in; `pid` is then the host's
7971
7660
  ...roomCommands.statusSnapshot(),
7972
7661
  version: VERSION,
7973
7662
  pluginBundle: SERVER_JS,
@@ -7988,7 +7677,7 @@ export async function startDaemon(opts: DaemonOptions) {
7988
7677
  ...(taskSweepConfig(config.task_sweep).enabled ? { taskWait: true } : {}),
7989
7678
  // Every supported peer's membership, for launchers that run outside the console role (#484).
7990
7679
  roster: [...KNOWN_PEERS, ...OPTIONAL_PEERS].map(peer => ({ peer, on: onRoster(peer) })),
7991
- protocol: PROTOCOL_MIN, protocolMin: PROTOCOL_MIN, protocolMax: PROTOCOL,
7680
+ protocol: acceptedBridgeWindow.vMin, protocolMin: acceptedBridgeWindow.vMin, protocolMax: acceptedBridgeWindow.v, bridgeProtocolFloorLimited,
7992
7681
  features: DAEMON_FEATURES,
7993
7682
  configuredAdapters: configuredIds,
7994
7683
  ...(externalAdapters.length ? { externalAdapters } : {}),
@@ -8011,10 +7700,11 @@ export async function startDaemon(opts: DaemonOptions) {
8011
7700
  pid: process.pid,
8012
7701
  cwd: opts.cwd,
8013
7702
  controlPort: server.port,
7703
+ ...(mcpEndpoint ? { mcpSocket: mcpEndpoint.path } : {}),
8014
7704
  ...(dashboard ? { uiOrigin: dashboard.origin } : {}),
8015
7705
  codexProxyPort: opts.codexProxyPort,
8016
7706
  peers: Object.fromEntries(
8017
- peerIds.map((id) => { const p = bus.peers.get(id); const summary = bus.queueSummary(id); const pressure = queueBackpressure?.peers[id]; const oldestQueuedAt = pressure ? pressure.oldestQueuedAt : summary.oldestQueuedAt; const context = contexts.view(id, contextSession(id), !!p && ["idle", "busy", "paused"].includes(bus.stateOf(id))); const statusNotice = isFixedBuiltinDefinition(definitionOf(id)) ? p?.statusNotice : undefined; const reviewObserverHoldNote = reviewObserverSessionIdentityHoldNote(id); const detached = jcodeDetached.get(id); return [id, { state: bus.stateOf(id), ...(includeAttentionItems && isExternalInstance(id) && !externalRefusedRows.has(id) && retainedExternalBinding(id) ? { externalInstance: retainedExternalBinding(id) } : {}), ...(!membershipAllowed(id) ? { rostered: false, rosterNote: "off roster" } : {}), ...permissionStatus(id, p), ...(statusNotice ? { statusNotice } : {}), ...(detached ? { detached } : {}), ...(reviewObserverHoldNote ? { reviewObserverHoldNote } : {}), ...(context.source !== null || context.measuredAt !== null ? { context } : {}), queued: bus.queued(id), ...(p ? {} : { attached: false }), ...(includeAttentionItems && p?.standbySessions?.length ? { standbySessions: p.standbySessions } : {}), ...(includeAttentionItems && p?.ownerAttachment ? { ownerAttachment: p.ownerAttachment } : {}), ...(declarations[id] && config.roles[id]?.includes("implementer") && definitionOf(id)?.transport === "claude-channel" ? { ownerIsolation: ownerIsolation[id] === true, ...(ownerIsolation[id] !== true ? { ownerIsolationNote: "terminal execution root not verified; owner admission refused" } : {}) } : {}), ...(summary.needsReview ? { needsReview: summary.needsReview } : {}), ...(summary.liveAccepted ? { liveAccepted: summary.liveAccepted, settlementNote: "awaiting adapter completion (Claude: correlated reply or hub_delivery_done); task state is independent" } : {}), ...queueHoldStatus(id, summary.heldBy), ...(typeof oldestQueuedAt === "number" ? { oldestQueuedAt } : {}), ...(bus.queuedImportant(id) ? { queuedImportant: bus.queuedImportant(id) } : {}), ...importantWaitingStatus(id, p), ...pausedNote(id), ...(reviewerUnavailable.has(id) ? { reviewerUnavailable: reviewerUnavailable.get(id) } : {}), ...jcodeModelSource(id), ...(reviewOnlyPeer(id) ? { reviewScope: reviewScopeOf(id) } : {}), ...(isLocalPeer(p) && p.lastServedBy ? { servedBy: p.lastServedBy } : {}), ...(isWsPeer(p) ? { ...(p.claiming ? { claiming: true } : {}), ...(definitionOf(id)?.transport === "claude-channel" && p.attached ? { attachMode: p.attachMode, attachEvidence: p.attachEvidence } : {}) } : {}), ...(isWsPeer(p) && p.pullOnly ? { pullOnly: true, toolsOnly: definitionOf(id)?.attach?.pullOnlyNotice ?? "tools-only: messages wait for hub_inbox; for pushes restart Claude with ahub claude", lastInboxAt: p.lastInboxAt ?? null } : {}), ...(isPiPeer(p) ? { requestedModel: p.getRequestedModel(), backends: modelRelays.get(id)?.status().backends ?? [] } : {}) }]; }),
7707
+ peerIds.map((id) => { const p = bus.peers.get(id); const summary = bus.queueSummary(id); const pressure = queueBackpressure?.peers[id]; const oldestQueuedAt = pressure ? pressure.oldestQueuedAt : summary.oldestQueuedAt; const context = contexts.view(id, contextSession(id), !!p && ["idle", "busy", "paused"].includes(bus.stateOf(id))); const statusNotice = isFixedBuiltinDefinition(definitionOf(id)) ? p?.statusNotice : undefined; const reviewObserverHoldNote = reviewObserverSessionIdentityHoldNote(id); const detached = jcodeDetached.get(id); return [id, { state: bus.stateOf(id), ...(includeAttentionItems && isExternalInstance(id) && !externalRefusedRows.has(id) && retainedExternalBinding(id) ? { externalInstance: retainedExternalBinding(id) } : {}), ...(!membershipAllowed(id) ? { rostered: false, rosterNote: "off roster" } : {}), ...permissionStatus(id, p), ...(statusNotice ? { statusNotice } : {}), ...(detached ? { detached } : {}), ...(jcodeRefusedHello.has(id) && ownedLaunchServing(id) ? { refusedHello: jcodeRefusedHello.get(id) } : {}), ...(reviewObserverHoldNote ? { reviewObserverHoldNote } : {}), ...(context.source !== null || context.measuredAt !== null ? { context } : {}), queued: bus.queued(id), ...(p ? {} : { attached: false }), ...(includeAttentionItems && p?.standbySessions?.length ? { standbySessions: p.standbySessions } : {}), ...(includeAttentionItems && p?.ownerAttachment ? { ownerAttachment: p.ownerAttachment } : {}), ...(declarations[id] && config.roles[id]?.includes("implementer") && definitionOf(id)?.transport === "claude-channel" ? { ownerIsolation: ownerIsolation[id] === true, ...(ownerIsolation[id] !== true ? { ownerIsolationNote: "terminal execution root not verified; owner admission refused" } : {}) } : {}), ...presetStatusRow(id), ...(summary.needsReview ? { needsReview: summary.needsReview } : {}), ...(summary.liveAccepted ? { liveAccepted: summary.liveAccepted, settlementNote: "awaiting adapter completion (Claude: correlated reply or hub_delivery_done); task state is independent" } : {}), ...queueHoldStatus(id, summary.heldBy), ...(typeof oldestQueuedAt === "number" ? { oldestQueuedAt } : {}), ...(bus.queuedImportant(id) ? { queuedImportant: bus.queuedImportant(id) } : {}), ...importantWaitingStatus(id, p), ...pausedNote(id), ...(reviewerUnavailable.has(id) ? { reviewerUnavailable: reviewerUnavailable.get(id) } : {}), ...jcodeModelSource(id), ...(reviewOnlyPeer(id) ? { reviewScope: reviewScopeOf(id) } : {}), ...(isLocalPeer(p) && p.lastServedBy ? { servedBy: p.lastServedBy } : {}), ...(isWsPeer(p) ? { ...(p.claiming ? { claiming: true } : {}), ...(definitionOf(id)?.transport === "claude-channel" && p.attached ? { attachMode: p.attachMode, attachEvidence: p.attachEvidence } : {}) } : {}), ...(isWsPeer(p) && p.pullOnly ? { pullOnly: true, toolsOnly: definitionOf(id)?.attach?.pullOnlyNotice ?? "tools-only: messages wait for hub_inbox; for pushes restart Claude with ahub claude", lastInboxAt: p.lastInboxAt ?? null } : {}), ...(isPiPeer(p) ? { requestedModel: p.getRequestedModel(), backends: modelRelays.get(id)?.status().backends ?? [] } : {}) }]; }),
8018
7708
  ),
8019
7709
  peerVersions,
8020
7710
  taskWip: tasks.wipBreakdown(peerIds),
@@ -8074,11 +7764,28 @@ export async function startDaemon(opts: DaemonOptions) {
8074
7764
  recovery: recoveryOperationId ? { id: recoveryOperationId, running: true } : undefined,
8075
7765
  tasks: taskNeeds,
8076
7766
  results: unreadResults().map(result => ({ id: result.id, peer: result.peer, since: result.settledAt })),
7767
+ panes: paneWatch.blocked().map(pane => ({ peer: pane.peer, handle: pane.handle, since: pane.since })),
8077
7768
  facts: [...taskStalls.map(stall => ({ kind: "stall" as const, id: stall.task })), ...pendingTaskOffers.map(offer => ({ kind: "offer" as const, id: offer.task, peer: offer.peer }))],
8078
- budget: Object.fromEntries(Object.entries(budget.status()).map(([peer, row]) => [peer, row.paused ? { paused: { since: row.paused.since, resetsAt: row.paused.resetsAt } } : {}])),
7769
+ budget: Object.fromEntries(Object.entries(budget.status()).map(([peer, row]) => [peer, row.paused
7770
+ ? { paused: { since: row.paused.since, resetsAt: row.paused.resetsAt } }
7771
+ : includeAttentionItems || includeAttentionInput ? { warnings: windowRow(peer, row).warnings } : {}])),
8079
7772
  };
8080
7773
  const attention = needs(attentionInput, Date.now());
8081
- return { ...view, ...(includeAttentionInput ? { attentionInput } : {}), needs: { act: attention.act, watch: attention.watch, state: attention.state, ...(attention.items[0] ? { first: attention.items[0] } : {}) },
7774
+ // #1798: the one hub check, built from the finished peer rows; every surface renders this result.
7775
+ const hubCheck = buildHubCheck({ version: VERSION, controlPort: server.port ?? 0, peers: peerIds.map(id => {
7776
+ const row = view.peers[id] as Record<string, any> | undefined, def = definitionOf(id);
7777
+ const attached = !!bus.peers.get(id) && ["idle", "busy", "paused"].includes(bus.stateOf(id)) && row?.attached !== false;
7778
+ const detached = jcodeDetached.get(id);
7779
+ // The expected link comes from the adapter definition and the form the peer is started in, never from the observed link: a push peer that
7780
+ // drops to pull-only must still be expected to push. Pull-only by design: a ws-pull transport (agy), and a form the definition lists in
7781
+ // attach.pullOnlyForms (the Kimi TUI). The hub keeps no launch form for any other peer, so those are expected to push.
7782
+ const form = def?.attach?.admission ? (kimiSessionMode ?? startMode(id)) : startMode(id); // a definition with native admission keeps its pending launch form
7783
+ const expected = expectedHubLink(def, form);
7784
+ const nextStep = detached?.command ?? startCommand(id);
7785
+ return { id, expected, attached, starting: starting.has(id), pullOnly: row?.pullOnly === true,
7786
+ ...(typeof row?.attachEvidence === "string" ? { evidence: row.attachEvidence } : {}), detached: !!detached, queued: Number(row?.queued ?? 0), nextStep };
7787
+ }) });
7788
+ return { ...view, hubCheck, ...(includeAttentionInput ? { attentionInput } : {}), needs: { act: attention.act, watch: attention.watch, state: attention.state, ...(attention.items[0] ? { first: attention.items[0] } : {}) },
8082
7789
  ...(includeAttentionItems ? { attentionItems: attention.items } : {}) };
8083
7790
  };
8084
7791
  // #226: who owns this manifest, beyond a pid that a reboot can hand to another process. Only the file carries it
@@ -8945,7 +8652,10 @@ export async function startDaemon(opts: DaemonOptions) {
8945
8652
  opening.set(peer, Date.now());
8946
8653
  if (resume && (stopping || recoveryActive() || !membershipAllowed(peer) || rosterChanging === peer || requestedPeerStops.has(peer))) { opening.delete(peer); return { ok: false, error: "Pi lifecycle changed before its continuity terminal opened; bookmark retained" }; }
8947
8654
  // Every word is the hub's own: its runtime, its entry point, this project and a peer from the closed list.
8948
- const opened = await opener.open(`${peer} (agent-hub)`, [process.execPath, CLI_ENTRY, "--project", opts.cwd, ...words]).catch((error: Error) => ({ ok: false as const, why: "the terminal provider failed", detail: error.message }));
8655
+ // #1811: an extra implementer's terminal lands in the Orca workspace of its own worktree; the base peer, and any peer whose root cannot be resolved, use the project root.
8656
+ let terminalRoot: string | undefined;
8657
+ try { const root = resolveExecutionCwd(peer, declarations, config.roles[peer] ?? [], adapterCatalog); if (root !== opts.cwd) terminalRoot = root; } catch { /* the opener falls back to the project root */ }
8658
+ const opened = await opener.open(`${peer} (agent-hub)`, [process.execPath, CLI_ENTRY, "--project", opts.cwd, ...words], terminalRoot).catch((error: Error) => ({ ok: false as const, why: "the terminal provider failed", detail: error.message }));
8949
8659
  if (!opened.ok) {
8950
8660
  opening.delete(peer); // nothing was opened: the next request may try again at once
8951
8661
  if (opened.detail) log(`terminal provider for ${peer}: ${opened.detail}`);
@@ -9154,7 +8864,7 @@ export async function startDaemon(opts: DaemonOptions) {
9154
8864
  if (!onRoster(peer)) return { ok: false, error: "qwen is off roster; a person can add it with ahub roster add qwen" };
9155
8865
  if (existing && existing.state !== "offline") return { ok: false, error: "Qwen is running headless; run ahub stop qwen before starting its TUI" };
9156
8866
  // The compat entry of the dual-output contract, not the headless ACP entry: 0.26.1 only.
9157
- const verdict = await qwenDualVersionAsync(config.qwen_cmd, executionCwd);
8867
+ const verdict = await qwenDualVersionAsync(config.qwen_cmd, executionCwd, ctx.env);
9158
8868
  startCurrent?.();
9159
8869
  if (!verdict.ok) return { ok: false, error: verdict.reason };
9160
8870
  if (verdict.note) log(verdict.note);
@@ -9205,7 +8915,7 @@ export async function startDaemon(opts: DaemonOptions) {
9205
8915
  ...(isFixedBuiltinDefinition(adapter) && adapter.modelOverride?.acp ? { modelPolicy: adapter.modelOverride.acp } : {}),
9206
8916
  providerProfile: (args.providerProfile ?? instance?.provider_profile ?? config.jcode_provider_profile) || undefined,
9207
8917
  ...(instance?.provider ? { provider: instance.provider } : {}),
9208
- ...(args.model ?? instance?.model ? { launchModel: (args.model ?? instance?.model)! } : {}), ...(args.sessionId ? { resumeSessionId: args.sessionId } : {}), cwd: executionCwd, watchdogMs: config.watchdog_ms,
8918
+ ...(args.model ?? instance?.model ? { launchModel: (args.model ?? instance?.model)! } : {}), ...(args.sessionId ? { resumeSessionId: args.sessionId } : {}), cwd: executionCwd, env: ctx.env, watchdogMs: config.watchdog_ms,
9209
8919
  toolCeilingMs: adapterTiming.acpToolCeilingMs(), activityBatchMs: adapterTiming.acpActivityBatchMs(), steerTimeoutMs: adapterTiming.jcodeSteerTimeoutMs(),
9210
8920
  tuiHintContext: () => ({ tui: startMode(peer) === "tui", afterCrash: crashReported }),
9211
8921
  preamble: sessionRoleContract(peer), log: () => log("Jcode native diagnostic: details withheld"),
@@ -9233,7 +8943,8 @@ export async function startDaemon(opts: DaemonOptions) {
9233
8943
  try { startCurrent?.(); await jcode.start(); startCurrent?.(); registerModelOwner(jcode); bindRecordOwner(jcode, executionCwd, () => jcode.nativeSession); await reconcileNativeStart(peer, jcode, startCurrent); }
9234
8944
  catch { await jcode.stop().catch(() => {}); if (jcodeLaunches.get(peer) === jcode) jcodeLaunches.delete(peer); throw new Error("Jcode startup not verified; check native version, provider profile, MCP store and owned daemon (details withheld)"); }
9235
8945
  // #1668: this peer is under the hub again, so it is no longer detached. A start that failed above keeps the record.
9236
- if (jcodeDetached.delete(peer) && !stopping) writeStatus();
8946
+ const clearedDetached = jcodeDetached.delete(peer), clearedRefused = jcodeRefusedHello.delete(peer);
8947
+ if ((clearedDetached || clearedRefused) && !stopping) writeStatus();
9237
8948
  return { ok: true, policy: "unmanaged" };
9238
8949
  }
9239
8950
  if (adapter?.start.acpCommand) {
@@ -9251,7 +8962,7 @@ export async function startDaemon(opts: DaemonOptions) {
9251
8962
  permissionMode: permissionMode(peer),
9252
8963
  ...(args.model ? { launchModel: args.model } : {}),
9253
8964
  ...(args.sessionId ? { resumeSessionId: args.sessionId } : {}),
9254
- cwd: executionCwd,
8965
+ cwd: executionCwd, env: ctx.env,
9255
8966
  watchdogMs: config.watchdog_ms,
9256
8967
  onPermission,
9257
8968
  // The hub's own tools pass without a console prompt, as Codex's do (approval_mode below; issue #72).
@@ -9262,7 +8973,7 @@ export async function startDaemon(opts: DaemonOptions) {
9262
8973
  log,
9263
8974
  // Pause synchronously before the adapter requeues a provider-refused prompt (#306).
9264
8975
  onQuotaRefusal: (window) => {
9265
- budget.report(peer, [window], true);
8976
+ budget.report(peer, [window], true, Date.now(), undefined, { turnStartedAt: turns.get(peer)?.start });
9266
8977
  return !!budget.record(peer) && bus.isPaused(peer);
9267
8978
  },
9268
8979
  // Kimi's usage_update is context occupancy ({used, size}), not consumption (#167): it becomes the peer's
@@ -9397,7 +9108,7 @@ export async function startDaemon(opts: DaemonOptions) {
9397
9108
  actionBudgets.revoke(peer);
9398
9109
  startCurrent?.();
9399
9110
  const codex: CodexPeer = adapter!.start.create!({ instance: peer, projectRoot: opts.cwd, stateDir: opts.stateDir, kindConfig: config, permission: permissionMode(peer), mcpServers: [], daemon: DAEMON_PORTS["codex-appserver"]({
9400
- activityServers: codexActivityServers(process.env.CODEX_HOME?.trim() || join(homedir(), ".codex"), executionCwd),
9111
+ activityServers: codexActivityServers(instanceAccountEnv(peer)?.CODEX_HOME || process.env.CODEX_HOME?.trim() || join(homedir(), ".codex"), executionCwd),
9401
9112
  getModelOverride: () => modelSelection(peer),
9402
9113
  onNativeModelApplied: model => { if (!stopping && bus.peers.get(peer) === codex && isNativeModelToken(model)) {
9403
9114
  try { modelLatches.observeNative(peer, codex, model); } catch { modelLatches.forget(peer); }
@@ -9469,10 +9180,11 @@ export async function startDaemon(opts: DaemonOptions) {
9469
9180
  ...HUB_TOOLS.map((name) => [`tools.${name}.approval_mode`, '"approve"']),
9470
9181
  ].flatMap(([k, v]) => ["-c", `mcp_servers.agent-hub.${k}=${v}`]),
9471
9182
  preamble: sessionRoleContract(peer),
9472
- onUsage: (rateLimits, hard, accountUsage) => { const windows = readNativeQuota(adapter, rateLimits); if (windows) budget.report(peer, windows, hard, Date.now(), accountUsage); },
9183
+ onUsage: (rateLimits, hard, accountUsage, origin) => { const windows = readNativeQuota(adapter, rateLimits); if (windows) budget.report(peer, windows, hard, Date.now(), accountUsage, origin); },
9473
9184
  usagePause: { current: () => budget.record(peer) !== undefined, subscribe: changed => budget.watchPause(peer, changed) },
9474
9185
  usagePollMs: config.budget.poll_min * 60_000,
9475
9186
  cwd: executionCwd,
9187
+ env: { ...ctx.env, ...(instanceAccountEnv(peer) ?? {}) },
9476
9188
  watchdogMs: config.watchdog_ms,
9477
9189
  log,
9478
9190
  }) }) as CodexPeer;
@@ -9905,7 +9617,7 @@ export async function startDaemon(opts: DaemonOptions) {
9905
9617
  const implementer = adapter.start.create!({ instance: peer, projectRoot: opts.cwd, stateDir: opts.stateDir, kindConfig: config, permission: selected, mcpServers: [], daemon: DAEMON_PORTS["claude-implementer"]({
9906
9618
  getModelOverride: () => modelSelection(peer),
9907
9619
  cwd: executionCwd, stateDir: opts.stateDir, projectRoot: opts.cwd, instanceId, server: SERVER_JS,
9908
- factsHook: join(import.meta.dir, "..", "cli", "facts-hook.ts"), systemPrompt: sessionRoleContract(peer), mode: selected, watchdogMs: config.watchdog_ms, ...(declarations[peer]?.model ? { model: declarations[peer].model } : {}),
9620
+ factsHook: join(import.meta.dir, "..", "cli", "facts-hook.ts"), systemPrompt: sessionRoleContract(peer), mode: selected, watchdogMs: config.watchdog_ms, ...(declarations[peer]?.model ? { model: declarations[peer].model } : {}), ...(instanceAccountEnv(peer) ? { accountEnv: instanceAccountEnv(peer)! } : {}),
9909
9621
  beforeInput: (context, envs) => beforeOwnedObserverInput(peer, implementer, context, envs),
9910
9622
  inputReleased: (context, envs) => ownedObserverInputReleased(peer, implementer, context, envs),
9911
9623
  admit: env => {
@@ -10003,11 +9715,13 @@ export async function startDaemon(opts: DaemonOptions) {
10003
9715
  },
10004
9716
  facts: env => env.private ? undefined : reviewDiff(executionCwd, env.refs?.commit, { privatePath: path => isDenied(path, config.local.deny) || matchesPolicy(executionCwd, path, config.pii?.paths ?? [], true), nameable: tasks.nameable }),
10005
9717
  verdictSince: (task, since) => board.get(task)?.history.some(h => h.by === peer && h.at >= since && (h.event === "approved" || h.event === "changes_requested")) === true,
10006
- onQuota: (value, attempt, current) => {
9718
+ onQuota: (value, attempt, current, turnStartedAt) => {
10007
9719
  const reading = nativeReviewerQuota(value);
10008
9720
  if (!reading || !current() || bus.peers.get(peer) !== reviewer || !/^[a-f0-9]{32}$/.test(attempt)) return false;
9721
+ const renewedAt = budget.renewalAt(peer);
9722
+ if (renewedAt !== undefined && turnStartedAt < renewedAt) return false;
10009
9723
  unsettledReviewerQuota.set(attempt, { account: accountOf(peer), peer });
10010
- budget.report(peer, [reading], true);
9724
+ budget.report(peer, [reading], true, Date.now(), undefined, { turnStartedAt });
10011
9725
  return budget.record(peer) !== undefined;
10012
9726
  },
10013
9727
  quotaSettled: attempt => {
@@ -10042,14 +9756,14 @@ export async function startDaemon(opts: DaemonOptions) {
10042
9756
  const safe = visible && hostSafe && diagnostic.refusal !== undefined && boundedSafe(diagnostic.refusal) && tasks.publicMetadataText(diagnostic.refusal) ? diagnostic.refusal : undefined;
10043
9757
  log(reviewerNoVerdictLine(peer, diagnostic, safe, !visible));
10044
9758
  },
10045
- onUnavailable: (failure, current) => {
9759
+ onUnavailable: (failure, current, turnStartedAt) => {
10046
9760
  const attached = () => current() && bus.peers.get(peer) === reviewer;
10047
9761
  if (!attached()) return false;
10048
9762
  if (failure.cause === "quota") {
10049
9763
  const readings = (failure.quota ?? []).map(nativeReviewerQuota).filter((row): row is NonNullable<typeof row> => row !== undefined);
10050
9764
  // ponytail: reviewer-only children have no attached native quota transport. Only an attached account sibling
10051
9765
  // or Budget's existing evaluate/expiry paths can end a pause; never infer an early reset here.
10052
- if (readings.length && !budget.record(peer)) budget.report(peer, readings, true);
9766
+ if (readings.length && !budget.record(peer)) budget.report(peer, readings, true, Date.now(), undefined, { turnStartedAt });
10053
9767
  // Canonical account handoff may already have moved this exact review while applying the hard pause.
10054
9768
  if (!tasks.reviewBindingCurrent(peer, failure.task, failure)) return true;
10055
9769
  }
@@ -10199,6 +9913,8 @@ export async function startDaemon(opts: DaemonOptions) {
10199
9913
  return {
10200
9914
  id: row.id, peer: row.peer, state: row.state, revision: row.revision,
10201
9915
  ...(row.failureCause ? { failureCause: row.failureCause } : {}),
9916
+ // #1795: the stored reason of a failed or held delivery, through the same private and public rules as its bodies.
9917
+ ...(detail && row.reason ? { reason: publicDeliveryReason(originals, row.reason, { publicOnly, taskPrivate: id => { const task = board.get(Number(id)); return !task || tasks.isPii(task); }, publicMetadataText: text => tasks.publicMetadataText(text) }) } : {}),
10202
9918
  ...roomChat.evidence(row.peer, row.id),
10203
9919
  ...(detail && bus.deliveryResolution(row.id) ? { resolvedBy: bus.deliveryResolution(row.id) } : {}),
10204
9920
  ...(!membershipAllowed(row.peer) ? { rostered: false, holdReason: "off roster" } : {}),
@@ -12193,7 +11909,7 @@ export async function startDaemon(opts: DaemonOptions) {
12193
11909
  let child: ReturnType<typeof Bun.spawn>;
12194
11910
  const inherited = { data: client, get readyState() { return open ? WebSocket.OPEN : WebSocket.CLOSED; }, send: (text: string) => child.send(JSON.parse(text)), close: () => { open = false; child.disconnect(); }, getBufferedAmount: () => 0 } as unknown as Sock;
12195
11911
  child = Bun.spawn({ cmd: [instructedRuntime.bun, join(instructedRuntime.root, "src/cli/main.js"), ...argv],
12196
- cwd: opts.cwd, env: { ...personEnv(process.env), AGENTHUB_INSTRUCTED_IPC: "1", AGENTHUB_STATE_DIR: opts.stateDir, AGENTHUB_PROJECT_DIR: opts.cwd },
11912
+ cwd: opts.cwd, env: { ...personEnv(ctx.env), AGENTHUB_INSTRUCTED_IPC: "1", ...projectChildEnv(ctx) },
12197
11913
  stdin: "ignore", stdout: "pipe", stderr: "pipe", serialization: "json",
12198
11914
  ipc(message) {
12199
11915
  try {
@@ -12354,10 +12070,16 @@ export async function startDaemon(opts: DaemonOptions) {
12354
12070
  if (!c.authed) {
12355
12071
  if (msg.t !== "hello" || msg.token !== token) return sock.close(4401, "bad token");
12356
12072
  if (typeof msg.peer === "string" && msg.peer.includes("@")) return sock.close(4403, "remote identities have no control connection");
12357
- const offered = protocolWindow(msg.v, msg.vMin), selectedProtocol = offered && negotiateProtocol({ v: PROTOCOL, vMin: PROTOCOL_MIN }, offered);
12073
+ const offered = protocolWindow(msg.v, msg.vMin), selectedProtocol = offered && negotiateProtocol(acceptedBridgeWindow, offered);
12358
12074
  if (selectedProtocol === undefined) {
12359
12075
  // An outdated plugin would drop every digest without a trace. Refuse it loudly instead.
12360
- log(`refused ${msg.role} ${msg.peer ?? ""}: wire version ${msg.v ?? 1}, hub speaks ${PROTOCOL} (claude plugin update agent-hub@agent-hub)`);
12076
+ const implemented = offered && negotiateProtocol({ v: PROTOCOL, vMin: PROTOCOL_MIN }, offered) !== undefined;
12077
+ const next = implemented
12078
+ ? "check upgrade.bridge_window_days and upgrade.bridge_window_min"
12079
+ : "update the agent-hub plugin (claude plugin update agent-hub@agent-hub)";
12080
+ const wire = offered ? `bridge wire offer ${offered.vMin}–${offered.v}`
12081
+ : msg.v === undefined ? "wire version 1" : "bridge wire offer invalid";
12082
+ log(`refused ${msg.role} ${msg.peer ?? ""}: ${wire}; hub accepts ${acceptedBridgeWindow.vMin}–${acceptedBridgeWindow.v}; ${next}`);
12361
12083
  return sock.close(4426, `wire version mismatch: hub speaks ${PROTOCOL}; update the agent-hub plugin`);
12362
12084
  }
12363
12085
  if ((msg.projectId && msg.projectId !== projectId) || (msg.instanceId && msg.instanceId !== instanceId) ||
@@ -12410,7 +12132,10 @@ export async function startDaemon(opts: DaemonOptions) {
12410
12132
  if (!owner || !owner.ownsLaunch(msg.launchId)) {
12411
12133
  // #1668: this peer's socket is served by a server the hub did not start, so the peer is offline here while that work goes on. The refusal
12412
12134
  // itself is unchanged and nothing new listens; the peer only gains the state `ahub status` reports until a hub-owned launch replaces it.
12413
- if (!stopping) { jcodeDetached.set(c.peer, jcodeDetachedNotice(c.peer)); writeStatus(); }
12135
+ // #1795: with the owned launch live and attached, the refused hello is a stray process, not a detached peer: name it and leave the peer's state alone.
12136
+ const live = !!owner && owner.ownedLaunchId !== undefined && bus.peers.get(c.peer) === owner && ["idle", "busy", "paused"].includes(bus.stateOf(c.peer));
12137
+ if (!stopping && live) { jcodeRefusedHello.set(c.peer, { at: Date.now(), ...refusedHelloProcess(msg.clientPid) }); writeStatus(); }
12138
+ else if (!stopping) { jcodeRefusedHello.delete(c.peer); jcodeDetached.set(c.peer, jcodeDetachedNotice(c.peer)); writeStatus(); }
12414
12139
  return sock.close(4403, "this process is not an owned launch of that peer; start it with ahub jcode");
12415
12140
  }
12416
12141
  }
@@ -12447,6 +12172,8 @@ export async function startDaemon(opts: DaemonOptions) {
12447
12172
  if (typeof msg.cwd === "string" && msg.cwd.length <= 4096) sock.data.cwd = msg.cwd;
12448
12173
  const clientPid = Number.isSafeInteger(msg.clientPid) && msg.clientPid > 0 && msg.clientPid <= 2_147_483_647 ? msg.clientPid as number : undefined;
12449
12174
  sock.data.clientPid = clientPid;
12175
+ // #1810: the session's home becomes a declared label here and the path goes no further; an undeclared home is the default label, which sets nothing.
12176
+ { const label = labelForHome(msg.home, definitionOf(c.peer)?.budget?.account ?? declarations[c.peer]?.kind ?? c.peer, config.accounts); if (label !== DEFAULT_ACCOUNT_LABEL) sock.data.accountLabel = label; else delete sock.data.accountLabel; }
12450
12177
  sock.data.clientVersion = c.clientVersion;
12451
12178
  const pushOverPullOnly = msg.channel !== false && ws.attached && ws.pullOnly && !ws.claiming;
12452
12179
  const hasLiveHolder = ws.attached || ws.claiming;
@@ -12478,7 +12205,7 @@ export async function startDaemon(opts: DaemonOptions) {
12478
12205
  // #604 PR B: one attach event per admitted peer or tools hello, with the same fields an envelope's `origin` carries. A refused hello returned above and writes none.
12479
12206
  if (c.role === "tools" && !c.session) toolsSockets.add(sock);
12480
12207
  if (c.role === "peer" || c.role === "tools") event(attachEvent({ role: c.role, peer: c.peer, launchId: c.launchId, ...(c.session ? { session: true } : {}) }));
12481
- return void reply({ t: "welcome", projectId, instanceId, cwd: opts.cwd, protocol: c.protocol, protocolMin: PROTOCOL_MIN, protocolMax: PROTOCOL, features: DAEMON_FEATURES,
12208
+ return void reply({ t: "welcome", projectId, instanceId, cwd: opts.cwd, protocol: c.protocol, protocolMin: acceptedBridgeWindow.vMin, protocolMax: acceptedBridgeWindow.v, features: DAEMON_FEATURES,
12482
12209
  ...(c.session ? { session: c.peer } : {}), ...(c.standbyId ? { standby: true, standbyId: c.standbyId } : {}) });
12483
12210
  }
12484
12211
  const committedSourceProof = c.role === "tools" && msg.t === "recovery_authority" && msg.op === "verify" && recoveryCommitted
@@ -13674,6 +13401,57 @@ export async function startDaemon(opts: DaemonOptions) {
13674
13401
  })().catch(() => reply({ ok: false, error: "public lifecycle readback unavailable" }));
13675
13402
  return;
13676
13403
  }
13404
+ if (msg.op === "sync") {
13405
+ // #1856 T3: a preview writes nothing; apply re-plans and refuses before any write unless the fingerprint still matches.
13406
+ if (c.role !== "console" && c.role !== "tools") return void reply({ ok: false, error: "ahub sdlc sync is for the person or a tools session; run it from a terminal" });
13407
+ if (c.peer && (!!turns.get(c.peer)?.private || contextPii(c.peer))) return void reply({ ok: false, error: "ahub sdlc sync is unavailable in a private turn; finish it and retry" });
13408
+ const apply = msg.apply === true, asker = c.role === "console" ? USER : c.peer;
13409
+ if (apply && (!asker || typeof msg.confirm !== "string" || !/^[a-f0-9]{64}$/.test(msg.confirm))) return void reply({ ok: false, error: "apply needs the fingerprint of a preview; run ahub sdlc sync, then ahub sdlc sync --apply --confirm <fingerprint>" });
13410
+ const repository = githubOriginRepository(opts.cwd);
13411
+ const writeRoadmap = msg.writeRoadmap === true, closeSettled = msg.closeSettled === true;
13412
+ if (closeSettled) { try { tasks.closeSettledGate(asker ?? USER); } catch (error) { return void reply({ ok: false, error: sanitize(error instanceof Error ? error.message : "closing settled issues is not permitted") }); } }
13413
+ const planNow = () => planSdlcSync({
13414
+ ...(writeRoadmap ? { roadmap: { tracked: msg.roadmapTracked === true, render: () => tasks.roadmapExport(asker ?? USER) } } : {}),
13415
+ ...(closeSettled ? { closeSettled: { cards: board.list().map(task => ({ id: task.id, state: task.state, pii: tasks.isPii(task), ...(task.sdlc?.repo ? { repo: task.sdlc.repo } : {}), ...(task.sdlc?.issue ? { issue: task.sdlc.issue } : {}), ...(task.sdlc?.pr ? { pr: task.sdlc.pr } : {}) })) } } : {}),
13416
+ repository, authority: asker === USER ? "person" : `conductor:${asker ?? "none"}:${lifecycleConfig.mode}`,
13417
+ gh: (args, timeout, _cwd, bound) => sdlcGh(args, timeout, opts.cwd, bound),
13418
+ tasks: board.list().filter(task => ["proposed", "in_progress", "in_review", "changes_requested"].includes(task.state)).map(task => {
13419
+ const pii = tasks.isPii(task);
13420
+ return { id: task.id, state: task.state, // not tasks.publicTitle: it prefixes `#<id> `, which the title parser would read as an issue.
13421
+ title: pii ? "" : task.title, pii, ...(task.refs.repo && !pii ? { refsRepo: task.refs.repo } : {}),
13422
+ branches: !pii && task.refs.branch ? [task.refs.branch] : [], historyLength: task.history.length,
13423
+ ...(task.sdlc && !pii ? { sdlc: { ...(task.sdlc.repo ? { repo: task.sdlc.repo } : {}), ...(task.sdlc.issue ? { issue: task.sdlc.issue } : {}), ...(task.sdlc.pr ? { pr: task.sdlc.pr } : {}), ...(task.sdlc.localHead ? { localHead: task.sdlc.localHead } : {}), ...(task.sdlc.reviewedHead ? { reviewedHead: task.sdlc.reviewedHead } : {}) } } : {}) };
13424
+ }),
13425
+ });
13426
+ if (!apply) {
13427
+ void planNow().then(plan => reply({ ok: true, apply: false, options: { writeRoadmap, closeSettled }, ...plan }), error => reply({ ok: false, error: `sync plan unavailable (${error instanceof Error ? error.name : "unknown error"}); run ahub sdlc check and retry` }));
13428
+ return;
13429
+ }
13430
+ taskOpsInFlight++;
13431
+ void (async () => {
13432
+ const plan = await planNow();
13433
+ if (plan.fingerprint !== msg.confirm) return reply({ ok: false, error: `the board, origin or authority changed since the preview; review ahub sdlc sync and confirm the new fingerprint ${plan.fingerprint}`, fingerprint: plan.fingerprint });
13434
+ const results: { task: number; kind: string; ok: boolean; error?: string }[] = [];
13435
+ for (const op of plan.operations) {
13436
+ try {
13437
+ if (op.kind === "link") tasks.recordSyncRepair(asker!, op.task, { repo: op.repo, issue: op.issue });
13438
+ else if (op.kind === "bind") tasks.recordSyncRepair(asker!, op.task, { repo: op.repo, pr: op.pr, localHead: op.localHead });
13439
+ else await tasks.adoptMerge(asker!, op.task, op.pr);
13440
+ results.push({ task: op.task, kind: op.kind, ok: true });
13441
+ } catch (error) { results.push({ task: op.task, kind: op.kind, ok: false, error: sanitize(error instanceof Error ? error.message : "refused") }); }
13442
+ }
13443
+ for (const close of plan.closes) {
13444
+ try { await tasks.closeSettledIssue(asker!, close.repo, close.issue); results.push({ task: 0, kind: `close #${close.issue}`, ok: true }); }
13445
+ catch (error) { results.push({ task: 0, kind: `close #${close.issue}`, ok: false, error: sanitize(error instanceof Error ? error.message : "refused") }); }
13446
+ }
13447
+ let roadmapFiles: { json: string; markdown: string } | undefined;
13448
+ if (plan.roadmap) {
13449
+ try { const files = await tasks.roadmapExport(asker!); roadmapFiles = { json: files.json, markdown: files.markdown }; } catch { results.push({ task: 0, kind: "roadmap refresh", ok: false, error: "the roadmap could not be rendered; run ahub roadmap export" }); }
13450
+ }
13451
+ reply({ ok: true, apply: true, fingerprint: plan.fingerprint, results, ambiguous: plan.ambiguous, headMoved: plan.headMoved, withheld: plan.withheld, ...(roadmapFiles ? { roadmapFiles } : {}) });
13452
+ })().catch((error: Error) => reply({ ok: false, error: sanitize(error.message) })).finally(() => { taskOpsInFlight--; });
13453
+ return;
13454
+ }
13677
13455
  if (c.role !== "console") return void reply({ ok: false, error: "SDLC readback is console only; task owners record ids through hub_sdlc_record" });
13678
13456
  if (msg.op === "queue" || msg.op === "release") {
13679
13457
  if (typeof msg.repo !== "string" || !Array.isArray(msg.liveIssues ?? []) || (msg.liveIssues ?? []).length > 32) return void reply({ ok: false, error: "invalid delivery readback arguments" });
@@ -13717,9 +13495,35 @@ export async function startDaemon(opts: DaemonOptions) {
13717
13495
  }, () => reply({ ok: false, error: "issue edit time unavailable; nothing was recorded" }));
13718
13496
  return;
13719
13497
  }
13498
+ // #1856 T2: the read-only audit. Open to the person and to agents; it writes nothing, shows public titles only and counts private tasks.
13499
+ if (msg.op === "check") {
13500
+ const offline = msg.offline === true, repository = githubOriginRepository(opts.cwd);
13501
+ const checkGh: SdlcGh = (args, timeout, _cwd, bound) => sdlcGh(args, timeout, opts.cwd, bound);
13502
+ const roleHolders = (role: string) => Object.keys(config.roles).filter(peer => config.roles[peer]!.includes(role) && projectRosterAllows(config.roster, peer, config.pi.enabled)).sort();
13503
+ const unsettled = board.list().filter(task => ["proposed", "in_progress", "in_review", "changes_requested"].includes(task.state));
13504
+ const tracked = hubGitSync(["ls-files", "--error-unmatch", "docs/roadmap.json"], { cwd: opts.cwd, encoding: "utf8", timeout: 5000 }).status === 0;
13505
+ void runSdlcCheck({
13506
+ offline, repository, gh: checkGh,
13507
+ running: { mode: lifecycleConfig.mode, requiredChecks: lifecycleConfig.requiredChecks, effectiveChecks: requiredChecksFor(lifecycleConfig, repository) },
13508
+ file: () => { const exists = existsSync(join(opts.cwd, ".agenthub", "sdlc.toml")); return { present: exists, config: loadSdlc(opts.cwd, VERSION) }; },
13509
+ holders: { planner: roleHolders("planner"), reviewer: roleHolders("reviewer"), conductor: roleHolders("conductor") },
13510
+ discover: run => discoverInitChecks(opts.cwd, run),
13511
+ securityScan: () => ({ configured: !!lifecycleConfig.securityScan, counts: tasks.securityScanCounts() }),
13512
+ tasks: unsettled.map(task => { const pii = tasks.isPii(task); return { id: task.id, state: task.state, title: pii ? "" : tasks.publicTitle(task), pii, ...(task.refs.branch && !pii ? { branch: task.refs.branch } : {}), ...(task.sdlc && !pii ? { sdlc: { ...(task.sdlc.repo ? { repo: task.sdlc.repo } : {}), ...(task.sdlc.issue ? { issue: task.sdlc.issue } : {}), ...(task.sdlc.pr ? { pr: task.sdlc.pr } : {}), ...(task.sdlc.localHead ? { localHead: task.sdlc.localHead } : {}) } } : {}) }; }),
13513
+ ...(board.milestones().length || tracked ? { roadmap: {
13514
+ drift: () => tasks.roadmapCheck(USER),
13515
+ unplaced: () => tasks.roadmapUnplaced(USER, {}, checkGh),
13516
+ } } : {}),
13517
+ }).then(report => reply({ ok: true, ...report }), error => reply({ ok: false, error: `lifecycle audit unavailable (${error instanceof Error ? error.name : "unknown error"}); run ahub sdlc status and retry` }));
13518
+ return;
13519
+ }
13720
13520
  if (msg.op !== "status" && msg.op !== "explain") return void reply({ ok: false, error: "unknown SDLC operation" });
13721
- const selected = msg.id === undefined ? board.list().filter(task => task.state !== "backlog" && (task.sdlc || lifecycleConfig.mode !== "off" || lifecycleConfig.workflow === "gsd-lite")) : [board.get(Number(msg.id))].filter((task): task is Task => !!task);
13722
- if (msg.id !== undefined && (!Number.isSafeInteger(msg.id) || msg.id <= 0 || !selected.length)) return void reply({ ok: false, error: "invalid lifecycle task id" });
13521
+ const listed = msg.id === undefined ? board.list().filter(task => task.state !== "backlog" && (task.sdlc || lifecycleConfig.mode !== "off" || lifecycleConfig.workflow === "gsd-lite")) : [board.get(Number(msg.id))].filter((task): task is Task => !!task);
13522
+ if (msg.id !== undefined && (!Number.isSafeInteger(msg.id) || msg.id <= 0 || !listed.length)) return void reply({ ok: false, error: "invalid lifecycle task id" });
13523
+ // #1856 T1: a bare status lists the unsettled tasks and those of a release train not yet shipped; `all` keeps the historical first-100 slice, a task id is unchanged.
13524
+ const unsettledOnly = msg.op === "status" && msg.id === undefined && msg.all !== true;
13525
+ const openTrains = unsettledOnly ? new Set(board.releases().filter(release => release.state !== "shipped" && release.state !== "dropped").map(release => release.id)) : undefined;
13526
+ const selected = unsettledOnly ? listed.filter(task => ["proposed", "in_progress", "in_review", "changes_requested"].includes(task.state) || (task.release != null && openTrains!.has(task.release))) : listed;
13723
13527
  void (async () => {
13724
13528
  const rows = [];
13725
13529
  for (const task of selected.slice(0, 100)) {
@@ -13727,7 +13531,7 @@ export async function startDaemon(opts: DaemonOptions) {
13727
13531
  const current = board.get(task.id) ?? task;
13728
13532
  rows.push({ id: task.id, title: tasks.publicTitle(current), ...(tasks.isPii(current) ? {} : { receipt: tasks.publicView(current).sdlc }), ...status });
13729
13533
  }
13730
- reply({ ok: true, mode: lifecycleConfig.mode, rows, ...(tasks.securityScanCounts() ? { securityScan: tasks.securityScanCounts() } : {}), truncated: selected.length > 100 });
13534
+ reply({ ok: true, mode: lifecycleConfig.mode, rows, ...(tasks.securityScanCounts() ? { securityScan: tasks.securityScanCounts() } : {}), truncated: selected.length > 100, ...(unsettledOnly ? { unsettledOnly: true, hiddenSettled: listed.length - selected.length } : {}) });
13731
13535
  })().catch(() => reply({ ok: false, error: "lifecycle readback unavailable" }));
13732
13536
  return;
13733
13537
  }
@@ -13802,15 +13606,21 @@ export async function startDaemon(opts: DaemonOptions) {
13802
13606
  case "status": {
13803
13607
  const sendStatus = () => {
13804
13608
  const current = status(c.role === "console", false, true, c.role === "console" || (c.role === "tools" || c.role === "peer") && c.peer === conductorPeer(config.roles), c.role === "console");
13609
+ // #1798 T3, display only: whether this tools connection runs under the launch the peer's current channel socket attached with. It labels a startup
13610
+ // notice and decides nothing: not admission, routing, delivery or permissions. Anyone holding the control token can send any launch id, so it is
13611
+ // a hint, never evidence. Per request, never cached or stored; the launch id itself is never returned, logged or recorded. Absent for every
13612
+ // other requester: a console, a minted session, a hub-owned tools child, a connection with no launch id, or a peer that is not a Claude channel.
13613
+ const thisLaunch = c.role === "tools" && !c.session && !c.toolsOwner && c.peer && c.launchId && definitionOf(c.peer)?.transport === "claude-channel"
13614
+ ? { thisLaunch: (bus.peers.get(c.peer) as { managedLaunchId?: unknown } | undefined)?.managedLaunchId === c.launchId } : {};
13805
13615
  if ((c.role === "console" || c.role === "tools") && msg.specs === true) {
13806
13616
  const summary = projectSpecs.status();
13807
13617
  if (summary) {
13808
13618
  const missingBlockHint = !specsMissingBlockHintShown && projectSpecs.missingBlock() === true;
13809
13619
  if (missingBlockHint) specsMissingBlockHintShown = true;
13810
- return void reply({ t: "status", status: { ...current, specs: { ...summary, ...(missingBlockHint ? { missingBlockHint: true } : {}) } } });
13620
+ return void reply({ t: "status", status: { ...current, ...thisLaunch, specs: { ...summary, ...(missingBlockHint ? { missingBlockHint: true } : {}) } } });
13811
13621
  }
13812
13622
  }
13813
- return void reply({ t: "status", status: current });
13623
+ return void reply({ t: "status", status: { ...current, ...thisLaunch } });
13814
13624
  };
13815
13625
  if (orphanChecks && !startupSpecPending()) return sendStatus();
13816
13626
  void Promise.all([orphanSweep, firstSpecProbe]).then(() => {
@@ -14147,7 +13957,8 @@ export async function startDaemon(opts: DaemonOptions) {
14147
13957
  if (c.closed || sock.readyState !== WebSocket.OPEN || c.invocationRequests.size >= 64) return void reply({ t: "task", ok: false, error: "invocation request connection unavailable" });
14148
13958
  invocation = new AbortController(); c.invocationRequests.set(msg.rid, invocation);
14149
13959
  }
14150
- const run = async () => c.externalOwner ? childToolAuthority.run({ by: c.peer!, current: () => currentExternalTools(c, true) }, () => taskOp(c.peer!, String(msg.op), msg.args ?? {})) : c.toolsOwner ? childToolAuthority.run({ by: c.peer!, current: captureImplementerTools(c) }, () => taskOp(c.peer!, String(msg.op), msg.args ?? {})) : taskOp(c.peer ?? USER, String(msg.op), msg.args ?? {});
13960
+ const dispatch = () => taskOp(c.peer ?? USER, String(msg.op), msg.args ?? {}, false, false, sock);
13961
+ const run = async () => c.externalOwner ? childToolAuthority.run({ by: c.peer!, current: () => currentExternalTools(c, true) }, dispatch) : c.toolsOwner ? childToolAuthority.run({ by: c.peer!, current: captureImplementerTools(c) }, dispatch) : dispatch();
14151
13962
  const execute = () => (invocation ? invocationRequestSignal.run({ signal: invocation.signal, current: () => {
14152
13963
  const live = !c.closed && sock.readyState === WebSocket.OPEN && c.invocationRequests?.get(msg.rid) === invocation;
14153
13964
  if (!live) invocation?.abort();
@@ -14237,6 +14048,66 @@ export async function startDaemon(opts: DaemonOptions) {
14237
14048
  .catch((e: Error) => reply({ t: "ask", ok: false, error: e.message }));
14238
14049
  return;
14239
14050
  }
14051
+ case "budget_renew": {
14052
+ // Authenticate the person before reading even the shape of the optional home field.
14053
+ if (c.role !== "console" || c.instructed) {
14054
+ return void reply({ t: "budget_renew", ok: false, error: "only the person may renew quota; run ahub budget renew in a person terminal" });
14055
+ }
14056
+ const peer = typeof msg.peer === "string" && PEER_ID.test(msg.peer) ? msg.peer : undefined;
14057
+ const mode = msg.mode;
14058
+ if (!peer || (mode !== "reset" && mode !== "switched")) {
14059
+ return void reply({ t: "budget_renew", ok: false, error: "renew requires a peer and exactly one mode; run ahub budget renew <peer> --reset or --switched" });
14060
+ }
14061
+ const def = definitionOf(peer);
14062
+ if (!def) return void reply({ t: "budget_renew", ok: false, error: "unknown peer; choose a peer shown by ahub budget" });
14063
+ if (!def.budget || def.budget.quotaExempt) return void reply({ t: "budget_renew", ok: false, error: "this peer has no renewable quota; inspect ahub budget" });
14064
+ const account = accountOf(peer);
14065
+ const accountBase = def.budget.account;
14066
+ const compareHomes = mode === "switched" && definitionOf(accountBase)?.start.daemonPort === "codex-appserver";
14067
+ const quotaRuntime = (id: string) => isFixedBuiltinDefinition(definitionOf(id)) ? bus.peers.get(id) : undefined;
14068
+ const compare = () => {
14069
+ if (!compareHomes) return [];
14070
+ const caller = typeof msg.callerHome === "string" ? msg.callerHome : undefined;
14071
+ return accountMembers(account).map(id => {
14072
+ try {
14073
+ const result = quotaRuntime(id)?.compareQuotaHome?.(caller) ?? compareNextCodexQuotaHome(id, caller);
14074
+ return { peer: id, result };
14075
+ } catch {
14076
+ return { peer: id, result: "unknown" as const };
14077
+ }
14078
+ });
14079
+ };
14080
+ const refused = (matches: ReturnType<typeof compare>) => {
14081
+ const mismatches = matches.filter(match => match.result !== "same");
14082
+ if (!mismatches.length) return false;
14083
+ reply({ t: "budget_renew", ok: false, homes: mismatches, error: "Codex home differs or could not be verified; quota was not renewed" });
14084
+ return true;
14085
+ };
14086
+ if (recoveryActive() || stopping) return void reply({ t: "budget_renew", ok: false, error: "quota was not renewed during recovery or shutdown; retry when the hub is ready" });
14087
+ if (refused(compare())) return;
14088
+ const changed = new Error("renewal home comparison changed");
14089
+ void budget.renew(peer, mode, () => {
14090
+ if (refused(compare())) throw changed;
14091
+ }).then(result => {
14092
+ const members = accountMembers(account);
14093
+ if (definitionOf(accountBase)?.start.daemonPort === "codex-appserver") {
14094
+ for (const id of members) {
14095
+ try { quotaRuntime(id)?.readQuotaNow?.(); }
14096
+ catch { /* The renewal is already saved. A failed read must not replace its reply. */ }
14097
+ }
14098
+ }
14099
+ reply({ t: "budget_renew", ok: true, ...result, ...(compareHomes ? { homeComparison: "same" } : {}),
14100
+ ...(compareHomes ? { pending: members.filter(id => definitionOf(id)?.start.daemonPort === "codex-appserver") } : {}),
14101
+ ...(mode === "switched" && definitionOf(accountBase)?.transport === "claude-channel" ? {
14102
+ softQuota: "Claude quota stays unknown after switching. Its soft gate is off. A hard refusal still pauses Claude, and you can supply a value with ahub budget set.",
14103
+ } : {}) });
14104
+ }, error => {
14105
+ if (error === changed) return;
14106
+ const stalled = error instanceof Error && error.message.startsWith("budget renewal was not saved;");
14107
+ reply({ t: "budget_renew", ok: false, error: stalled ? error.message : "quota renewal did not finish; inspect ahub budget and retry when the hub is ready" });
14108
+ });
14109
+ return;
14110
+ }
14240
14111
  case "budget":
14241
14112
  if (c.role !== "console") {
14242
14113
  if (msg.resume !== undefined || msg.set !== undefined) return void reply({ t: "budget", ok: false, error: "budget mutations are console commands" });
@@ -14246,8 +14117,9 @@ export async function startDaemon(opts: DaemonOptions) {
14246
14117
  if (msg.resume) {
14247
14118
  if (!budget.override(String(msg.resume))) return void reply({ t: "budget", ok: false, error: `${msg.resume} is not paused by the budget coordinator` });
14248
14119
  } else if (msg.set) {
14120
+ if (c.instructed) return void reply({ t: "budget", ok: false, error: "only the person may set quota; use ahub budget in a person terminal" });
14249
14121
  const used = Number(msg.set.used);
14250
- if (!bus.peers.has(String(msg.set.peer)) && !budget.record(String(msg.set.peer))) return void reply({ t: "budget", ok: false, error: `unknown peer: ${msg.set.peer}` });
14122
+ if (!bus.peers.has(String(msg.set.peer)) && !budget.record(String(msg.set.peer)) && budget.renewalAt(String(msg.set.peer)) === undefined) return void reply({ t: "budget", ok: false, error: `unknown peer: ${msg.set.peer}` });
14251
14123
  if (!(used >= 0 && used <= 1)) return void reply({ t: "budget", ok: false, error: "used must be between 0 and 1" });
14252
14124
  budget.report(String(msg.set.peer), [{ id: msg.set.window === "week" ? "week" : "5h", kind: "manual", used, ...(msg.set.resetsInMs ? { resetsAt: Date.now() + Number(msg.set.resetsInMs) } : {}), source: "ahub budget set" }]);
14253
14125
  }
@@ -14488,6 +14360,7 @@ export async function startDaemon(opts: DaemonOptions) {
14488
14360
  board.close();
14489
14361
  turnLog?.close();
14490
14362
  server.stop(true);
14363
+ try { await mcpEndpoint?.stop(); } catch { /* the socket is gone with the directory */ }
14491
14364
  try { bus.closeJournal(); } catch { /* the state dir is gone; the journal went with it */ }
14492
14365
  } finally {
14493
14366
  // State removal and the stopped notification run no matter what failed above,
@@ -14514,9 +14387,59 @@ export async function startDaemon(opts: DaemonOptions) {
14514
14387
  orphanWatch.unref?.();
14515
14388
  intervals.push(orphanWatch);
14516
14389
 
14390
+ /**
14391
+ * #1780 T2a-2c: one endpoint session, admitted by the control path itself. The link is a Sock-shaped object over the endpoint's connection: the hello goes through `onControlMessage` as a bridge's would, so peer admission,
14392
+ * launch proof, account label (#1810) and attachment are the control code, not a copy of it. A session is pull-only for now (`channel: false`): pushes and receipts are the next task. Nothing here logs the hello's home.
14393
+ */
14394
+ /** Failed pushes of a peer that had no delivery id, kept per peer id so a reconnect finds them (the bridge's buffer, up to 200 each, now in the hub). Cleared with the daemon. */
14395
+ const mcpPushBuffers = new PushBuffers(), mcpListedTools = new ListedTools();
14396
+ async function openMcpSession(session: { peer: string; mode: "channel" | "tools" }, hello: McpHello, write: (line: string) => boolean, closeEndpoint: () => void): Promise<McpSessionServer | undefined> {
14397
+ const tools = hello.mode === "tools" || hello.session !== undefined;
14398
+ const evidence = hello.mode === "tools" ? "unknown" : opts.mcpChannelEvidence?.(hello) ?? "unknown";
14399
+ const channel = hello.mode !== "tools" && hello.session === undefined && evidence === "development-channel-launch";
14400
+ // The endpoint ends a refused connection itself, after the refusal line is written: closing it first would drop that line.
14401
+ let open = true, established = false, sock!: Sock;
14402
+ const refuse = (reason: string) => { write(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32000, message: `the hub refused this session: ${sanitize(reason)}` } })); };
14403
+ let cwd: string | undefined;
14404
+ if (hello.mode !== "tools") { try { cwd = realPath(hello.cwd); } catch { /* an unresolvable cwd withholds root evidence only, as in the bridge */ } }
14405
+ let client;
14406
+ try {
14407
+ client = await ControlClient.inProcess((receive, closed) => {
14408
+ sock = {
14409
+ data: { authed: false } as Client,
14410
+ get readyState() { return open ? WebSocket.OPEN : WebSocket.CLOSED; },
14411
+ send: (text: string) => { let msg: unknown; try { msg = JSON.parse(text); } catch { return; } queueMicrotask(() => receive(msg)); },
14412
+ close: (code?: number, reason?: string) => { if (!open) return; open = false; try { controlWebsocket.close!(sock, code ?? 1000, reason ?? ""); } finally { if (established) closeEndpoint(); closed(code ?? 1000, reason ?? ""); } },
14413
+ getBufferedAmount: () => 0,
14414
+ } as unknown as Sock;
14415
+ // Every client message takes the WebSocket handler's own path, errors included.
14416
+ return { get readyState() { return open ? WebSocket.OPEN : WebSocket.CLOSED; }, send: (text: string) => controlWebsocket.message!(sock, text), close: () => sock.close(1000, "") } as never;
14417
+ }, {
14418
+ token, role: tools ? "tools" : "peer", peer: hello.peer, v: acceptedBridgeWindow.v, vMin: acceptedBridgeWindow.vMin, projectId, instanceId, projectRoot: hello.projectRoot ?? opts.cwd, clientVersion: VERSION, clientPid: hello.pid,
14419
+ ...(tools ? {} : { channel, channelEvidence: evidence, retainStandby: false, ...(hello.home !== undefined ? { home: hello.home } : {}) }),
14420
+ ...(hello.session !== undefined ? { session: hello.session } : {}),
14421
+ ...(hello.claudeSessionId !== undefined ? { claudeSessionId: hello.claudeSessionId } : {}),
14422
+ ...(hello.launchId !== undefined ? { launchId: hello.launchId } : {}),
14423
+ ...(cwd !== undefined ? { cwd } : {}),
14424
+ });
14425
+ } catch (error) { refuse((error as Error).message.replace(/^hub closed the connection: /, "")); return undefined; }
14426
+ established = true;
14427
+ const surface = () => ({ peerId: hello.peer, toolsMode: hello.mode === "tools", channel, permissionTool: hello.mode === "tools" && hello.permissionTool === true, deliveryOnly: hello.deliveryOnly === true,
14428
+ roles: config.roles, sessionRoles: hello.mode === "tools" ? [] : selectedRoles(hello.peer, config.roles, roleAssignments, catalog), profile: resolvedProfile });
14429
+ const buffer = mcpPushBuffers.forSession(hello.peer, hello.session !== undefined);
14430
+ return serveMcpSession({ client, channel, buffer, listed: mcpListedTools.forSession(hello.peer, hello.session !== undefined), log, mode: session.mode, peer: hello.peer, permissionTool: hello.permissionTool === true && hello.mode === "tools", deliveryOnly: hello.deliveryOnly === true, sessionJoin: hello.session !== undefined, surface, write, close: closeEndpoint });
14431
+ }
14432
+
14517
14433
  const tokenFile = join(opts.stateDir, "control-token");
14518
14434
  writeFileSync(tokenFile, token, { mode: 0o600 });
14519
14435
  chmodSync(tokenFile, 0o600);
14436
+ // #1780 T1: the per-project MCP socket. A refusal (a group-accessible directory, a stale or live socket, a path too long) is logged with its fix and the hub runs without the endpoint.
14437
+ if (opts.mcpHome) {
14438
+ const started = await startMcpEndpoint({ home: opts.mcpHome, projectId, token, log, exclusiveOwner: opts.controlPort !== 0,
14439
+ ...(opts.mcpServe ? { serve: openMcpSession } : {}),
14440
+ accountLabel: (home, peer) => { const label = labelForHome(home, definitionOf(peer)?.budget?.account ?? declarations[peer]?.kind ?? peer, config.accounts); return label === DEFAULT_ACCOUNT_LABEL ? undefined : label; } });
14441
+ if (started.ok) mcpEndpoint = started.endpoint; else log(`mcp endpoint unavailable: ${started.refusal}`);
14442
+ }
14520
14443
  budget.restore(); // pauses recorded by an earlier hub run stay in force; unfinished handoffs wait for peers to attach
14521
14444
  bus.onQueues(); // initial restored holds are reported only after the listener is bound; writes status.json too
14522
14445
  log(`${RUN_START}${process.pid} control=127.0.0.1:${server.port} cwd=${opts.cwd}`);