@open-mercato/cezar 0.9.1 → 0.9.2-pr778.1064

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 (355) hide show
  1. package/README.md +29 -11
  2. package/dist/agent-config/account-identity.d.ts +44 -0
  3. package/dist/agent-config/account-identity.js +128 -0
  4. package/dist/agent-config/account-identity.js.map +1 -0
  5. package/dist/agent-config/catalog.d.ts +9 -1
  6. package/dist/agent-config/catalog.js +18 -0
  7. package/dist/agent-config/catalog.js.map +1 -1
  8. package/dist/agent-config/files.d.ts +1 -1
  9. package/dist/agent-config/model-settings/claude.d.ts +2 -0
  10. package/dist/agent-config/model-settings/claude.js +11 -0
  11. package/dist/agent-config/model-settings/claude.js.map +1 -0
  12. package/dist/agent-config/model-settings/codex.d.ts +2 -0
  13. package/dist/agent-config/model-settings/codex.js +16 -0
  14. package/dist/agent-config/model-settings/codex.js.map +1 -0
  15. package/dist/agent-config/model-settings/opencode.d.ts +2 -0
  16. package/dist/agent-config/model-settings/opencode.js +8 -0
  17. package/dist/agent-config/model-settings/opencode.js.map +1 -0
  18. package/dist/agent-config/model-settings/shared.d.ts +9 -0
  19. package/dist/agent-config/model-settings/shared.js +93 -0
  20. package/dist/agent-config/model-settings/shared.js.map +1 -0
  21. package/dist/agent-config/model-settings/types.d.ts +9 -0
  22. package/dist/agent-config/model-settings/types.js +2 -0
  23. package/dist/agent-config/model-settings/types.js.map +1 -0
  24. package/dist/agent-config/models.d.ts +9 -0
  25. package/dist/agent-config/models.js +30 -0
  26. package/dist/agent-config/models.js.map +1 -0
  27. package/dist/agent-config/service.d.ts +1 -1
  28. package/dist/agent-config/service.js +4 -4
  29. package/dist/agent-config/service.js.map +1 -1
  30. package/dist/agent-config/validate.d.ts +1 -1
  31. package/dist/automations/coordinator.d.ts +26 -0
  32. package/dist/automations/coordinator.js +66 -0
  33. package/dist/automations/coordinator.js.map +1 -0
  34. package/dist/automations/github-poller.d.ts +74 -0
  35. package/dist/automations/github-poller.js +234 -0
  36. package/dist/automations/github-poller.js.map +1 -0
  37. package/dist/automations/scheduler.d.ts +42 -0
  38. package/dist/automations/scheduler.js +192 -0
  39. package/dist/automations/scheduler.js.map +1 -0
  40. package/dist/automations/store.d.ts +65 -0
  41. package/dist/automations/store.js +298 -0
  42. package/dist/automations/store.js.map +1 -0
  43. package/dist/automations/task-template.d.ts +18 -0
  44. package/dist/automations/task-template.js +95 -0
  45. package/dist/automations/task-template.js.map +1 -0
  46. package/dist/automations/types.d.ts +251 -0
  47. package/dist/automations/types.js +158 -0
  48. package/dist/automations/types.js.map +1 -0
  49. package/dist/config.d.ts +17 -112
  50. package/dist/config.js +45 -4
  51. package/dist/config.js.map +1 -1
  52. package/dist/contract/agent-config.d.ts +151 -0
  53. package/dist/contract/agent-profiles.d.ts +332 -0
  54. package/dist/contract/automations.d.ts +919 -0
  55. package/dist/contract/events.d.ts +45 -0
  56. package/dist/contract/github.d.ts +467 -0
  57. package/dist/contract/health.d.ts +96 -0
  58. package/dist/contract/index.d.ts +16 -0
  59. package/dist/contract/index.js +1604 -0
  60. package/dist/contract/projects.d.ts +185 -0
  61. package/dist/contract/repo.d.ts +234 -0
  62. package/dist/contract/runs.d.ts +1261 -0
  63. package/dist/contract/skills.d.ts +229 -0
  64. package/dist/contract/workflows.d.ts +212 -0
  65. package/dist/contract/workspace.d.ts +472 -0
  66. package/dist/core/agent-env.d.ts +1 -1
  67. package/dist/core/agent-model-policy.d.ts +10 -0
  68. package/dist/core/agent-model-policy.js +36 -0
  69. package/dist/core/agent-model-policy.js.map +1 -0
  70. package/dist/core/agent-profiles.d.ts +59 -0
  71. package/dist/core/agent-profiles.js +83 -0
  72. package/dist/core/agent-profiles.js.map +1 -0
  73. package/dist/core/agent-runner.d.ts +12 -1
  74. package/dist/core/agent-runner.js +13 -0
  75. package/dist/core/agent-runner.js.map +1 -1
  76. package/dist/core/ask.d.ts +45 -124
  77. package/dist/core/ask.js +103 -13
  78. package/dist/core/ask.js.map +1 -1
  79. package/dist/core/backend-detect.js +7 -2
  80. package/dist/core/backend-detect.js.map +1 -1
  81. package/dist/core/claude-cli-runner.d.ts +2 -2
  82. package/dist/core/claude-cli-runner.js +52 -9
  83. package/dist/core/claude-cli-runner.js.map +1 -1
  84. package/dist/core/claude-ui-mapper.d.ts +1 -1
  85. package/dist/core/codex-app-server-runner.d.ts +1 -1
  86. package/dist/core/codex-app-server-runner.js +60 -3
  87. package/dist/core/codex-app-server-runner.js.map +1 -1
  88. package/dist/core/codex-app-server-transport.d.ts +6 -1
  89. package/dist/core/codex-app-server-transport.js +12 -3
  90. package/dist/core/codex-app-server-transport.js.map +1 -1
  91. package/dist/core/codex-model-catalog.d.ts +1 -1
  92. package/dist/core/codex-ui-mapper.d.ts +5 -1
  93. package/dist/core/codex-ui-mapper.js +74 -17
  94. package/dist/core/codex-ui-mapper.js.map +1 -1
  95. package/dist/core/model-identity.d.ts +13 -6
  96. package/dist/core/model-identity.js +32 -17
  97. package/dist/core/model-identity.js.map +1 -1
  98. package/dist/core/model-presets.d.ts +2 -2
  99. package/dist/core/model-presets.js +1 -1
  100. package/dist/core/opencode-server-runner.d.ts +2 -2
  101. package/dist/core/opencode-ui-mapper.d.ts +4 -1
  102. package/dist/core/opencode-ui-mapper.js +45 -7
  103. package/dist/core/opencode-ui-mapper.js.map +1 -1
  104. package/dist/core/provider-auth.d.ts +154 -0
  105. package/dist/core/provider-auth.js +488 -0
  106. package/dist/core/provider-auth.js.map +1 -0
  107. package/dist/core/provider-availability.d.ts +3 -0
  108. package/dist/core/provider-availability.js +14 -0
  109. package/dist/core/provider-availability.js.map +1 -0
  110. package/dist/core/runner-factory.d.ts +1 -1
  111. package/dist/core/runner-model-catalog.d.ts +1 -1
  112. package/dist/core/shell-env.d.ts +28 -0
  113. package/dist/core/shell-env.js +56 -0
  114. package/dist/core/shell-env.js.map +1 -0
  115. package/dist/core/tool-display.d.ts +1 -1
  116. package/dist/core/ui-events.d.ts +1 -1
  117. package/dist/core/ui-events.js +1 -1
  118. package/dist/core/usage-limit.d.ts +42 -0
  119. package/dist/core/usage-limit.js +209 -0
  120. package/dist/core/usage-limit.js.map +1 -0
  121. package/dist/git-diff-base.d.ts +60 -0
  122. package/dist/git-diff-base.js +54 -0
  123. package/dist/git-diff-base.js.map +1 -0
  124. package/dist/git-worktree.d.ts +37 -6
  125. package/dist/git-worktree.js +39 -9
  126. package/dist/git-worktree.js.map +1 -1
  127. package/dist/handoff.d.ts +2 -2
  128. package/dist/handoff.js +1 -1
  129. package/dist/index.js +65 -8
  130. package/dist/index.js.map +1 -1
  131. package/dist/paths.d.ts +69 -6
  132. package/dist/paths.js +86 -9
  133. package/dist/paths.js.map +1 -1
  134. package/dist/planner.d.ts +2 -2
  135. package/dist/planner.js +7 -1
  136. package/dist/planner.js.map +1 -1
  137. package/dist/release/manifests.d.ts +81 -0
  138. package/dist/release/manifests.js +74 -0
  139. package/dist/release/manifests.js.map +1 -0
  140. package/dist/release/snapshot.d.ts +9 -23
  141. package/dist/release/snapshot.js +9 -22
  142. package/dist/release/snapshot.js.map +1 -1
  143. package/dist/release/stable.d.ts +15 -29
  144. package/dist/release/stable.js +14 -27
  145. package/dist/release/stable.js.map +1 -1
  146. package/dist/runs/auto-name.d.ts +1 -1
  147. package/dist/runs/auto-name.js +6 -1
  148. package/dist/runs/auto-name.js.map +1 -1
  149. package/dist/runs/retention.d.ts +1 -1
  150. package/dist/runs/store.d.ts +149 -336
  151. package/dist/runs/store.js +187 -9
  152. package/dist/runs/store.js.map +1 -1
  153. package/dist/runs/ui-event-sink.d.ts +1 -1
  154. package/dist/server/app-type.d.ts +21 -0
  155. package/dist/server/app-type.js +2 -0
  156. package/dist/server/app-type.js.map +1 -0
  157. package/dist/server/capabilities.d.ts +6 -5
  158. package/dist/server/capabilities.js +11 -0
  159. package/dist/server/capabilities.js.map +1 -1
  160. package/dist/server/forge/github.d.ts +58 -151
  161. package/dist/server/forge/github.js +530 -6
  162. package/dist/server/forge/github.js.map +1 -1
  163. package/dist/server/forge/index.d.ts +10 -3
  164. package/dist/server/forge/index.js +14 -1
  165. package/dist/server/forge/index.js.map +1 -1
  166. package/dist/server/forge/types.d.ts +86 -1
  167. package/dist/server/git-changes.d.ts +8 -8
  168. package/dist/server/git-changes.js +14 -17
  169. package/dist/server/git-changes.js.map +1 -1
  170. package/dist/server/git.d.ts +2 -0
  171. package/dist/server/git.js +9 -0
  172. package/dist/server/git.js.map +1 -1
  173. package/dist/server/github.d.ts +3 -3
  174. package/dist/server/github.js +1 -1
  175. package/dist/server/github.js.map +1 -1
  176. package/dist/server/open-in-terminal.d.ts +8 -1
  177. package/dist/server/open-in-terminal.js +16 -8
  178. package/dist/server/open-in-terminal.js.map +1 -1
  179. package/dist/server/pr.d.ts +2 -2
  180. package/dist/server/project-context.d.ts +20 -3
  181. package/dist/server/project-context.js +30 -1
  182. package/dist/server/project-context.js.map +1 -1
  183. package/dist/server/provider-action-gate.d.ts +8 -0
  184. package/dist/server/provider-action-gate.js +54 -0
  185. package/dist/server/provider-action-gate.js.map +1 -0
  186. package/dist/server/provider-auth-runtime.d.ts +21 -0
  187. package/dist/server/provider-auth-runtime.js +66 -0
  188. package/dist/server/provider-auth-runtime.js.map +1 -0
  189. package/dist/server/server.d.ts +12052 -47
  190. package/dist/server/server.js +2626 -918
  191. package/dist/server/server.js.map +1 -1
  192. package/dist/server/validators.d.ts +97 -0
  193. package/dist/server/validators.js +86 -0
  194. package/dist/server/validators.js.map +1 -0
  195. package/dist/server/ws.d.ts +2 -2
  196. package/dist/server/ws.js +2 -2
  197. package/dist/server/ws.js.map +1 -1
  198. package/dist/server-install/engine.d.ts +1 -1
  199. package/dist/server-install/platforms/macosx-ngrok.d.ts +1 -1
  200. package/dist/server-install/platforms/ubuntu-vps.d.ts +16 -1
  201. package/dist/server-install/platforms/ubuntu-vps.js +83 -1
  202. package/dist/server-install/platforms/ubuntu-vps.js.map +1 -1
  203. package/dist/server-install/state.d.ts +1 -1
  204. package/dist/server-install/steps.d.ts +2 -2
  205. package/dist/server-install/strategies.d.ts +1 -1
  206. package/dist/server-install/types.d.ts +38 -424
  207. package/dist/server-install/ui.d.ts +1 -1
  208. package/dist/skills-banner.d.ts +7 -6
  209. package/dist/skills-banner.js +7 -6
  210. package/dist/skills-banner.js.map +1 -1
  211. package/dist/skills-remote.d.ts +2 -2
  212. package/dist/skills-update.d.ts +88 -0
  213. package/dist/skills-update.js +392 -0
  214. package/dist/skills-update.js.map +1 -0
  215. package/dist/skills.d.ts +2 -0
  216. package/dist/skills.js +7 -2
  217. package/dist/skills.js.map +1 -1
  218. package/dist/todos.d.ts +2 -28
  219. package/dist/todos.js +1 -1
  220. package/dist/ui-state.d.ts +16 -2
  221. package/dist/ui-state.js +14 -1
  222. package/dist/ui-state.js.map +1 -1
  223. package/dist/workflows/load.d.ts +1 -1
  224. package/dist/workflows/run.d.ts +238 -12
  225. package/dist/workflows/run.js +1103 -115
  226. package/dist/workflows/run.js.map +1 -1
  227. package/dist/workflows/types.d.ts +59 -224
  228. package/dist/workflows/types.js +14 -0
  229. package/dist/workflows/types.js.map +1 -1
  230. package/dist/workspace/agent-accounts.d.ts +149 -0
  231. package/dist/workspace/agent-accounts.js +303 -0
  232. package/dist/workspace/agent-accounts.js.map +1 -0
  233. package/dist/workspace/agent-profiles.d.ts +78 -0
  234. package/dist/workspace/agent-profiles.js +115 -0
  235. package/dist/workspace/agent-profiles.js.map +1 -0
  236. package/dist/workspace/config.d.ts +82 -206
  237. package/dist/workspace/config.js +183 -14
  238. package/dist/workspace/config.js.map +1 -1
  239. package/dist/workspace/migrations.d.ts +1 -1
  240. package/dist/workspace/migrations.js +19 -4
  241. package/dist/workspace/migrations.js.map +1 -1
  242. package/dist/workspace/projects.d.ts +8 -2
  243. package/dist/workspace/projects.js +9 -3
  244. package/dist/workspace/projects.js.map +1 -1
  245. package/dist/workspace/semaphore.d.ts +45 -0
  246. package/dist/workspace/semaphore.js +45 -1
  247. package/dist/workspace/semaphore.js.map +1 -1
  248. package/dist/workspace/ui-state.d.ts +13 -3
  249. package/dist/workspace/ui-state.js +15 -5
  250. package/dist/workspace/ui-state.js.map +1 -1
  251. package/package.json +17 -39
  252. package/scripts/inline-contract.mjs +112 -0
  253. package/scripts/mock-claude.mjs +59 -1
  254. package/scripts/sync-readme.mjs +20 -0
  255. package/web/dist/assets/alert-dialog-DDkrFSNo.js +1 -0
  256. package/web/dist/assets/arrow-down-6yITIPsm.js +1 -0
  257. package/web/dist/assets/arrow-left-ClFtONFn.js +1 -0
  258. package/web/dist/assets/bundle-mjs-BT31bpU6.js +1 -0
  259. package/web/dist/assets/centered-state-B6eNyY9K.js +43 -0
  260. package/web/dist/assets/chevron-right-DU1ld4lK.js +1 -0
  261. package/web/dist/assets/{chunk-BO2N2NFS-DtrdTCWa.js → chunk-BO2N2NFS-DE6qKn3r.js} +8 -8
  262. package/web/dist/assets/circle-check-CrpGUTuT.js +1 -0
  263. package/web/dist/assets/circle-x-BswQ4rx0.js +1 -0
  264. package/web/dist/assets/collapsible-Cv8ki6G4.js +1 -0
  265. package/web/dist/assets/commit-list-Bwor0g70.js +1 -0
  266. package/web/dist/assets/compare-variants-BA3qQSVU.js +1 -0
  267. package/web/dist/assets/{core-DePtBHcl.js → core-BCsw8oQw.js} +1 -1
  268. package/web/dist/assets/diff-CV5qDJ7S.js +3 -0
  269. package/web/dist/assets/diff-stat-C96SW0xK.js +1 -0
  270. package/web/dist/assets/{diff-view-DCeSegKk.js → diff-view-9Qw79-f1.js} +4 -4
  271. package/web/dist/assets/dropdown-menu-Bnk-hg8y.js +1 -0
  272. package/web/dist/assets/editable-title-veprAEpy.js +1 -0
  273. package/web/dist/assets/{ellipsis-vertical-CNnSLn5a.js → ellipsis-vertical-C8LP-M9x.js} +1 -1
  274. package/web/dist/assets/{file-D4GBh1ao.js → file-DnCwXidV.js} +1 -1
  275. package/web/dist/assets/folder-BBBuunLT.js +1 -0
  276. package/web/dist/assets/{git-pull-request-DnR8Xh4_.js → git-pull-request-BuHs3KJ6.js} +1 -1
  277. package/web/dist/assets/git-toolbar-CPt4JoOj.js +1 -0
  278. package/web/dist/assets/github-Cz2tagoB.js +1 -0
  279. package/web/dist/assets/highlighted-body-OFNGDK62-BL-MfFgl.js +1 -0
  280. package/web/dist/assets/highlighter-CdHqIwFr.js +3 -0
  281. package/web/dist/assets/image-preview-B-UiFJKd.js +1 -0
  282. package/web/dist/assets/index-B84F80Q8.css +2 -0
  283. package/web/dist/assets/index-CkXaC99i.js +6 -0
  284. package/web/dist/assets/lib-BQXq3kEf.js +1 -0
  285. package/web/dist/assets/lib-BxQXEXDF.js +1 -0
  286. package/web/dist/assets/markdown-B0APBJCK.js +2 -0
  287. package/web/dist/assets/mermaid-GHXKKRXX-C4jxqUUb.js +1 -0
  288. package/web/dist/assets/new-task-form-BjNLkW4w.js +1 -0
  289. package/web/dist/assets/pill-DF3ZRiuk.js +1 -0
  290. package/web/dist/assets/project-router-DMinES4q.js +1 -0
  291. package/web/dist/assets/prompt-templates-CKnyW-ae.js +15 -0
  292. package/web/dist/assets/react-runtime-CCIEwYL0.js +9 -0
  293. package/web/dist/assets/{refresh-cw-BT8E96Tm.js → refresh-cw-BTiJYD2N.js} +1 -1
  294. package/web/dist/assets/repo-git-BovGLcYW.js +1 -0
  295. package/web/dist/assets/rolldown-runtime-QTnfLwEv.js +1 -0
  296. package/web/dist/assets/run-diff-BVWjG5af.js +3 -0
  297. package/web/dist/assets/run-header-CEr8j77z.js +1 -0
  298. package/web/dist/assets/{search-x-BDjaMrzG.js → search-x--hctwQW4.js} +1 -1
  299. package/web/dist/assets/skill-empty-hint-DXlK1qF5.js +1 -0
  300. package/web/dist/assets/skills-BiWfHmCR.js +1 -0
  301. package/web/dist/assets/skills-DpxiSJPs.js +1 -0
  302. package/web/dist/assets/sparkles-BSB94GWf.js +1 -0
  303. package/web/dist/assets/{square-terminal-Ckjjn0vb.js → square-terminal-DI9vN2oU.js} +1 -1
  304. package/web/dist/assets/tab-link-xE17QWo3.js +1 -0
  305. package/web/dist/assets/task-changes-DzQ0clq-.js +1 -0
  306. package/web/dist/assets/task-commits-BRvrT2AH.js +1 -0
  307. package/web/dist/assets/task-files-Bw84_sPi.js +2 -0
  308. package/web/dist/assets/task-thread-BT4gX0y6.js +9 -0
  309. package/web/dist/assets/textarea-CxwpSdn4.js +1 -0
  310. package/web/dist/assets/thread-loading-lFlqLRN5.js +1 -0
  311. package/web/dist/assets/{trash-2-DAyZ0VSi.js → trash-2-COvilYIt.js} +1 -1
  312. package/web/dist/assets/{triangle-alert-Uy8rokUh.js → triangle-alert-BVqzlcpl.js} +1 -1
  313. package/web/dist/assets/{upload-CDdyPPo_.js → upload-Ctrt-DXu.js} +1 -1
  314. package/web/dist/assets/use-desktop-BzoSqrBi.js +1 -0
  315. package/web/dist/assets/use-submit-shortcut-C-M46aas.js +1 -0
  316. package/web/dist/assets/utils-Dfe0KwV2.js +64 -0
  317. package/web/dist/assets/workflows-B1wIdn-o.js +11 -0
  318. package/web/dist/assets/zoomable-image-D0J9qb-_.js +1 -0
  319. package/web/dist/index.html +33 -13
  320. package/scripts/dev.mjs +0 -74
  321. package/scripts/release-snapshot.mjs +0 -130
  322. package/scripts/release.mjs +0 -119
  323. package/web/dist/assets/arrow-left-CnSdp92h.js +0 -1
  324. package/web/dist/assets/bundle-mjs-BegPhL5c.js +0 -1
  325. package/web/dist/assets/centered-state-DOsTcJZF.js +0 -43
  326. package/web/dist/assets/commit-list-BrxBEzRK.js +0 -1
  327. package/web/dist/assets/compare-variants-Bv2c9ORF.js +0 -1
  328. package/web/dist/assets/dist-B6XQOhgM.js +0 -1
  329. package/web/dist/assets/git-toolbar-pIC1ubPM.js +0 -1
  330. package/web/dist/assets/github-DTTSG0ht.js +0 -1
  331. package/web/dist/assets/highlighted-body-OFNGDK62-BuFJwunK.js +0 -1
  332. package/web/dist/assets/image-preview-DEhW0TFz.js +0 -1
  333. package/web/dist/assets/index-Cijmlz7q.js +0 -30
  334. package/web/dist/assets/index-DzroxqBG.css +0 -2
  335. package/web/dist/assets/lib-DPEZDBUN.js +0 -1
  336. package/web/dist/assets/lib-uHpeUPzK.js +0 -1
  337. package/web/dist/assets/mermaid-GHXKKRXX-CN2zQue0.js +0 -1
  338. package/web/dist/assets/open-mercato-toBr6SOa.svg +0 -11
  339. package/web/dist/assets/project-router-BMx4e8m-.js +0 -1
  340. package/web/dist/assets/repo-git-BusYfa3t.js +0 -1
  341. package/web/dist/assets/run-diff-wOJ3odA-.js +0 -3
  342. package/web/dist/assets/run-header-Cg5incil.js +0 -1
  343. package/web/dist/assets/skill-empty-hint-DTUSp6Vl.js +0 -1
  344. package/web/dist/assets/skills-PpP2owbM.js +0 -1
  345. package/web/dist/assets/tab-link-F3uQrdm2.js +0 -1
  346. package/web/dist/assets/task-changes-iD9kS79I.js +0 -1
  347. package/web/dist/assets/task-commits-COkLaUri.js +0 -1
  348. package/web/dist/assets/task-files-Ckttz7XH.js +0 -2
  349. package/web/dist/assets/task-thread-CQD91VPt.js +0 -9
  350. package/web/dist/assets/textarea-Bj_LCreg.js +0 -1
  351. package/web/dist/assets/use-desktop-DUh0STzq.js +0 -3
  352. package/web/dist/assets/utils-B8s5qIcK.js +0 -1
  353. package/web/dist/assets/workflows-BFk8C0co.js +0 -11
  354. package/web/dist/assets/zoomable-image-PEDOqyLQ.js +0 -1
  355. /package/web/{open-mercato.svg → dist/open-mercato.svg} +0 -0
@@ -1,4 +1,11 @@
1
1
  import { existsSync, readFileSync, statSync } from 'node:fs';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { AutomationStore } from '../automations/store.js';
4
+ import { AutomationCoordinator } from '../automations/coordinator.js';
5
+ import { GithubPoller } from '../automations/github-poller.js';
6
+ import { ProjectAutomationScheduler, WorkspaceAutomationScheduler } from '../automations/scheduler.js';
7
+ import { launchAutomationRun, reconcileAutomationReceipts, validateAutomationPrompt } from '../automations/task-template.js';
8
+ import { automationEventSchema, automationFiltersSchema, automationLogResultSchema, automationTaskSchema, } from '../automations/types.js';
2
9
  import { access, constants as fsConstants, mkdir, readFile, realpath, stat, unlink, writeFile } from 'node:fs/promises';
3
10
  import { basename, dirname, join, resolve, sep } from 'node:path';
4
11
  import { fileURLToPath } from 'node:url';
@@ -6,16 +13,21 @@ import { Hono } from 'hono';
6
13
  import { serve } from '@hono/node-server';
7
14
  import { bodyLimit } from 'hono/body-limit';
8
15
  import { streamSSE } from 'hono/streaming';
16
+ import { jsonZodValidator, paramZodValidator, queryZodValidator } from './validators.js';
9
17
  import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
10
18
  import { z } from 'zod';
11
19
  import { detectEnvironment } from '../core/backend-detect.js';
20
+ import { AGENT_MODELS_LOCKED_ERROR, agentModelsLocked } from '../core/agent-model-policy.js';
12
21
  import { discoverCodexModels } from '../core/codex-model-catalog.js';
22
+ import { PROVIDER_IDS, ProviderAuthService, providerAuthChecksDisabled, } from '../core/provider-auth.js';
23
+ import { applyProviderEnablement } from '../core/provider-availability.js';
13
24
  import { RunnerModelCatalog } from '../core/runner-model-catalog.js';
14
25
  import { currentUsage, onUsage } from '../core/process-usage.js';
15
26
  import { WORKFLOWS_DIR, loadWorkflows } from '../workflows/load.js';
16
27
  import { QUICK_TASK_WORKFLOW, normalizeWorkflowDoc, skillStackOf, skillsToSteps, stepsIssue, workflowFileSchema, workflowStepSchema, } from '../workflows/types.js';
17
28
  import { planChain, slugify } from '../planner.js';
18
29
  import { discoverSkills } from '../skills.js';
30
+ import { SkillsUpdateConflictError, SkillsUpdateCoordinator, SkillsUpdateService } from '../skills-update.js';
19
31
  import { getTeamSkillsCached, refreshTeamSkills, waitForTeamSkills } from '../skills-remote.js';
20
32
  import { appendHandoffHeartbeat, handoffProgressExcerpt, readHandoff } from '../handoff.js';
21
33
  import { markStarted, onTodosChanged, readTodos, removeTodo, todoTaskText } from '../todos.js';
@@ -26,47 +38,157 @@ import { getBranches, getCommit, getDiff, getLog, getRepoInfo, getStatus } from
26
38
  import { collectChanges, collectCommitChanges, collectRunCommits, commitAll, createOrSwitchBranch, imageMimeType, isOsOpenableImage, pushCurrentBranch, readWorktreePath, } from './git-changes.js';
27
39
  import { gatedSkillsRepos, loadConfig, resolveWorktreeRetention } from '../config.js';
28
40
  import { findConfigFile } from '../agent-config/catalog.js';
29
- import { readConfigFile, writeConfigFile } from '../agent-config/files.js';
41
+ import { readConfigFile, statConfigPath, writeConfigFile } from '../agent-config/files.js';
42
+ import { readAgentModelDefaults } from '../agent-config/models.js';
30
43
  import { listAgentConfig } from '../agent-config/service.js';
31
- import { PROJECT_ID_RE, defaultWorkspaceConfig, loadWorkspaceConfig, mergeWriteWorkspaceConfig, } from '../workspace/config.js';
44
+ import { listConfigFiles } from '../agent-config/catalog.js';
45
+ import { readAccountIdentity } from '../agent-config/account-identity.js';
46
+ import { PROJECT_ID_RE, defaultWorkspaceConfig, effectiveSkillsAutoUpdate, loadWorkspaceConfig, mergeWriteWorkspaceConfig, effectiveComposerDefault, } from '../workspace/config.js';
47
+ import { CONTROL_CHARS_RE, DEFAULT_AGENT_ACCOUNT_ID, defaultAgentAccountStore, isAbsoluteConfigDir, loadAgentAccounts, mergeWriteAgentAccounts, } from '../workspace/agent-accounts.js';
48
+ import { defaultAgentProfile, listAgentProfiles, profileDirState, resolveProfileEnvForRoot, resolveStoredProfile, sameProfileDir, } from '../workspace/agent-profiles.js';
49
+ import { PROFILE_CAPABLE_PROVIDERS, profileEnv, supportsProfiles } from '../core/agent-profiles.js';
50
+ import { withEnvPrefix } from '../core/shell-env.js';
32
51
  import { allocateProjectSlug, listProjects, probeProjectStatus, registerProject, removeProject, shouldRegisterProject, } from '../workspace/projects.js';
33
52
  import { mergeWriteWorkspaceUiState, readWorkspaceUiState } from '../workspace/ui-state.js';
34
53
  import { checkoutRepo } from './checkout.js';
35
54
  import { ProjectContextError, ProjectContexts } from './project-context.js';
36
55
  import { reviewGateEnabled } from '../runs/review-gate.js';
37
56
  import { readUiState, uiStatePath } from '../ui-state.js';
38
- import { expandTilde } from '../paths.js';
57
+ import { agentHomePaths, expandTilde } from '../paths.js';
39
58
  import { isLoopbackHostHeader, normalizeHostname, resolveCapabilities } from './capabilities.js';
40
59
  import { createSocketHub } from './ws.js';
41
60
  import { browseDirectory, isInsideBrowseRoot, isLexicallyInsideBrowseRoot, resolveBrowseRoot } from './fs-browse.js';
42
- import { resolveForge } from './forge/index.js';
43
- import { fetchGithub, fetchGithubComments } from './github.js';
61
+ import { parseRemote, resolveForge } from './forge/index.js';
62
+ import { fetchGithub, fetchGithubChecks, fetchGithubComments, fetchGithubPrDiff, GithubPrNotFoundError, GH_CHECKS_MAX } from './github.js';
44
63
  import { ensureLaunchKey } from './launch-key.js';
45
64
  import { openInTerminal } from './open-in-terminal.js';
46
65
  import { agentCliRunner, detectOpenTargets, openFileInDefaultApp, openInApp } from './open-in-app.js';
47
66
  import { createDraftPr } from './pr.js';
67
+ import { ProviderRuntimeAuthObserver } from './provider-auth-runtime.js';
68
+ import { providerForActiveRun, providerForExistingRun, providersRequiredByWorkflow, unavailableProviderMessage, } from './provider-action-gate.js';
48
69
  import { ASSET_CACHE_CONTROL, BUILD_HINT_HTML, assetContentType, isSafeAssetFilename, resolveGetRequest, } from './static-ui.js';
49
70
  /** `projectId` gate at the route boundary (spec "Project identity"): the slug
50
71
  * shape or the reserved `default` alias — validated BEFORE touching any map
51
72
  * or path. (`default` matches the slug regex too; the literal keeps the
52
73
  * contract explicit.) */
53
74
  const projectIdSchema = z.union([z.literal('default'), z.string().regex(PROJECT_ID_RE)]);
54
- const SCOPED_PREFIX = '/api/p/:projectId';
75
+ const providerConnectSchema = z.object({
76
+ provider: z.enum(PROVIDER_IDS),
77
+ /** Which agent account to sign in (spec 2026-07-29-agent-profiles). Absent = the discovered
78
+ * default, which is what every pre-profiles client sends. Without this, "Connect" on a second
79
+ * Claude account would open a login for the FIRST one and report success. */
80
+ profileId: z.string().max(64).optional(),
81
+ }).strict();
82
+ /** Agent-account bodies (spec 2026-07-29-agent-profiles). Bounds mirror `agentProfileSchema` in
83
+ * src/workspace/config.ts exactly, so a value these accept can never be degraded away by the
84
+ * next load's `.catch`. The id is allocated server-side and is never a request field. */
85
+ const createAgentProfileSchema = z.object({
86
+ provider: z.enum(PROVIDER_IDS),
87
+ label: z.string().trim().max(200).optional(),
88
+ configDir: z.string().trim().min(1).max(4096),
89
+ }).strict();
90
+ /** `POST …/agent-profiles/:id/open` — a catalog id (or `folder`) plus an optional open target. */
91
+ const openAgentAccountFileSchema = z.object({
92
+ file: z.string().min(1).max(200),
93
+ target: z.string().min(1).max(64).optional(),
94
+ }).strict();
95
+ const updateAgentProfileSchema = z.object({
96
+ label: z.string().trim().max(200).optional(),
97
+ configDir: z.string().trim().min(1).max(4096).optional(),
98
+ }).strict().refine((value) => value.label !== undefined || value.configDir !== undefined, 'send label or configDir');
99
+ /** `PUT …/agent-profiles/selection` — which account a project uses for one provider. `null`
100
+ * clears it back to the discovered account. */
101
+ const selectAgentProfileSchema = z.object({
102
+ /** `null` targets the machine-wide default rather than one repo. */
103
+ projectId: z.string().min(1).max(64).nullable(),
104
+ provider: z.enum(PROVIDER_IDS),
105
+ profileId: z.string().max(64).nullable(),
106
+ }).strict();
107
+ /** The hosted-mode refusal, worded like the agent-config one it mirrors. */
108
+ const hostedProfileRefusal = {
109
+ error: 'agent accounts are managed from the machine that owns the checkout (this cockpit runs in hosted mode)',
110
+ };
111
+ /**
112
+ * Allocate a profile id from the label (or, with no label, the folder name).
113
+ *
114
+ * Reuses the project allocator's shape, and deliberately its reserved set too: `default` is the
115
+ * discovered profile here exactly as it is the boot alias there, so a folder called `default/`
116
+ * becomes `default-2` and can never shadow it.
117
+ */
118
+ function allocateAgentProfileId(source, taken) {
119
+ // `allocateProjectSlug` already basenames its argument and enforces the shared
120
+ // `^[a-z0-9][a-z0-9-]{0,63}$` shape, so `~/.claude-klaudiusz` slugs to `claude-klaudiusz`.
121
+ return allocateProjectSlug(source, taken);
122
+ }
123
+ const providerParamSchema = z.enum(PROVIDER_IDS);
124
+ const providerEnabledSchema = z.object({ enabled: z.boolean() }).strict();
125
+ const providerRetrySchema = z.object({
126
+ authFailureId: z.string().min(1).max(128),
127
+ }).strict();
128
+ const automationEditableSchema = z
129
+ .object({
130
+ name: z.string().trim().min(1).max(200),
131
+ description: z.string().max(2_000).optional(),
132
+ enabled: z.boolean().optional(),
133
+ events: z.array(automationEventSchema).min(1).max(4),
134
+ intervalSeconds: z.number().int().min(60).max(86_400),
135
+ filters: automationFiltersSchema,
136
+ task: automationTaskSchema,
137
+ })
138
+ .strict();
139
+ const automationCreateSchema = automationEditableSchema.extend({ enable: z.boolean().optional() });
140
+ const automationUpdateSchema = automationEditableSchema.extend({ expectedRevision: z.number().int().positive() });
141
+ const automationCheckRequestSchema = z.object({ mode: z.enum(['preview', 'execute']) }).strict();
142
+ const automationLogQuerySchema = z.object({
143
+ automationId: z.string().optional(),
144
+ result: automationLogResultSchema.optional(),
145
+ event: automationEventSchema.optional(),
146
+ since: z.string().datetime().optional(),
147
+ cursor: z.coerce.number().int().positive().optional(),
148
+ // Optional, not `.default(100)`: `AutomationStore.logs` already clamps `limit ?? 100` into
149
+ // 1..100, so the default here was a second copy of it — and a defaulted key is REQUIRED in the
150
+ // request type `queryZodValidator` publishes (see validators.ts on why the request side falls
151
+ // back to the schema's output), which would have made every caller send a `?limit=` this route
152
+ // never needed.
153
+ limit: z.coerce.number().int().min(1).max(100).optional(),
154
+ });
155
+ function editableAutomation(definition) {
156
+ return {
157
+ name: definition.name,
158
+ description: definition.description,
159
+ enabled: definition.enabled,
160
+ events: definition.events,
161
+ intervalSeconds: definition.intervalSeconds,
162
+ filters: definition.filters,
163
+ task: definition.task,
164
+ };
165
+ }
166
+ /**
167
+ * The public API surface (spec 2026-07-23-independent-server-web-packages).
168
+ *
169
+ * Every route lives under this one prefix. The unversioned `/api/*` spelling the cockpit used
170
+ * to speak was removed once the whole API was reachable here — carrying two spellings meant two
171
+ * surfaces to keep working, and only one of them could be the typed contract. Bumping to `v2`
172
+ * means mounting a second table beside this one, not editing route paths.
173
+ */
174
+ const V1_PREFIX = '/api/v1';
175
+ /** Project scoping inside the versioned surface. The version is the OUTER dimension, so a
176
+ * consumer picks its API version once and then addresses projects inside it. */
177
+ const V1_SCOPED_PREFIX = `${V1_PREFIX}/p/:projectId`;
55
178
  /**
56
- * The project-scoped route table of a `createApp()` app, derived from its
57
- * actual registrations (so it can never drift from the code): every
58
- * method+path mounted under `/api/p/:projectId/…`, minus the scope-resolver
59
- * middleware (method ALL), deduped. The alias-parity suite iterates this to
60
- * assert unprefixed `/api/<path>` ≡ `/api/p/<boot>/<path>` ≡
61
- * `/api/p/default/<path>`.
179
+ * The project-scoped route table of a `createApp()` app, derived from its actual registrations
180
+ * (so it can never drift from the code): every method+path mounted under
181
+ * `/api/v1/p/:projectId/…`, minus the scope-resolver middleware (method ALL), deduped. The
182
+ * alias-parity suite iterates this to assert `/api/v1/<path>` ≡ `/api/v1/p/<boot>/<path>` ≡
183
+ * `/api/v1/p/default/<path>`.
62
184
  */
63
185
  export function projectRouteManifest(app) {
64
186
  const seen = new Set();
65
187
  const manifest = [];
66
188
  for (const route of app.routes) {
67
- if (route.method === 'ALL' || !route.path.startsWith(`${SCOPED_PREFIX}/`))
189
+ if (route.method === 'ALL' || !route.path.startsWith(`${V1_SCOPED_PREFIX}/`))
68
190
  continue;
69
- const path = route.path.slice(SCOPED_PREFIX.length);
191
+ const path = route.path.slice(V1_SCOPED_PREFIX.length);
70
192
  const key = `${route.method} ${path}`;
71
193
  if (seen.has(key))
72
194
  continue;
@@ -81,10 +203,11 @@ const FOLLOWUPS_OFF = 'the follow-up inbox is disabled — set CEZ_FOLLOWUPS=1 t
81
203
  * The in-process bus for workspace-level SSE events. The registry-mutating
82
204
  * routes (`POST /api/projects` — step 4.2, emits `project-added` for a
83
205
  * genuinely new entry; `DELETE /api/projects/:projectId` — step 4.4) and the
84
- * checkout flow (step 4.3) call `emit()`; every open `/api/workspace/events`
85
- * stream relays the
86
- * event verbatim under its name. Injectable via `ServerDeps.workspaceEvents`
87
- * so tests (and any out-of-createApp emitter) can drive the stream.
206
+ * checkout flow (step 4.3) call `emit()`; runtime provider auth observation
207
+ * emits host-wide `provider-status`; every open `/api/workspace/events` stream
208
+ * relays the event verbatim under its name. Injectable via
209
+ * `ServerDeps.workspaceEvents` so tests (and any out-of-createApp emitter) can
210
+ * drive the stream.
88
211
  */
89
212
  export class WorkspaceEventBus {
90
213
  listeners = new Set();
@@ -120,15 +243,19 @@ const startRunSchema = z
120
243
  // other prompt fields (`systemPrompt` 20k, message `text` 100k) so an
121
244
  // unbounded body can't be piped into a spawned process (#429). 100k chars
122
245
  // (~25k tokens) is well past any hand-written task.
123
- task: z.string().min(1).max(100_000, 'task must be at most 100000 characters'),
246
+ task: z.string().min(1).max(100_000, 'must be at most 100000 characters'),
124
247
  model: z.string().optional(),
125
248
  // Agent backend for this task (falls back to config `defaultRunner`).
126
249
  runner: z.enum(['claude', 'codex', 'opencode']).optional(),
250
+ // Agent account for this task (spec 2026-07-29-agent-profiles). Falls back to the project's
251
+ // own selection, then the discovered default. Bounded like a profile id in the workspace
252
+ // schema, so a value this route accepts can never be degraded away by the next load.
253
+ agentProfile: z.string().max(64).optional(),
127
254
  // Parallel variants (spec 010): ×2/×3 runs the task as 2–3 competing
128
255
  // agents in separate worktrees; the user compares diffs and picks one.
129
256
  variants: z.number().int().min(1).max(3).optional(),
130
257
  // Composer worktree opt-out (#worktree-toggle): false runs in the repo
131
- // working tree (read-only skills). Ignored when variants > 1.
258
+ // working tree. Ignored when variants > 1.
132
259
  worktree: z.boolean().optional(),
133
260
  // Autonomous mode (#autonomous): the run never parks at `waiting` — it
134
261
  // auto-continues until the agent signals done. No "needs you" is raised.
@@ -145,7 +272,7 @@ const startRunSchema = z
145
272
  systemPrompt: z
146
273
  .string()
147
274
  .trim()
148
- .max(20_000, 'systemPrompt must be at most 20000 characters')
275
+ .max(20_000, 'must be at most 20000 characters')
149
276
  .optional()
150
277
  .transform((s) => (s ? s : undefined)),
151
278
  // Screenshots pasted into the new-task form — same shape and limits as a
@@ -163,7 +290,7 @@ const startRunSchema = z
163
290
  // started — the same bookkeeping POST /api/todos/:id/start does, so the
164
291
  // audit trail survives the composer detour. Bounded like every other
165
292
  // string here; a todo id is a short generated key.
166
- todoId: z.string().min(1).max(200, 'todoId must be at most 200 characters').optional(),
293
+ todoId: z.string().min(1).max(200, 'must be at most 200 characters').optional(),
167
294
  })
168
295
  .refine((b) => Boolean(b.workflow) !== Boolean(b.steps), {
169
296
  message: 'provide either "workflow" or "steps", not both',
@@ -173,7 +300,7 @@ const pickSchema = z.object({
173
300
  });
174
301
  const planSchema = z.object({
175
302
  // Same bound as `startRunSchema.task` — this flows into `planChain` (#429).
176
- task: z.string().trim().min(1).max(100_000, 'task must be at most 100000 characters'),
303
+ task: z.string().trim().min(1).max(100_000, 'must be at most 100000 characters'),
177
304
  });
178
305
  // A saved workflow carries full `steps` OR the builder's `skills` stack
179
306
  // (spec 012). `overwrite: true` is the builder's Save on an existing file —
@@ -183,7 +310,7 @@ const saveWorkflowSchema = z
183
310
  name: z.string().trim().min(1).max(80),
184
311
  // Written into a YAML file on disk (#429) — a workflow description is a
185
312
  // short blurb, so a 2k cap is generous without allowing a file-bloat write.
186
- description: z.string().max(2_000, 'description must be at most 2000 characters').optional(),
313
+ description: z.string().max(2_000, 'must be at most 2000 characters').optional(),
187
314
  steps: z.array(workflowStepSchema).min(1).max(8).optional(),
188
315
  skills: z.array(z.string().trim().min(1)).min(1).max(8).optional(),
189
316
  overwrite: z.boolean().optional(),
@@ -206,14 +333,32 @@ const SKILL_USAGE_MAX_ENTRIES = 200;
206
333
  // generous for GUI prefs; over-limit is a 400, never a silent strip. Shared by
207
334
  // BOTH ui-state routes (per-repo and workspace) via `parseUiStateBody`.
208
335
  const UI_STATE_MAX_KEYS = 200;
209
- /** Settings → Appearance (redesign R6): accent + density. ONE schema for both
210
- * ui-state files — per-repo (the legacy home, kept so an older cezar in the
211
- * same repo still honours it) and workspace (`~/.cezar/ui-state.json`, its
212
- * post-migration home — multi-project spec, Data Model). */
336
+ /** Settings → Appearance (redesign R6): accent + density + reading width. ONE
337
+ * schema for both ui-state files — per-repo (the legacy home, kept so an older
338
+ * cezar in the same repo still honours it) and workspace
339
+ * (`~/.cezar/ui-state.json`, its post-migration home — multi-project spec,
340
+ * Data Model).
341
+ *
342
+ * Every key is `.optional()` so an older ui-state.json parses unchanged, but
343
+ * each one must be listed HERE: the enclosing `workspaceUiStateSchema` is
344
+ * `.passthrough()` at the top level only, so an unlisted key inside
345
+ * `appearance` is stripped by zod and then wiped from the file by the shallow
346
+ * merge-on-write. The cockpit adopts the PUT response as authoritative, so a
347
+ * stripped key does not merely fail to persist — it visibly reverts the
348
+ * control the user just touched. Adding an appearance preference means adding
349
+ * it here in the same change. */
213
350
  const appearanceSchema = z.object({
214
351
  accent: z.enum(['lime', 'violet']).optional(),
215
352
  density: z.enum(['comfortable', 'compact', 'ultra']).optional(),
353
+ width: z.enum(['narrow', 'wide']).optional(),
216
354
  });
355
+ const providerAuthDismissalsSchema = z
356
+ .object({
357
+ claude: z.string().min(1).max(128).optional(),
358
+ codex: z.string().min(1).max(128).optional(),
359
+ opencode: z.string().min(1).max(128).optional(),
360
+ })
361
+ .strict();
217
362
  /** Global GUI state (`~/.cezar/ui-state.json`, step 2.7) — the workspace twin
218
363
  * of `uiStateSchema` below, sharing its `.passthrough()` + key-cap + shallow
219
364
  * merge-on-write semantics via `parseUiStateBody`. Known keys are the
@@ -223,6 +368,16 @@ const workspaceUiStateSchema = z
223
368
  .object({
224
369
  appearance: appearanceSchema.optional(),
225
370
  notifications: z.object({ enabled: z.boolean().optional() }).passthrough().optional(),
371
+ dismissedProviderAuthFailures: providerAuthDismissalsSchema.optional(),
372
+ lastLocation: z
373
+ .object({
374
+ projectId: z.string().min(1).max(64),
375
+ pathname: z.string().min(1).max(2048).startsWith('/p/'),
376
+ search: z.string().max(4096).startsWith('?').optional(),
377
+ hash: z.string().max(2048).startsWith('#').optional(),
378
+ })
379
+ .strict()
380
+ .optional(),
226
381
  // Sidebar per-project collapse map, keyed by project id (slug ≤ 64 chars).
227
382
  // Entry-capped like `skillUsage`: the map is written straight to a file the
228
383
  // cockpit GETs on every load, so it must stay bounded on every axis.
@@ -330,7 +485,7 @@ const patchRunSchema = z.object({
330
485
  });
331
486
  // Session commit (redesign R5 — §"Git/session API additions").
332
487
  const gitCommitSchema = z.object({
333
- message: z.string().trim().min(1, 'commit message must not be empty').max(5_000),
488
+ message: z.string().trim().min(1, 'must not be empty').max(5_000),
334
489
  });
335
490
  // "Open in…" (#open-in / #365): `target` selects the app; `path` (optional, worktree-relative)
336
491
  // narrows the target's own worktree/repo-root default to one file — used by the diff pane's
@@ -387,7 +542,7 @@ function foldedLength(task, stack) {
387
542
  // follow-up composer is a full composer, so a screenshot pasted into it must reach the reopened
388
543
  // session rather than being silently dropped.
389
544
  const continueSchema = z.object({
390
- text: z.string().max(100_000, 'text must be at most 100000 characters').optional(),
545
+ text: z.string().max(100_000, 'must be at most 100000 characters').optional(),
391
546
  images: z.array(imageInputSchema).max(4).optional(),
392
547
  runner: z.enum(['claude', 'codex', 'opencode']).optional(),
393
548
  model: z.string().max(200).optional(),
@@ -406,7 +561,7 @@ const startTodoSchema = z
406
561
  prompt: z
407
562
  .string()
408
563
  .trim()
409
- .max(20_000, 'prompt must be at most 20000 characters')
564
+ .max(20_000, 'must be at most 20000 characters')
410
565
  .optional()
411
566
  .transform((s) => (s ? s : undefined)),
412
567
  })
@@ -432,21 +587,100 @@ function stripHostPort(host) {
432
587
  return bracketed[1];
433
588
  return host.replace(/:\d+$/, '');
434
589
  }
435
- /** The shared write-side half of BOTH ui-state routes (per-repo `/api/ui-state`
436
- * and workspace `/api/workspace/ui-state`) — the factored split the
437
- * multi-project spec calls for instead of a copy: parse with the route's own
438
- * schema, then cap the top-level key count so a `.passthrough()` schema can't
439
- * accumulate an unbounded key set (#429). The merge-on-write stays with each
440
- * route (they write different files) but is shallow in both. */
441
- function parseUiStateBody(schema, body) {
442
- const parsed = schema.safeParse(body);
443
- if (!parsed.success)
444
- return { error: parsed.error.issues.map((i) => i.message).join('; ') };
445
- if (Object.keys(parsed.data).length > UI_STATE_MAX_KEYS) {
446
- return { error: `ui-state has too many keys (max ${UI_STATE_MAX_KEYS})` };
590
+ /** The shared write-side half of BOTH ui-state routes (per-repo `/api/v1/ui-state`
591
+ * and workspace `/api/v1/workspace/ui-state`) — the factored split the
592
+ * multi-project spec calls for instead of a copy: the route's own schema, plus a
593
+ * cap on the top-level key count so a `.passthrough()` schema can't accumulate an
594
+ * unbounded key set (#429). The cap rides as a refinement so the whole thing is one
595
+ * schema and can go through `jsonBody` like every other mutating route. The
596
+ * merge-on-write stays with each route (they write different files) but is shallow
597
+ * in both. */
598
+ function capUiStateKeys(data, ctx) {
599
+ if (Object.keys(data).length > UI_STATE_MAX_KEYS) {
600
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: `ui-state has too many keys (max ${UI_STATE_MAX_KEYS})` });
601
+ }
602
+ }
603
+ // Derived once per route instead of by a generic `wrap(schema)` helper called at the route: a
604
+ // generic wrapper leaves the schema type unresolved where `jsonBody` needs it, and Hono answers
605
+ // that by dropping the whole PUT from the route schema rather than erroring — both ui-state PUTs
606
+ // silently vanished from `AppType`. Concrete consts keep them visible to `hc`.
607
+ const workspaceUiStateBody = workspaceUiStateSchema.superRefine(capUiStateKeys);
608
+ const uiStateBody = uiStateSchema.superRefine(capUiStateKeys);
609
+ /**
610
+ * Query schemas for the READ routes — deliberately permissive.
611
+ *
612
+ * These exist to make a query key VISIBLE to the route type (`hc` refuses a `query` argument for
613
+ * a key no validator declares), NOT to narrow what the route accepts. Every one of these handlers
614
+ * compares `=== '1'` and treats everything else as false, so `?refresh=0` is a successful request
615
+ * today; a literal schema would silently turn it into a 400. The comparison stays in the handler
616
+ * and the validator stays out of its way.
617
+ *
618
+ * The one route that really is strict on the wire — `GET /github/prs/:number/changes`, which 400s
619
+ * on `?refresh=true` — keeps its own `z.enum(['1'])` schema next to the route.
620
+ */
621
+ /**
622
+ * One query value, matching what `c.req.query('k')` did before these routes were validated.
623
+ *
624
+ * Hono's query validator hands a REPEATED key as an array (`?wait=1&wait=1` → `['1','1']`), where
625
+ * `c.req.query()` silently took the first. A plain `z.string()` therefore turns a request that
626
+ * used to answer 200 into a 400 — a wire change no caller asked for. Collapsing to the first
627
+ * value keeps the old behaviour, and the client still sees a plain `key?: string`.
628
+ */
629
+ const queryValue = z.union([z.string(), z.array(z.string()).transform((v) => v[0])]).optional();
630
+ const refreshQuery = z.object({ refresh: queryValue });
631
+ const waitQuery = z.object({ wait: queryValue });
632
+ function parseAccept(header) {
633
+ const ranges = [];
634
+ for (const part of header.split(',')) {
635
+ const [range = '', ...params] = part.split(';');
636
+ const [type = '', subtype = ''] = range.trim().toLowerCase().split('/');
637
+ if (type === '' || subtype === '')
638
+ continue;
639
+ const weight = params.map((p) => p.trim().toLowerCase()).find((p) => p.startsWith('q='));
640
+ const parsed = weight === undefined ? 1 : Number.parseFloat(weight.slice(2));
641
+ const q = Number.isFinite(parsed) ? Math.min(Math.max(parsed, 0), 1) : 0;
642
+ if (q > 0)
643
+ ranges.push({ type, subtype, q });
644
+ }
645
+ return ranges;
646
+ }
647
+ /**
648
+ * The best of `offers` for this `Accept`, or `null` for "no preference expressed" — which is what
649
+ * an absent header, a `*<slash>*`-only header and a header naming nothing on offer all mean, and
650
+ * what leaves the caller on its route's default.
651
+ *
652
+ * `offers` is the server's own preference order: an offer may itself be a wildcard (`image/*`,
653
+ * since the concrete image type is not known until the file is read), and equal q-values go to the
654
+ * EARLIER offer, so each route lists its default representation first.
655
+ */
656
+ function negotiate(accept, offers) {
657
+ if (accept === undefined)
658
+ return null;
659
+ const ranges = parseAccept(accept);
660
+ let best = null;
661
+ for (const offer of offers) {
662
+ const [type = '', subtype = ''] = offer.split('/');
663
+ let q = 0;
664
+ for (const range of ranges) {
665
+ if (range.type === '*' && range.subtype === '*')
666
+ continue; // "anything" is not a preference
667
+ const typeMatches = range.type === type || range.type === '*' || type === '*';
668
+ const subtypeMatches = range.subtype === subtype || range.subtype === '*' || subtype === '*';
669
+ if (typeMatches && subtypeMatches && range.q > q)
670
+ q = range.q;
671
+ }
672
+ if (q > 0 && (best === null || q > best.q))
673
+ best = { offer, q };
447
674
  }
448
- return { data: parsed.data };
675
+ return best?.offer ?? null;
449
676
  }
677
+ /** What `GET /repo/commit/:sha` offers, DEFAULT FIRST: the legacy `text/plain` blob is what a
678
+ * request with no opinion has always received (§2), so it also wins an Accept tie. */
679
+ const COMMIT_FORMATS = ['text/plain', 'application/json'];
680
+ /** What `GET /runs/:id/files` offers, DEFAULT FIRST. `image/*` rather than a concrete type: which
681
+ * image type the bytes are is only known once the path resolves, and the raw branch refuses
682
+ * everything that is not an image anyway. */
683
+ const FILE_FORMATS = ['application/json', 'image/*'];
450
684
  /** Workspace-root writability probe (multi-project spec, "API Contracts"):
451
685
  * optional `mkdir -p`, `access W_OK`, then a real create/delete round-trip — W_OK alone
452
686
  * can lie (e.g. a read-only mount still reports writable permission bits).
@@ -469,6 +703,10 @@ async function probeWritableDir(dir, create) {
469
703
  return err instanceof Error ? err.message : String(err);
470
704
  }
471
705
  }
706
+ // The return type is INFERRED on purpose: it is the chained app type built at the bottom of
707
+ // this function, and `AppType` (src/server/app-type.ts) is `ReturnType<typeof createApp>`.
708
+ // Annotating it `Hono` here would erase every route from the type and leave the typed client
709
+ // with nothing to offer. See the `routed` assembly at the end of the function.
472
710
  export function createApp(deps) {
473
711
  const { version, update, bindHost, bootProjectId } = deps;
474
712
  // Boot singletons keep DELIBERATELY distinct names (`boot*`): every
@@ -481,6 +719,54 @@ export function createApp(deps) {
481
719
  const modelCatalog = deps.modelCatalog ?? new RunnerModelCatalog({
482
720
  adapters: { codex: { discover: () => discoverCodexModels({ cwd: bootRoot }) } },
483
721
  });
722
+ const providerAuth = deps.providerAuth ?? new ProviderAuthService();
723
+ const workspaceConfig = deps.workspaceConfig ?? {
724
+ load: loadWorkspaceConfig,
725
+ mergeWrite: mergeWriteWorkspaceConfig,
726
+ };
727
+ const providerStatus = async (options) => {
728
+ if (providerAuthChecksDisabled()) {
729
+ return applyProviderEnablement(await providerAuth.status(options?.refresh ? { refresh: true } : undefined), []);
730
+ }
731
+ const [discovered, workspace] = await Promise.all([
732
+ providerAuth.status(options?.refresh ? { refresh: true } : undefined),
733
+ workspaceConfig.load(),
734
+ ]);
735
+ return applyProviderEnablement(discovered, workspace.disabledProviders);
736
+ };
737
+ /**
738
+ * The gate: why a run cannot start against `required`, or null when it can.
739
+ *
740
+ * VERIFY BEFORE YOU REFUSE. Auth state is served stale-while-revalidate (see
741
+ * `ProviderAuthService.status`), so a cached "disconnected" may predate a login cezar could not
742
+ * observe — someone running `claude auth login` in a terminal. Refusing on that would lock a user
743
+ * out of their own cockpit with no way back but waiting. So a believed-unavailable provider is
744
+ * re-probed, and only a refusal that survives the fresh answer is returned.
745
+ *
746
+ * The cost lands where it belongs: the common path (connected, warm) pays nothing at all, and the
747
+ * probe is only spawned when cezar is about to say no — a rare, interactive moment. This is also
748
+ * what lets the cache hold a negative for a minute instead of five seconds, which is what made
749
+ * every reader of `GET /providers/status` periodically pay for a CLI spawn.
750
+ *
751
+ * A runtime auth latch is deliberately NOT escaped by this: `withRuntimeFailures` keeps forcing
752
+ * the row disconnected until the user acknowledges that exact incident, so the re-probe cannot
753
+ * talk cezar out of a rejection it actually observed.
754
+ */
755
+ const providerActionError = async (required) => {
756
+ const known = await providerStatus();
757
+ const message = unavailableProviderMessage(required, known);
758
+ if (message === null)
759
+ return null;
760
+ // A DISABLED provider is a settings fact, not a probe result — re-probing it learns nothing and
761
+ // would spawn a CLI to re-read something the user typed.
762
+ const disabled = required.some((provider) => known.providers.find((row) => row.provider === provider)?.enabled === false);
763
+ if (disabled)
764
+ return message;
765
+ return unavailableProviderMessage(required, await providerStatus({ refresh: true }));
766
+ };
767
+ const openTerminal = deps.openTerminal ?? openInTerminal;
768
+ const openFile = deps.openFile ?? openFileInDefaultApp;
769
+ const skillsUpdate = deps.skillsUpdate ?? new SkillsUpdateService();
484
770
  // ---- workspace boot-project identity (multi-project spec) ----------------
485
771
  // The boot flow (`initWorkspace` in src/index.ts) registers the boot repo
486
772
  // and plumbs its registry id in via `deps.bootProjectId`. Legacy callers and
@@ -551,6 +837,7 @@ export function createApp(deps) {
551
837
  dataDir: bootDataDir,
552
838
  store: deps.store,
553
839
  manager: deps.manager,
840
+ automationStore: deps.automationStore ?? AutomationStore.open(bootDataDir),
554
841
  launchKey: ensureLaunchKey(bootDataDir), // bookmarklet auto-start secret (spec 011)
555
842
  };
556
843
  // Non-boot projects build lazily on first scoped request; their managers
@@ -567,6 +854,25 @@ export function createApp(deps) {
567
854
  // Workspace-level SSE bus (step 2.8) — the registry mutators and the
568
855
  // checkout flow (Phase 4) emit here; /api/workspace/events relays.
569
856
  const workspaceEvents = deps.workspaceEvents ?? new WorkspaceEventBus();
857
+ const emitAutomationChange = (project, automationId, revision, deleted = false) => workspaceEvents.emit('automation-change', {
858
+ project: project.id,
859
+ automationId,
860
+ revision,
861
+ ...(deleted ? { deleted: true } : {}),
862
+ });
863
+ const automationsChanged = () => deps.automationsChanged?.();
864
+ const providerRuntimeAuth = deps.providerRuntimeAuth
865
+ ?? new ProviderRuntimeAuthObserver(providerAuth, (status) => {
866
+ workspaceEvents.emit('provider-status', status);
867
+ });
868
+ providerRuntimeAuth.watch(bootContext.store);
869
+ for (const id of contexts.ids()) {
870
+ const ctx = contexts.peek(id);
871
+ if (ctx)
872
+ providerRuntimeAuth.watch(ctx.store);
873
+ }
874
+ contexts.onStoreCreated((store) => providerRuntimeAuth.watch(store));
875
+ contexts.onContextBuilt((ctx) => providerRuntimeAuth.watch(ctx.store));
570
876
  const app = new Hono();
571
877
  // Reject oversized request bodies before they reach any handler (#429). GETs
572
878
  // and SSE carry no body, so this only ever gates the mutating routes.
@@ -577,7 +883,7 @@ export function createApp(deps) {
577
883
  // own: any page the user visits can still POST to us (CSRF), and DNS
578
884
  // rebinding can point a foreign domain at loopback and read our responses.
579
885
  // Two zero-config checks close both holes on every /api route EXCEPT
580
- // /api/health (the intentional cross-origin discovery endpoint, spec 011 —
886
+ // /api/v1/health (the intentional cross-origin discovery endpoint, spec 011 —
581
887
  // it exposes nothing sensitive, see #431):
582
888
  // 1. Host allowlist (loopback deployments only) — a request whose Host is
583
889
  // not a loopback name did not really originate from this machine. A
@@ -600,7 +906,7 @@ export function createApp(deps) {
600
906
  // Scope note: check 2 covers writes only. A cross-origin GET from any site
601
907
  // still reaches the read routes — but its Host is ours, so it is a *forced
602
908
  // request*, not a read: the same-origin policy stops the attacker seeing any
603
- // response body (we send CORS headers on /api/health alone), and no GET
909
+ // response body (we send CORS headers on /api/v1/health alone), and no GET
604
910
  // handler mutates state. Rebinding, which WOULD make those reads legible, is
605
911
  // what check 1 stops.
606
912
  const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
@@ -615,9 +921,12 @@ export function createApp(deps) {
615
921
  error: 'forbidden: unexpected Host header — this request did not originate from this machine (see #426)',
616
922
  }, 403);
617
923
  }
618
- // /api/health stays CORS-open for bookmarklet discovery, but its Host is
619
- // still checked above: cross-origin is legitimate, DNS rebinding is not.
620
- if (c.req.path === '/api/health')
924
+ // /api/v1/health stays CORS-open for cross-origin discovery, but its Host is
925
+ // still checked above: cross-origin is legitimate, DNS rebinding is not. The
926
+ // path is spelled through V1_PREFIX rather than inline — an unversioned
927
+ // literal here silently stopped matching when the API moved and left health
928
+ // relying on the mutating-methods gate below to let its GETs through.
929
+ if (c.req.path === `${V1_PREFIX}/health`)
621
930
  return next();
622
931
  if (MUTATING_METHODS.has(c.req.method)) {
623
932
  const origin = c.req.header('origin');
@@ -661,15 +970,16 @@ export function createApp(deps) {
661
970
  });
662
971
  // The mirrored project-route table (spec "API Contracts → Project-scoped").
663
972
  // Every route below registers ONCE on this sub-app; `createApp` mounts it
664
- // twice — under `/api/p/:projectId` (scoped) and under `/api` (the legacy
665
- // aliases, protected surfaces) — so both spellings share one handler and
666
- // can never drift. The resolver middleware binds `c.get('project')`:
667
- // no `projectId` param (legacy mount) → the boot context, byte-identical to
973
+ // twice — under `/api/v1/p/:projectId` (scoped) and under `/api/v1` (bound to
974
+ // the boot project) — so both spellings share one handler and can never
975
+ // drift. The resolver middleware binds `c.get('project')`:
976
+ // no `projectId` param (unscoped mount) → the boot context, byte-identical to
668
977
  // the pre-workspace closures; `default` or the boot project's own id → the
669
978
  // boot context too; anything else → the lazy context map, with
670
979
  // `ProjectContextError` mapped to 404 (unknown) / 409 (missing root).
671
- const api = new Hono();
672
- api.use('*', async (c, next) => {
980
+ // Named rather than inlined because both mounts share it — one function, so
981
+ // the two spellings can never disagree about what `default` means.
982
+ const resolveProjectScope = async (c, next) => {
673
983
  const raw = c.req.param('projectId');
674
984
  if (raw === undefined) {
675
985
  c.set('project', bootContext);
@@ -694,15 +1004,23 @@ export function createApp(deps) {
694
1004
  throw err;
695
1005
  }
696
1006
  return next();
697
- });
1007
+ };
698
1008
  // ---- static GUI ----------------------------------------------------------
699
1009
  const webDir = resolveWebDir();
700
1010
  const distDir = join(webDir, 'dist');
701
1011
  const HTML_TYPE = 'text/html; charset=utf-8';
702
- const staticFile = (name, type) => () => {
1012
+ const staticFile = (name, type) => (c) => {
703
1013
  // Read per request — the files are tiny and this keeps dev iteration live.
704
- const body = readFileSync(join(webDir, name));
705
- return new Response(body, { headers: { 'content-type': type } });
1014
+ //
1015
+ // Served out of the Vite build: the file is a `public/` asset of the web package, which the
1016
+ // build copies verbatim into `web/dist`. One home, one URL — the same bytes this route
1017
+ // hands out are what the bundle's own `<img src="/open-mercato.svg">` asks for.
1018
+ // Without a build there is nothing to serve, which is a 404 rather than a crash (the shell
1019
+ // route answers the same dev-only state with its build hint).
1020
+ const path = join(distDir, name);
1021
+ if (!existsSync(path))
1022
+ return c.json({ error: 'not found' }, 404);
1023
+ return new Response(readFileSync(path), { headers: { 'content-type': type } });
706
1024
  };
707
1025
  let hintLogged = false;
708
1026
  const serveShell = (c) => {
@@ -749,14 +1067,14 @@ export function createApp(deps) {
749
1067
  },
750
1068
  });
751
1069
  });
752
- // The favicon web/app/index.html points at (`../open-mercato.svg`).
1070
+ // The favicon packages/web/index.html points at (`/open-mercato.svg`).
753
1071
  app.get('/open-mercato.svg', staticFile('open-mercato.svg', 'image/svg+xml'));
754
1072
  // ---- meta ----------------------------------------------------------------
755
1073
  // CORS — deliberately for /api/health ONLY (spec 011): the bookmarklets
756
1074
  // fetch it cross-origin from github.com to discover which local ports run a
757
1075
  // cockpit and which repo each serves. Health exposes no secrets beyond the
758
1076
  // repo path/remote; every other endpoint stays same-origin.
759
- app.use('/api/health', async (c, next) => {
1077
+ const healthCors = async (c, next) => {
760
1078
  c.header('access-control-allow-origin', '*');
761
1079
  if (c.req.method === 'OPTIONS') {
762
1080
  // Preflight (e.g. Chrome Private Network Access) — allow the plain GET.
@@ -765,10 +1083,16 @@ export function createApp(deps) {
765
1083
  return c.body(null, 204);
766
1084
  }
767
1085
  await next();
768
- });
1086
+ };
1087
+ app.use(`${V1_PREFIX}/health`, healthCors);
769
1088
  // One builder for both transports: `GET /api/health` (the authoritative,
770
- // CORS-open discovery endpoint) and the `health` topic on `/api/ws` below
1089
+ // CORS-open discovery endpoint) and the `health` topic on `/api/v1/ws` below
771
1090
  // push the byte-identical shape, so the two can never drift.
1091
+ // Deliberately UNANNOTATED: this literal is the source of the `/health` shape. Annotating it
1092
+ // with the api-client's `HealthResponse` made the contract circular — the DTO was declared by
1093
+ // hand, the handler was checked against it, and `AppType` then reported the hand-written type
1094
+ // back as if the server had proven it. Inferring here means the route says what it actually
1095
+ // sends, which is what lets the DTO be derived instead of maintained.
772
1096
  const healthSnapshot = async () => {
773
1097
  const [checks, repo, config, workspace] = await Promise.all([
774
1098
  detectEnvironment(),
@@ -782,7 +1106,11 @@ export function createApp(deps) {
782
1106
  const caps = capabilities();
783
1107
  return {
784
1108
  version,
785
- latestVersion: update?.latest,
1109
+ // Spread rather than `latestVersion: update?.latest`: an `undefined` VALUE is dropped by
1110
+ // JSON.stringify, so the key is absent on the wire — but writing it unconditionally types
1111
+ // the key as always-present, which is a shape no client ever receives. The contract schema
1112
+ // says `.optional()`, and contract-parity.test.ts holds the two together.
1113
+ ...(update?.latest !== undefined ? { latestVersion: update.latest } : {}),
786
1114
  // Health is CORS-open and, in hosted mode, reachable off the loopback —
787
1115
  // so any site/host that reads it would learn the developer's absolute
788
1116
  // checkout path and username (#431). Local mode keeps the full path (the
@@ -874,7 +1202,13 @@ export function createApp(deps) {
874
1202
  void refreshHealth(); // stale: refresh, don't wait on it
875
1203
  return healthCache.payload;
876
1204
  };
877
- app.get('/api/health', async (c) => c.json(await readHealth()));
1205
+ // ---- chained family: health (workspace-level) ----------------------------
1206
+ // Written as ONE chained expression rather than a loose `app.get(...)`
1207
+ // statement because Hono accumulates its route types through the chain: a
1208
+ // statement's return value is discarded, so `typeof app` would record nothing
1209
+ // and `hc<AppType>` would have no endpoint to offer. `createApp` mounts this
1210
+ // under both `/api` (the frozen legacy spelling) and `/api/v1`.
1211
+ const healthRoutes = new Hono().get('/health', async (c) => c.json(await readHealth()));
878
1212
  // The push twin of the poll it replaced (#369): while at least one cockpit
879
1213
  // holds the `health` topic the server re-reads the snapshot on the old 5 s
880
1214
  // cadence and broadcasts ONLY when it changed — a `git checkout` in a
@@ -906,14 +1240,676 @@ export function createApp(deps) {
906
1240
  // `GET /api/health` reads a warm value instead of the cold ~1 s compute.
907
1241
  if (deps.socketHub)
908
1242
  void refreshHealth();
909
- // Host capability, not project state: one installed/authenticated Codex CLI
910
- // and one in-memory cache are shared by every registered workspace.
911
- app.get('/api/models', async (c) => {
912
- const query = z.object({ runner: z.literal('codex') }).safeParse(c.req.query());
913
- if (!query.success)
914
- return c.json({ error: 'runner must be codex' }, 400);
1243
+ /**
1244
+ * Warm the whole of cezar's agent knowledge — the three discovered defaults AND every extra
1245
+ * account — so no reader ever pays the first shell-out.
1246
+ *
1247
+ * Which login each agent is signed into is operating knowledge, not a settings-page detail: the
1248
+ * composer, the action gate, the accounts pane and every run resolution ask for it. So the server
1249
+ * learns it once, at boot, and keeps it (see the asymmetric cache lifetime in
1250
+ * `core/provider-auth.ts`); on-demand refresh rides on `?refresh=1` and on the explicit
1251
+ * invalidations — connect, repoint, remove, runtime rejection.
1252
+ *
1253
+ * Extra accounts are warmed ONE AT A TIME, after the defaults. Each is a CLI spawn, and a machine
1254
+ * with several accounts would otherwise fan out a spawn storm at exactly the moment the browser is
1255
+ * fetching the bundle; nothing is waiting on this, so sequential costs nothing that matters.
1256
+ *
1257
+ * Hosted mode warms only the defaults: the agent-profiles family is refused there, so there are
1258
+ * no accounts to learn about.
1259
+ */
1260
+ const warmAgentKnowledge = async () => {
1261
+ await providerAuth.status().catch(() => { });
1262
+ if (!capabilities().localHandoff)
1263
+ return;
1264
+ const store = await loadAgentAccounts().catch(() => defaultAgentAccountStore());
1265
+ for (const account of listAgentProfiles(store, PROVIDER_IDS)) {
1266
+ if (account.isDefault)
1267
+ continue; // covered by `status()` above
1268
+ await providerAuth
1269
+ .profileStatus(account.provider, { id: account.id, configDir: account.path })
1270
+ .catch(() => { });
1271
+ }
1272
+ };
1273
+ // Same gate as `refreshHealth`, same reason (startServer injects the hub; a bare app in tests does
1274
+ // not, so tests never spawn probes here). Fire-and-forget: a probe that fails leaves that row
1275
+ // cold, which is exactly the state every reader already handles.
1276
+ if (deps.socketHub)
1277
+ void warmAgentKnowledge();
1278
+ // ---- chained family: host model catalog (workspace-level) ----
1279
+ const modelsRoutes = new Hono()
1280
+ .get('/models', queryZodValidator(z.object({ runner: z.union([z.string(), z.array(z.string()).transform((v) => v[0])]).pipe(z.literal('codex')) }), { message: 'runner must be codex' }), async (c) => {
1281
+ const query = { data: c.req.valid('query') };
915
1282
  return c.json(await modelCatalog.get(query.data.runner));
916
1283
  });
1284
+ /**
1285
+ * Resolve `profileId` (absent = the discovered default) into a concrete account for `provider`.
1286
+ *
1287
+ * A dangling id is an ERROR here rather than the silent fall-back to the default that run
1288
+ * resolution performs. The difference is who is asking: a run is replaying a stored reference
1289
+ * and the default is the only safe answer it can act on, whereas a route is answering a user
1290
+ * who just named an account — telling them "unknown account" is honest, and quietly connecting
1291
+ * or reporting on a different one is not.
1292
+ */
1293
+ const resolveWorkspaceProfile = async (provider, profileId) => {
1294
+ if (profileId === undefined || profileId === DEFAULT_AGENT_ACCOUNT_ID) {
1295
+ return { profile: defaultAgentProfile(provider) };
1296
+ }
1297
+ let accounts;
1298
+ try {
1299
+ accounts = (await loadAgentAccounts()).accounts;
1300
+ }
1301
+ catch {
1302
+ return { error: `unknown ${provider} account: ${profileId}` };
1303
+ }
1304
+ const stored = accounts.find((a) => a.id === profileId && a.provider === provider);
1305
+ if (!stored)
1306
+ return { error: `unknown ${provider} account: ${profileId}` };
1307
+ return { profile: resolveStoredProfile(stored) };
1308
+ };
1309
+ /**
1310
+ * The environment a terminal handoff must carry so the CLI lands on the right account.
1311
+ *
1312
+ * `profileId` is the one RECORDED on the step that owns the session, never the project's
1313
+ * current selection: `claude --resume <id>` reads `<configDir>/sessions`, so a handoff for a
1314
+ * run started on the work account and resumed after the project was switched back would find
1315
+ * nothing and silently open a fresh conversation.
1316
+ */
1317
+ const handoffEnv = async (provider, profileId) => {
1318
+ const resolved = await resolveWorkspaceProfile(provider, profileId);
1319
+ if ('error' in resolved) {
1320
+ return { error: `this session belongs to an account that no longer exists (${profileId})` };
1321
+ }
1322
+ const { profile } = resolved;
1323
+ return { env: profile.isDefault ? {} : profileEnv(provider, profile.path) };
1324
+ };
1325
+ /** The copy-paste fallback shown when no terminal could be opened — same account, spelled for
1326
+ * this platform's shell. `null` when the dir cannot be embedded safely, which is a refusal. */
1327
+ const handoffFallbackCommand = (cwd, command, env) => {
1328
+ const prefixed = withEnvPrefix(command, env, process.platform);
1329
+ return prefixed === null ? null : `cd '${cwd}' && ${prefixed}`;
1330
+ };
1331
+ /** A registered project's realpath'd root, or null when the id is unknown. */
1332
+ const projectRootFor = async (projectId) => {
1333
+ try {
1334
+ return (await loadWorkspaceConfig()).projects.find((p) => p.id === projectId)?.root ?? null;
1335
+ }
1336
+ catch {
1337
+ return null;
1338
+ }
1339
+ };
1340
+ // ---- chained family: agent providers (workspace-level) ----
1341
+ const providersRoutes = new Hono()
1342
+ .get('/providers/status', queryZodValidator(z.object({ refresh: queryValue.refine((v) => v === undefined || v === '1') }), { message: 'refresh must be 1 when provided' }), async (c) => {
1343
+ const query = { data: c.req.valid('query') };
1344
+ return c.json(await providerStatus({ refresh: query.data.refresh === '1' }));
1345
+ })
1346
+ .put('/providers/:provider/enabled', paramZodValidator(z.object({ provider: providerParamSchema }), { message: 'provider and enabled boolean are required' }), jsonZodValidator(providerEnabledSchema, { message: 'provider and enabled boolean are required' }), async (c) => {
1347
+ const provider = { data: c.req.valid('param').provider };
1348
+ const body = { data: c.req.valid('json') };
1349
+ let workspace;
1350
+ try {
1351
+ workspace = await workspaceConfig.mergeWrite((config) => {
1352
+ const disabled = new Set(config.disabledProviders);
1353
+ if (body.data.enabled)
1354
+ disabled.delete(provider.data);
1355
+ else
1356
+ disabled.add(provider.data);
1357
+ config.disabledProviders = PROVIDER_IDS.filter((id) => disabled.has(id));
1358
+ });
1359
+ }
1360
+ catch {
1361
+ return c.json({ error: 'Provider preference could not be saved.' }, 500);
1362
+ }
1363
+ const result = applyProviderEnablement(await providerAuth.status(), workspace.disabledProviders);
1364
+ const row = result.providers.find(({ provider: id }) => id === provider.data);
1365
+ if (row)
1366
+ workspaceEvents.emit('provider-status', row);
1367
+ return c.json(result);
1368
+ })
1369
+ .post('/providers/:provider/retry', paramZodValidator(z.object({ provider: providerParamSchema }), { message: 'provider and current authFailureId are required' }), jsonZodValidator(providerRetrySchema, { message: 'provider and current authFailureId are required' }), async (c) => {
1370
+ const provider = { data: c.req.valid('param').provider };
1371
+ const body = { data: c.req.valid('json') };
1372
+ if (!providerAuth.clearRuntimeAuthFailure(provider.data, body.data.authFailureId)) {
1373
+ return c.json({ error: 'Authentication incident changed. Refresh and try again.' }, 409);
1374
+ }
1375
+ const result = await providerStatus({ refresh: true });
1376
+ const row = result.providers.find(({ provider: id }) => id === provider.data);
1377
+ if (row)
1378
+ workspaceEvents.emit('provider-status', row);
1379
+ return c.json(result);
1380
+ })
1381
+ .post('/providers/connect', jsonZodValidator(providerConnectSchema, { message: 'provider must be claude, codex, or opencode' }), async (c) => {
1382
+ const body = { data: c.req.valid('json') };
1383
+ const provider = body.data.provider;
1384
+ // A NAMED account is refused in hosted mode before anything is resolved, exactly like every
1385
+ // sibling route in the agent-profiles family. Checking later would already have read
1386
+ // `~/.cezar/agent-accounts.json`, built a command carrying the account's absolute path (which
1387
+ // both the success body and the hosted 409 echo), and — for a stored account — spawned a
1388
+ // probe. It would also answer `unknown account: <id>` for a wrong id, which is an enumeration
1389
+ // oracle for the very ids the hosted listing withholds. The bare-provider spelling keeps its
1390
+ // existing behaviour: it names no host path and is how the Providers card has always worked.
1391
+ if (body.data.profileId !== undefined
1392
+ && body.data.profileId !== DEFAULT_AGENT_ACCOUNT_ID
1393
+ && !capabilities().localHandoff) {
1394
+ return c.json(hostedProfileRefusal, 409);
1395
+ }
1396
+ // Resolve the account BEFORE anything else: both the command and the status probe below
1397
+ // must describe the same one, or the pane reports on the personal login while the terminal
1398
+ // signs into the work login.
1399
+ const resolved = await resolveWorkspaceProfile(provider, body.data.profileId);
1400
+ if ('error' in resolved)
1401
+ return c.json({ error: resolved.error }, 400);
1402
+ const { profile } = resolved;
1403
+ const command = providerAuth.loginCommand(provider, profile.isDefault ? null : profile.path);
1404
+ // Fail closed: a config dir that cannot be embedded safely in this platform's shell has no
1405
+ // safe degradation. Running the bare command would sign the user into a DIFFERENT account
1406
+ // than the one they clicked, and nothing in the terminal would say so.
1407
+ if (command === null) {
1408
+ return c.json({ error: `This account's folder cannot be used in a terminal command: ${profile.configDir}` }, 409);
1409
+ }
1410
+ // BOTH branches must mean "is this account signed in NOW". The default branch refreshes; the
1411
+ // account branch has to evict first, because `profileStatus` serves the per-account cache and
1412
+ // a connected answer there stands for CONNECTED_TTL_MS. Without this, Connect after a
1413
+ // `claude /logout` answers "already connected", opens nothing, and the user is stuck — and it
1414
+ // would contradict this module's own invariant that opening a login is one of the things
1415
+ // cezar CAN observe and therefore invalidates explicitly rather than waiting out a window.
1416
+ if (!profile.isDefault)
1417
+ providerAuth.forgetProfileStatus(provider, profile.id);
1418
+ const row = profile.isDefault
1419
+ ? (await providerAuth.status({ refresh: true })).providers.find((candidate) => candidate.provider === provider)
1420
+ : await providerAuth.profileStatus(provider, { id: profile.id, configDir: profile.path });
1421
+ if (!row) {
1422
+ return c.json({ error: 'Authentication could not be verified. Try again.' }, 500);
1423
+ }
1424
+ if (row.status === 'connected') {
1425
+ return c.json({ opened: false, connected: true, command });
1426
+ }
1427
+ if (row.status === 'not-installed') {
1428
+ return c.json({ error: row.hint ?? providerAuth.installHint(provider), command }, 409);
1429
+ }
1430
+ if (row.status === 'unknown') {
1431
+ return c.json({ error: row.hint ?? 'Authentication could not be verified. Try again.', command }, 409);
1432
+ }
1433
+ if (!capabilities().localHandoff) {
1434
+ return c.json({ error: 'Run this command on the machine hosting cezar.', command }, 409);
1435
+ }
1436
+ let opened = false;
1437
+ try {
1438
+ // No `env` argument: `loginCommand` already rendered the account's config dir INTO the
1439
+ // command, because this string is also the copy-paste fallback the pane shows. Passing
1440
+ // it again here would set the variable twice.
1441
+ opened = await openTerminal(bootRoot, command);
1442
+ }
1443
+ catch {
1444
+ // Terminal handoff is best-effort; the exact command remains the safe fallback.
1445
+ }
1446
+ if (!opened) {
1447
+ return c.json({ error: 'No terminal emulator could be opened. Run this command manually.', command }, 409);
1448
+ }
1449
+ return c.json({ opened: true, command });
1450
+ });
1451
+ // ---- chained family: agent profiles / accounts (workspace-level) ----------
1452
+ // Extra config dirs for a SECOND login of the same agent CLI (spec
1453
+ // 2026-07-29-agent-profiles). Workspace-level and therefore SINGLE-MOUNT: an account belongs to
1454
+ // the person and the machine, never to a repo, and a project-scoped spelling would be a second
1455
+ // surface to protect with no consumer. Which account a project uses is a field on
1456
+ // `PATCH /api/v1/projects/:projectId` instead.
1457
+ //
1458
+ // Writing is a LOCAL-MACHINE capability, exactly like `PUT /api/v1/agent-config/:id`: a profile
1459
+ // points an agent at a directory on the host, and the listing echoes absolute paths carrying
1460
+ // the username — the same disclosure `/api/v1/health` trims in hosted mode (#431).
1461
+ /**
1462
+ * This agent's own USER-scope config files, resolved inside ONE account's folder.
1463
+ *
1464
+ * Straight from the catalog — the single home of config-file vendor knowledge — with an
1465
+ * `AgentHomePaths` whose slot for this provider is the account's dir. That is what makes a second
1466
+ * login's `settings.json` the file you open rather than the default account's, and it keeps the
1467
+ * ids opaque and stable so the open route below never takes a path from the client.
1468
+ */
1469
+ const accountFiles = async (profile) => {
1470
+ const home = {
1471
+ ...agentHomePaths(),
1472
+ ...(profile.provider === 'claude' ? { claude: profile.path } : {}),
1473
+ ...(profile.provider === 'codex' ? { codex: profile.path } : {}),
1474
+ ...(profile.provider === 'opencode' ? { opencodeConfig: profile.path } : {}),
1475
+ };
1476
+ const defs = listConfigFiles().filter((def) => def.scope === 'user' && def.runners.includes(profile.provider));
1477
+ return Promise.all(defs.map(async (def) => {
1478
+ const path = def.resolve(bootRoot, home);
1479
+ return { id: def.id, label: basename(path), path, exists: (await statConfigPath(path)).exists };
1480
+ }));
1481
+ };
1482
+ /** Build the wire row for one resolved profile: its dir state plus whatever auth is cached. */
1483
+ const agentProfileBody = async (profile) => ({
1484
+ id: profile.id,
1485
+ provider: profile.provider,
1486
+ label: profile.label,
1487
+ configDir: profile.configDir,
1488
+ path: profile.path,
1489
+ ...(await profileDirState(profile.provider, profile.path)),
1490
+ isDefault: profile.isDefault,
1491
+ // CACHED auth only — this listing must never pay a CLI spawn.
1492
+ //
1493
+ // Probing here cost a shell-out per provider PLUS one per extra account: ~0.7s with no extra
1494
+ // accounts and over 2s with a few, on every cold load, for a route whose real job (what
1495
+ // accounts exist) is a JSON read and a handful of stats. `GET /api/v1/health` already
1496
+ // established the rule — it serves whatever the cache holds and never pays a `gh` shell-out.
1497
+ // An absent `status` means "not determined yet", which the cockpit renders as Checking… and
1498
+ // then fills in from the per-account status route below.
1499
+ //
1500
+ // SPREAD, not `status: maybeUndefined`: hono would type the key as always-present while
1501
+ // `JSON.stringify` drops it, which is exactly the drift `contract-parity` catches (AGENTS.md
1502
+ // names this as one of the two recurring mismatches).
1503
+ ...(() => {
1504
+ const cached = profile.isDefault
1505
+ ? providerAuth.peekStatus()?.providers.find((row) => row.provider === profile.provider)
1506
+ : providerAuth.peekProfileStatus(profile.provider, profile.id);
1507
+ return cached ? { status: cached } : {};
1508
+ })(),
1509
+ files: await accountFiles(profile),
1510
+ });
1511
+ /**
1512
+ * Resolve `:id` to an account for the per-account reads below. Unlike `resolveWorkspaceProfile`
1513
+ * this accepts the reserved `default` for a NAMED provider, which these routes cannot infer — so
1514
+ * the id may be `default:<provider>` as well as a stored account id.
1515
+ */
1516
+ const accountById = async (id) => {
1517
+ const [head, tail] = id.split(':');
1518
+ if (head === DEFAULT_AGENT_ACCOUNT_ID) {
1519
+ const provider = PROVIDER_IDS.find((p) => p === tail);
1520
+ return provider ? defaultAgentProfile(provider) : null;
1521
+ }
1522
+ try {
1523
+ const stored = (await loadAgentAccounts()).accounts.find((a) => a.id === id);
1524
+ return stored ? resolveStoredProfile(stored) : null;
1525
+ }
1526
+ catch {
1527
+ return null;
1528
+ }
1529
+ };
1530
+ /** Validate a client-supplied config dir. Returns the error text, or null when it is usable. */
1531
+ const checkProfileDir = (configDir) => {
1532
+ if (CONTROL_CHARS_RE.test(configDir))
1533
+ return 'folder must not contain control characters';
1534
+ const expanded = expandTilde(configDir);
1535
+ // Absolute after expansion: a relative dir would resolve against whatever cwd the agent
1536
+ // happens to be spawned in, which for a task is a throwaway worktree. Through
1537
+ // `isAbsoluteConfigDir`, never a leading-`/` test — see its note: a string test refuses every
1538
+ // real Windows path, and this is the only gate the Add-account dialog has.
1539
+ if (!isAbsoluteConfigDir(expanded))
1540
+ return `folder must be an absolute path: ${configDir}`;
1541
+ return null;
1542
+ };
1543
+ /** Refuse a dir that is already some other account's (or the default's), compared through
1544
+ * `realpath` — two spellings of one directory would be two accounts silently sharing one
1545
+ * session store, and "which one am I logged into?" would stop having an answer. */
1546
+ const conflictingProfile = async (profiles, provider, path, exceptId) => {
1547
+ if (await sameProfileDir(path, defaultAgentProfile(provider).path)) {
1548
+ return 'that is already this agent\'s default folder';
1549
+ }
1550
+ for (const candidate of profiles) {
1551
+ if (candidate.provider !== provider || candidate.id === exceptId)
1552
+ continue;
1553
+ if (await sameProfileDir(path, expandTilde(candidate.configDir))) {
1554
+ return `that folder is already used by "${candidate.label || candidate.id}"`;
1555
+ }
1556
+ }
1557
+ return null;
1558
+ };
1559
+ const agentProfilesRoutes = new Hono()
1560
+ .get('/workspace/agent-profiles', async (c) => {
1561
+ const editable = capabilities().localHandoff;
1562
+ // Hosted mode withholds the listing entirely rather than serving it read-only: the paths
1563
+ // are the host disclosure, so an empty list is the only honest hosted answer.
1564
+ //
1565
+ // ONE body object, never a hosted `return` and a local `return`: two returns let hono
1566
+ // narrow `editable` to the literal `false`/`true` of each branch, and the contract's
1567
+ // honest `z.boolean()` then reads as wider than the route. Same shape as
1568
+ // `listAgentConfig`, which carries the same flag for the same reason.
1569
+ let store = defaultAgentAccountStore();
1570
+ if (editable) {
1571
+ try {
1572
+ store = await loadAgentAccounts();
1573
+ }
1574
+ catch {
1575
+ // an unreadable home degrades to "no extra accounts", never a failed request
1576
+ }
1577
+ }
1578
+ const profiles = editable
1579
+ ? await Promise.all(listAgentProfiles(store, PROVIDER_IDS).map(agentProfileBody))
1580
+ : [];
1581
+ return c.json({
1582
+ editable,
1583
+ profiles,
1584
+ profileCapableProviders: [...PROFILE_CAPABLE_PROVIDERS],
1585
+ // Which account each project uses, keyed by repo root. Served here rather than on the
1586
+ // project registry because it lives in the same file as the accounts it names.
1587
+ selections: editable ? store.selections : {},
1588
+ /** The machine-wide fallback, for repos that have chosen nothing. Withheld in hosted mode
1589
+ * on the same terms as the rest of this family. */
1590
+ defaults: editable ? store.defaults : {},
1591
+ });
1592
+ })
1593
+ .post('/workspace/agent-profiles', jsonZodValidator(() => createAgentProfileSchema), async (c) => {
1594
+ if (!capabilities().localHandoff)
1595
+ return c.json(hostedProfileRefusal, 409);
1596
+ const { provider, configDir, label } = c.req.valid('json');
1597
+ if (!supportsProfiles(provider)) {
1598
+ return c.json({ error: `${provider} cannot carry more than one account` }, 400);
1599
+ }
1600
+ const dirError = checkProfileDir(configDir);
1601
+ if (dirError)
1602
+ return c.json({ error: dirError }, 400);
1603
+ // Read-first, exactly like `POST /projects`: the duplicate check needs `realpath`, and the
1604
+ // merge-write mutator is deliberately SYNCHRONOUS so the read→rename window stays as small
1605
+ // as it is for every other writer of this file. Two processes adding the same folder in
1606
+ // that window would both win — a cosmetic duplicate, not a correctness problem, since the
1607
+ // schema's id dedupe is what keeps resolution deterministic.
1608
+ let existing = [];
1609
+ try {
1610
+ existing = (await loadAgentAccounts()).accounts;
1611
+ }
1612
+ catch {
1613
+ // unreadable store — the merge-write below reports the real failure
1614
+ }
1615
+ const conflict = await conflictingProfile(existing, provider, expandTilde(configDir));
1616
+ if (conflict !== null)
1617
+ return c.json({ error: conflict }, 409);
1618
+ let created;
1619
+ try {
1620
+ await mergeWriteAgentAccounts((store) => {
1621
+ const id = allocateAgentProfileId(label ?? configDir, store.accounts.map((a) => a.id));
1622
+ created = {
1623
+ id,
1624
+ provider,
1625
+ configDir,
1626
+ label: label?.trim() || id,
1627
+ addedAt: new Date().toISOString(),
1628
+ };
1629
+ store.accounts.push(created);
1630
+ });
1631
+ }
1632
+ catch (err) {
1633
+ return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
1634
+ }
1635
+ if (!created)
1636
+ return c.json({ error: 'account could not be saved' }, 500);
1637
+ // A brand-new account is the one thing the boot warm could not have known about, so learn it
1638
+ // now rather than only when something asks. Still off the response: the row is returned with
1639
+ // `status` absent (the listing's rule), the pane shows Checking…, and its follow-up request
1640
+ // joins this same in-flight probe.
1641
+ const account = resolveStoredProfile(created);
1642
+ const created201 = await agentProfileBody(account);
1643
+ void providerAuth
1644
+ .profileStatus(account.provider, { id: account.id, configDir: account.path })
1645
+ .catch(() => { });
1646
+ return c.json({ profile: created201 }, 201);
1647
+ })
1648
+ .patch('/workspace/agent-profiles/:id', paramZodValidator(z.object({ id: z.string() })), jsonZodValidator(() => updateAgentProfileSchema), async (c) => {
1649
+ if (!capabilities().localHandoff)
1650
+ return c.json(hostedProfileRefusal, 409);
1651
+ const id = c.req.param('id');
1652
+ const { label, configDir } = c.req.valid('json');
1653
+ if (configDir !== undefined) {
1654
+ const dirError = checkProfileDir(configDir);
1655
+ if (dirError)
1656
+ return c.json({ error: dirError }, 400);
1657
+ }
1658
+ // Read-first (see POST above, and `PATCH /projects`): a well-formed but unknown id must
1659
+ // 404 WITHOUT rewriting the config, and the duplicate check needs async `realpath`.
1660
+ let existing = [];
1661
+ try {
1662
+ existing = (await loadAgentAccounts()).accounts;
1663
+ }
1664
+ catch {
1665
+ // unreadable store — treated as unknown, like DELETE and PATCH /projects
1666
+ }
1667
+ const current = existing.find((a) => a.id === id);
1668
+ if (!current)
1669
+ return c.json({ error: `unknown account: ${id}` }, 404);
1670
+ if (configDir !== undefined) {
1671
+ const conflict = await conflictingProfile(existing, current.provider, expandTilde(configDir), id);
1672
+ if (conflict !== null)
1673
+ return c.json({ error: conflict }, 409);
1674
+ }
1675
+ let updated;
1676
+ try {
1677
+ await mergeWriteAgentAccounts((store) => {
1678
+ const entry = store.accounts.find((a) => a.id === id);
1679
+ if (!entry)
1680
+ return; // lost a race with a concurrent delete — answered below
1681
+ // Mutated in place so `.passthrough()` keys on the row survive.
1682
+ if (label !== undefined)
1683
+ entry.label = label.trim() || entry.id;
1684
+ if (configDir !== undefined)
1685
+ entry.configDir = configDir;
1686
+ updated = entry;
1687
+ });
1688
+ }
1689
+ catch (err) {
1690
+ return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
1691
+ }
1692
+ if (!updated)
1693
+ return c.json({ error: `unknown account: ${id}` }, 404);
1694
+ // The dir may have moved under a cached probe — drop THIS account's answer so the response
1695
+ // reports the new folder's state rather than the old one's, and leave every other account's
1696
+ // warm answer alone (it is still true). Then re-learn it in the background, so the server's
1697
+ // knowledge is complete again whether or not a cockpit is open to ask; the pane's own
1698
+ // request for this row joins the same in-flight probe rather than spawning a second.
1699
+ const repointed = resolveStoredProfile(updated);
1700
+ providerAuth.forgetProfileStatus(repointed.provider, repointed.id);
1701
+ const body = await agentProfileBody(repointed);
1702
+ void providerAuth
1703
+ .profileStatus(repointed.provider, { id: repointed.id, configDir: repointed.path })
1704
+ .catch(() => { });
1705
+ return c.json({ profile: body });
1706
+ })
1707
+ /**
1708
+ * One account's authentication state, probed for real.
1709
+ *
1710
+ * Separate from the listing because a probe shells out to an agent CLI: keeping it here lets
1711
+ * the pane paint immediately and fill each row in as its answer lands, instead of every cold
1712
+ * load blocking on N spawns. `refresh=1` drops this account's cached answer and re-probes, for
1713
+ * the "Check again" affordance — the cache itself holds a connected answer for minutes and an
1714
+ * unsettled one for a minute (`cacheTtlFor` in `core/provider-auth.ts`).
1715
+ */
1716
+ .get('/workspace/agent-profiles/:id/status', paramZodValidator(z.object({ id: z.string() })), queryZodValidator(z.object({ refresh: queryValue.refine((v) => v === undefined || v === '1') }), { message: 'refresh must be 1 when provided' }), async (c) => {
1717
+ if (!capabilities().localHandoff)
1718
+ return c.json(hostedProfileRefusal, 409);
1719
+ const account = await accountById(c.req.param('id'));
1720
+ if (!account)
1721
+ return c.json({ error: `unknown account: ${c.req.param('id')}` }, 404);
1722
+ const refresh = c.req.valid('query').refresh === '1';
1723
+ // The discovered account's row is the one `GET /api/v1/providers/status` owns, so it comes
1724
+ // from there — enablement included, which a bare probe does not know about.
1725
+ if (account.isDefault) {
1726
+ const all = await providerStatus(refresh ? { refresh: true } : undefined);
1727
+ const row = all.providers.find((candidate) => candidate.provider === account.provider);
1728
+ return c.json({ status: row ?? { provider: account.provider, status: 'unknown' } });
1729
+ }
1730
+ // "Check again" re-probes THIS account only — the other accounts' warm answers are not
1731
+ // invalidated by asking about this one.
1732
+ if (refresh)
1733
+ providerAuth.forgetProfileStatus(account.provider, account.id);
1734
+ return c.json({
1735
+ status: await providerAuth.profileStatus(account.provider, {
1736
+ id: account.id,
1737
+ configDir: account.path,
1738
+ }),
1739
+ });
1740
+ })
1741
+ /**
1742
+ * Who this account is signed in AS — the pane's "Show details".
1743
+ *
1744
+ * A separate, on-demand route rather than a field on the listing, and that is what makes
1745
+ * "hidden by default" real: an email carried by the listing would already be in the response,
1746
+ * the query cache and devtools, whatever the UI chose to render. `provider-auth.ts` keeps
1747
+ * identity out of ITS boundary on purpose; this is the deliberate, local-only, opt-in
1748
+ * exception — not a widening of that rule. Never logged, never persisted.
1749
+ */
1750
+ .get('/workspace/agent-profiles/:id/details', paramZodValidator(z.object({ id: z.string() })), async (c) => {
1751
+ if (!capabilities().localHandoff)
1752
+ return c.json(hostedProfileRefusal, 409);
1753
+ const account = await accountById(c.req.param('id'));
1754
+ if (!account)
1755
+ return c.json({ error: `unknown account: ${c.req.param('id')}` }, 404);
1756
+ return c.json(await readAccountIdentity(account.provider, account.path));
1757
+ })
1758
+ /**
1759
+ * Open one of this account's own config files — or its folder — in a local app.
1760
+ *
1761
+ * `file` is a catalog ID from the account's own `files`, never a path: the client cannot name a
1762
+ * location, so there is no traversal surface here at all (the same rule
1763
+ * `/api/v1/agent-config/:id` follows). `folder` is the one extra keyword, and it resolves to
1764
+ * the account's dir rather than anything the caller spelled.
1765
+ */
1766
+ .post('/workspace/agent-profiles/:id/open', paramZodValidator(z.object({ id: z.string() })), jsonZodValidator(() => openAgentAccountFileSchema), async (c) => {
1767
+ if (!capabilities().localHandoff)
1768
+ return c.json(hostedProfileRefusal, 409);
1769
+ const account = await accountById(c.req.param('id'));
1770
+ if (!account)
1771
+ return c.json({ error: `unknown account: ${c.req.param('id')}` }, 404);
1772
+ const { file, target } = c.req.valid('json');
1773
+ let path;
1774
+ if (file === 'folder') {
1775
+ path = account.path;
1776
+ }
1777
+ else {
1778
+ const match = (await accountFiles(account)).find((f) => f.id === file);
1779
+ if (!match)
1780
+ return c.json({ error: `unknown file: ${file}` }, 404);
1781
+ path = match.path;
1782
+ }
1783
+ // A file the agent has not written yet has nothing to open; say so rather than hand the OS
1784
+ // a missing path and report success.
1785
+ if (!(await statConfigPath(path)).exists && file !== 'folder') {
1786
+ return c.json({ error: `this account has no ${basename(path)} yet` }, 409);
1787
+ }
1788
+ // `target` names a detected app; absent means the OS default handler. Either way the PATH
1789
+ // came from the catalog, so an editor is only ever pointed inside this account's folder.
1790
+ //
1791
+ // Which targets APPLY is checked here rather than left to the UI, because two of them are
1792
+ // actively wrong rather than merely useless: `terminal` runs `cd <path>`, which fails on a
1793
+ // file, and a `cli:<runner>` handoff would start an agent session inside the config folder.
1794
+ // A route is a surface of its own; it refuses what it cannot do correctly.
1795
+ if (target !== undefined) {
1796
+ if (agentCliRunner(target) !== null) {
1797
+ return c.json({ error: 'agent CLIs open a task worktree, not a config folder' }, 400);
1798
+ }
1799
+ if (target === 'terminal' && file !== 'folder') {
1800
+ return c.json({ error: 'a terminal opens a folder, not a file' }, 400);
1801
+ }
1802
+ if (!detectOpenTargets().some((candidate) => candidate.id === target)) {
1803
+ return c.json({ error: `no such app on this machine: ${target}` }, 400);
1804
+ }
1805
+ }
1806
+ const opened = target === undefined
1807
+ ? await openFile(path)
1808
+ : await openInApp(target, path);
1809
+ if (!opened)
1810
+ return c.json({ error: `could not open ${basename(path)}`, path }, 409);
1811
+ return c.json({ opened: true, path });
1812
+ })
1813
+ // Which account a PROJECT uses. On the accounts family rather than `PATCH /api/v1/projects`
1814
+ // because the selection is stored beside the accounts it names — one file, one atomic write,
1815
+ // and nothing about it can be dropped by a cezar version that never heard of accounts.
1816
+ .put('/workspace/agent-profiles/selection', jsonZodValidator(() => selectAgentProfileSchema), async (c) => {
1817
+ if (!capabilities().localHandoff)
1818
+ return c.json(hostedProfileRefusal, 409);
1819
+ const { projectId, provider, profileId } = c.req.valid('json');
1820
+ // `null` writes the MACHINE-WIDE default instead of one repo's selection: the account any
1821
+ // repo that has chosen nothing uses, so a second login is set up once rather than per
1822
+ // checkout. No project to resolve, and therefore no 404 path.
1823
+ let root = null;
1824
+ if (projectId !== null) {
1825
+ const resolvedId = projectId === 'default' ? await resolveBootProject() : projectId;
1826
+ // Keyed by repo ROOT, so the selection survives the registry being rebuilt and needs no
1827
+ // cross-reference into config.json. An unknown project is a 404 rather than an orphan
1828
+ // entry nobody will ever read.
1829
+ root = await projectRootFor(resolvedId);
1830
+ if (root === null)
1831
+ return c.json({ error: `unknown project: ${projectId}` }, 404);
1832
+ }
1833
+ // A user naming an account that does not exist gets told so — the opposite of how RUN
1834
+ // resolution treats a dangling stored id, and deliberately: a run has no better answer
1835
+ // than the default, a person does.
1836
+ if (profileId !== null && profileId !== DEFAULT_AGENT_ACCOUNT_ID) {
1837
+ const account = await resolveWorkspaceProfile(provider, profileId);
1838
+ if ('error' in account)
1839
+ return c.json({ error: account.error }, 400);
1840
+ }
1841
+ let store;
1842
+ try {
1843
+ store = await mergeWriteAgentAccounts((current) => {
1844
+ // One rule, two targets: the machine default is the same per-provider shape as a repo's
1845
+ // selection, so it clears the same way rather than growing its own spelling.
1846
+ const selection = root === null ? current.defaults : current.selections[root] ?? {};
1847
+ // `null` and the reserved `default` both mean "back to the discovered account", which
1848
+ // is stored as ABSENCE — the default id is never written to the file.
1849
+ if (profileId === null || profileId === DEFAULT_AGENT_ACCOUNT_ID)
1850
+ delete selection[provider];
1851
+ else
1852
+ selection[provider] = profileId;
1853
+ // The machine default keeps an emptied object where a repo selection is deleted, and
1854
+ // that asymmetry is the schema's, not an oversight: `defaults` is one FIXED field with
1855
+ // `.default(() => ({}))`, so `mergeWriteAgentAccounts` re-materializes it on the next
1856
+ // write no matter what this one omits (verified). `selections` is a growing MAP, where
1857
+ // an emptied entry is a row per repo ever touched that says nothing. The rule stated
1858
+ // for `agentDefaults.models` — "absence is the same answer" — applies there because
1859
+ // that key is `.optional()`, so deleting it actually sticks.
1860
+ if (root === null)
1861
+ current.defaults = selection;
1862
+ else if (Object.keys(selection).length === 0)
1863
+ delete current.selections[root];
1864
+ else
1865
+ current.selections[root] = selection;
1866
+ });
1867
+ }
1868
+ catch (err) {
1869
+ return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
1870
+ }
1871
+ return c.json({ selections: store.selections, defaults: store.defaults });
1872
+ })
1873
+ .delete('/workspace/agent-profiles/:id', paramZodValidator(z.object({ id: z.string() })), async (c) => {
1874
+ if (!capabilities().localHandoff)
1875
+ return c.json(hostedProfileRefusal, 409);
1876
+ const id = c.req.param('id');
1877
+ let removed = false;
1878
+ // Captured inside the mutator, because after the write there is nothing left to ask which
1879
+ // provider this account belonged to — and the eviction below is keyed by it.
1880
+ let removedProvider;
1881
+ try {
1882
+ await mergeWriteAgentAccounts((store) => {
1883
+ const before = store.accounts.length;
1884
+ removedProvider = store.accounts.find((a) => a.id === id)?.provider;
1885
+ store.accounts = store.accounts.filter((a) => a.id !== id);
1886
+ removed = store.accounts.length < before;
1887
+ if (!removed)
1888
+ return;
1889
+ // Scrub every reference IN THE SAME MUTATOR — the reason selections share this file.
1890
+ // A two-call delete-then-scrub can be observed mid-way by another cezar process on
1891
+ // this machine, which would then resolve a dangling id; harmless today (it degrades
1892
+ // to the default) but only by luck.
1893
+ for (const [root, selection] of Object.entries(store.selections)) {
1894
+ for (const key of Object.keys(selection)) {
1895
+ if (selection[key] === id)
1896
+ delete selection[key];
1897
+ }
1898
+ if (Object.keys(selection).length === 0)
1899
+ delete store.selections[root];
1900
+ }
1901
+ });
1902
+ }
1903
+ catch (err) {
1904
+ return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
1905
+ }
1906
+ if (!removed)
1907
+ return c.json({ error: `unknown account: ${id}` }, 404);
1908
+ // Only this account's answer: it is about to stop existing, and holding it would let a
1909
+ // re-added account with the same id read the deleted one's state.
1910
+ providerAuth.forgetProfileStatus(removedProvider, id);
1911
+ return c.json({ removed: true, id });
1912
+ });
917
1913
  // ---- workspace projects (multi-project spec) -----------------------------
918
1914
  // The registered-project list for the cockpit sidebar. Same-origin (unlike
919
1915
  // health), so absolute `root`s are fine here. `listProjects()` TTL-caches
@@ -939,7 +1935,9 @@ export function createApp(deps) {
939
1935
  return defaultWorkspaceConfig().browseRoot;
940
1936
  }
941
1937
  };
942
- app.get('/api/projects', async (c) => {
1938
+ // ---- chained family: project registry (workspace-level) ----
1939
+ const projectsRoutes = new Hono()
1940
+ .get('/projects', async (c) => {
943
1941
  let projects = [];
944
1942
  let projectsDir = defaultWorkspaceConfig().projectsDir;
945
1943
  try {
@@ -958,38 +1956,196 @@ export function createApp(deps) {
958
1956
  projectsDir,
959
1957
  };
960
1958
  return c.json(body);
961
- });
962
- // Register an existing folder (multi-project spec, "Add project" — the
963
- // folder-browser dialog's commit step, step 4.2). Workspace-level like its
964
- // GET twin. Everything here is a guard; the registry write itself is one
965
- // idempotent `registerProject` call.
966
- const registerProjectSchema = z.object({
967
- root: z.string().trim().min(1).max(4096),
968
- });
969
- /**
970
- * The register-a-folder half of `POST /api/projects`, factored out so the
971
- * checkout route (step 4.3) commits its fresh clone through the SAME guards
972
- * and the same `project-added` emission rather than a second copy of them.
973
- * Returns the status + body for the caller to answer with.
974
- */
975
- const registerFolder = async (spelled, source) => {
1959
+ })
1960
+ .post('/projects', jsonZodValidator(() => registerProjectSchema, { message: 'root must be a non-empty path' }), async (c) => {
1961
+ const parsed = { data: c.req.valid('json') };
1962
+ const registered = await registerFolder(parsed.data.root, 'local');
1963
+ if (registered.status !== 200)
1964
+ return c.json(registered.body, registered.status);
1965
+ return c.json(registered.body, 200);
1966
+ })
1967
+ .delete('/projects/:projectId', async (c) => {
976
1968
  if (capabilities().singleProject) {
977
- return { status: 409, body: singleProjectRefusal('adding projects') };
1969
+ return c.json(singleProjectRefusal('removing projects'), 409);
978
1970
  }
979
- // `~` is expanded for the same reason `/api/fs/browse` expands it: the
980
- // dialog hands back absolute paths, but a hand-written body (curl, a
981
- // future CLI) spells home the way a shell does.
982
- const requested = expandTilde(spelled);
983
- if (!requested.startsWith('/')) {
984
- return {
985
- status: 400,
986
- body: { error: `not a folder: ${spelled} is not an absolute path` },
987
- };
1971
+ const raw = c.req.param('projectId');
1972
+ // Same gate the scoped-route resolver applies, and the same 404 wording —
1973
+ // a malformed id is an unknown project, not a validation essay.
1974
+ if (!projectIdSchema.safeParse(raw).success) {
1975
+ return c.json({ error: `unknown project: ${raw}` }, 404);
988
1976
  }
989
- // Hosted mode: the same root the picker is narrowed to, re-checked — see
990
- // `isInsideBrowseRoot`. Local mode deliberately has NO containment: a
991
- // project under `/srv/code` is a normal local setup and `cezar serve`
992
- // registers it today.
1977
+ const bootId = await resolveBootProject();
1978
+ // `default` is the boot alias everywhere else in the API; honour it here
1979
+ // too rather than 404ing a spelling the cockpit is allowed to use.
1980
+ const id = raw === 'default' ? bootId : raw;
1981
+ let entry;
1982
+ try {
1983
+ entry = (await loadWorkspaceConfig()).projects.find((p) => p.id === id);
1984
+ }
1985
+ catch {
1986
+ // unreadable workspace — there is nothing to remove, and saying so is
1987
+ // more useful than a 500 the user cannot act on
1988
+ }
1989
+ if (!entry)
1990
+ return c.json({ error: `unknown project: ${id}` }, 404);
1991
+ // The boot project is refused, not removed: `cezar serve` re-registers the
1992
+ // repo it was started in on every boot, so "removing" it would undo itself
1993
+ // at the next restart while breaking this session's sidebar in the
1994
+ // meantime. The pane disables the button and says the same thing.
1995
+ if (id === bootId) {
1996
+ return c.json({
1997
+ error: `cezar is serving ${entry.name} right now — it re-registers itself at every start, so it cannot be removed from here`,
1998
+ }, 409);
1999
+ }
2000
+ const active = activeRunCount(id);
2001
+ if (active > 0) {
2002
+ return c.json({
2003
+ error: `${entry.name} has ${active} running task${active === 1 ? '' : 's'} — cancel or finish ${active === 1 ? 'it' : 'them'} before removing the project`,
2004
+ runningTasks: active,
2005
+ }, 409);
2006
+ }
2007
+ let removed;
2008
+ try {
2009
+ removed = await removeProject(id);
2010
+ }
2011
+ catch (err) {
2012
+ // e.g. a read-only home — nothing was persisted (atomic tmp+rename).
2013
+ return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
2014
+ }
2015
+ // Lost a race with another writer (or another cezar process): the entry is
2016
+ // gone, which is what the caller wanted, but say it honestly.
2017
+ if (!removed)
2018
+ return c.json({ error: `unknown project: ${id}` }, 404);
2019
+ // In-process handles for a project no route can reach any more: store
2020
+ // closed (index flushed), manager's timers and usage subscription dropped.
2021
+ contexts.dispose(id);
2022
+ workspaceEvents.emit('project-removed', { id });
2023
+ const body = { removed: true, id };
2024
+ return c.json(body);
2025
+ })
2026
+ .patch('/projects/:projectId', jsonZodValidator(() => updateProjectSchema), async (c) => {
2027
+ if (capabilities().singleProject) {
2028
+ return c.json(singleProjectRefusal('editing projects'), 409);
2029
+ }
2030
+ const raw = c.req.param('projectId');
2031
+ // Same gate + 404 wording as DELETE: a malformed id is an unknown project.
2032
+ if (!projectIdSchema.safeParse(raw).success) {
2033
+ return c.json({ error: `unknown project: ${raw}` }, 404);
2034
+ }
2035
+ const parsed = { data: c.req.valid('json') };
2036
+ // `default` is the boot alias the cockpit is allowed to use everywhere else.
2037
+ const id = raw === 'default' ? await resolveBootProject() : raw;
2038
+ const { maxParallel } = parsed.data;
2039
+ // Read-first (mirroring DELETE, server.ts:1252-1258): a well-formed but
2040
+ // unknown id must 404 WITHOUT rewriting the config — otherwise it would both
2041
+ // do a needless full-config tmp+rename and, on a read-only home, surface the
2042
+ // write failure as a 500 where the honest answer is 404.
2043
+ let known = false;
2044
+ try {
2045
+ known = (await loadWorkspaceConfig()).projects.some((p) => p.id === id);
2046
+ }
2047
+ catch {
2048
+ // unreadable workspace — treat as unknown; the read-only case answers 404,
2049
+ // not a 500 the caller cannot act on (same reasoning as DELETE).
2050
+ }
2051
+ if (!known)
2052
+ return c.json({ error: `unknown project: ${id}` }, 404);
2053
+ let updated;
2054
+ try {
2055
+ await mergeWriteWorkspaceConfig((config) => {
2056
+ const entry = config.projects.find((p) => p.id === id);
2057
+ if (!entry)
2058
+ return; // lost a race with a concurrent remove — answered below
2059
+ // null clears the override; a number sets it. Mutated in place so
2060
+ // `.passthrough()` keys on the entry survive.
2061
+ if (maxParallel === null)
2062
+ delete entry.maxParallel;
2063
+ else
2064
+ entry.maxParallel = maxParallel;
2065
+ updated = entry;
2066
+ });
2067
+ }
2068
+ catch (err) {
2069
+ // e.g. a read-only home — nothing was persisted (atomic tmp+rename).
2070
+ return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
2071
+ }
2072
+ // Raced with a concurrent removal between the read and the write.
2073
+ if (!updated)
2074
+ return c.json({ error: `unknown project: ${id}` }, 404);
2075
+ // The new ceiling takes effect WITHOUT a restart: refresh the shared
2076
+ // semaphore's snapshot and pump every manager — the same live-apply hook
2077
+ // `PUT /api/workspace/config` fires for a workspace-cap change.
2078
+ await deps.semaphore?.refresh();
2079
+ const body = {
2080
+ project: { ...updated, ...(await probeProjectStatus(updated.root)) },
2081
+ };
2082
+ return c.json(body);
2083
+ })
2084
+ .post('/projects/checkout', jsonZodValidator(() => checkoutSchema, { message: 'url must be a GitHub repository' }), async (c) => {
2085
+ if (capabilities().singleProject) {
2086
+ return c.json(singleProjectRefusal('adding projects'), 409);
2087
+ }
2088
+ const parsed = { data: c.req.valid('json') };
2089
+ const { url, name, checkoutId } = parsed.data;
2090
+ const result = await checkoutRepo({
2091
+ url,
2092
+ name,
2093
+ checkoutId,
2094
+ projectsDir: expandTilde(await workspaceProjectsDir()),
2095
+ onProgress: (event) => workspaceEvents.emit('checkout-progress', event),
2096
+ // A closed dialog / navigated-away tab aborts the request; the clone is
2097
+ // killed and its partial directory removed rather than left running.
2098
+ signal: c.req.raw.signal,
2099
+ ...(deps.cloneRunner ? { run: deps.cloneRunner } : {}),
2100
+ });
2101
+ if (!result.ok) {
2102
+ // `reason` rides along on the 503 (`gh` unavailable) — the spec's
2103
+ // `{ error, reason }` degradation, mirroring the GitHub pane.
2104
+ return c.json('reason' in result ? { error: result.error, reason: result.reason } : { error: result.error }, result.status);
2105
+ }
2106
+ const registered = await registerFolder(result.target, 'checkout');
2107
+ if (registered.status !== 200) {
2108
+ // The clone SUCCEEDED and its files are legitimately the user's, so this
2109
+ // path deliberately does NOT clean up — an unregisterable checkout is a
2110
+ // registry problem, not a reason to delete a repo we just fetched. Say
2111
+ // where it is so they can register it by hand.
2112
+ const { body } = registered;
2113
+ const error = 'error' in body && body.error ? body.error : 'could not register the checkout';
2114
+ return c.json({ error: `${error} (the clone is at ${result.target})` }, registered.status);
2115
+ }
2116
+ return c.json(registered.body, 200);
2117
+ });
2118
+ // Register an existing folder (multi-project spec, "Add project" — the
2119
+ // folder-browser dialog's commit step, step 4.2). Workspace-level like its
2120
+ // GET twin. Everything here is a guard; the registry write itself is one
2121
+ // idempotent `registerProject` call.
2122
+ const registerProjectSchema = z.object({
2123
+ root: z.string().trim().min(1).max(4096),
2124
+ });
2125
+ /**
2126
+ * The register-a-folder half of `POST /api/projects`, factored out so the
2127
+ * checkout route (step 4.3) commits its fresh clone through the SAME guards
2128
+ * and the same `project-added` emission rather than a second copy of them.
2129
+ * Returns the status + body for the caller to answer with.
2130
+ */
2131
+ const registerFolder = async (spelled, source) => {
2132
+ if (capabilities().singleProject) {
2133
+ return { status: 409, body: singleProjectRefusal('adding projects') };
2134
+ }
2135
+ // `~` is expanded for the same reason `/api/fs/browse` expands it: the
2136
+ // dialog hands back absolute paths, but a hand-written body (curl, a
2137
+ // future CLI) spells home the way a shell does.
2138
+ const requested = expandTilde(spelled);
2139
+ if (!requested.startsWith('/')) {
2140
+ return {
2141
+ status: 400,
2142
+ body: { error: `not a folder: ${spelled} is not an absolute path` },
2143
+ };
2144
+ }
2145
+ // Hosted mode: the same root the picker is narrowed to, re-checked — see
2146
+ // `isInsideBrowseRoot`. Local mode deliberately has NO containment: a
2147
+ // project under `/srv/code` is a normal local setup and `cezar serve`
2148
+ // registers it today.
993
2149
  //
994
2150
  // Containment is asked in two halves, around the stat, and the split is
995
2151
  // deliberate.
@@ -1079,13 +2235,6 @@ export function createApp(deps) {
1079
2235
  workspaceEvents.emit('project-added', { project });
1080
2236
  return { status: 200, body: { project } };
1081
2237
  };
1082
- app.post('/api/projects', async (c) => {
1083
- const parsed = registerProjectSchema.safeParse(await c.req.json().catch(() => null));
1084
- if (!parsed.success)
1085
- return c.json({ error: 'root must be a non-empty path' }, 400);
1086
- const { status, body } = await registerFolder(parsed.data.root, 'local');
1087
- return c.json(body, status);
1088
- });
1089
2238
  // Deregister a project (multi-project spec, step 4.4 — Settings → Projects,
1090
2239
  // the per-row "Remove"). READ THIS BEFORE TOUCHING THE HANDLER: the ONLY
1091
2240
  // durable effect allowed here is dropping one entry from
@@ -1120,64 +2269,59 @@ export function createApp(deps) {
1120
2269
  return 0;
1121
2270
  return ctx.store.listRuns().filter((run) => ACTIVE_RUN_STATUSES.has(run.status)).length;
1122
2271
  };
1123
- app.delete('/api/projects/:projectId', async (c) => {
1124
- if (capabilities().singleProject) {
1125
- return c.json(singleProjectRefusal('removing projects'), 409);
1126
- }
1127
- const raw = c.req.param('projectId');
1128
- // Same gate the scoped-route resolver applies, and the same 404 wording —
1129
- // a malformed id is an unknown project, not a validation essay.
1130
- if (!projectIdSchema.safeParse(raw).success) {
1131
- return c.json({ error: `unknown project: ${raw}` }, 404);
1132
- }
2272
+ // Workspace-level by design: update state spans project and global installs,
2273
+ // but the selected registered project supplies the safe, server-owned cwd.
2274
+ const skillsUpdateInputSchema = z.object({ projectId: projectIdSchema }).strict();
2275
+ const resolveSkillsUpdateRoot = async (raw) => {
2276
+ if (!projectIdSchema.safeParse(raw).success)
2277
+ return { status: 404, error: `unknown project: ${raw}` };
1133
2278
  const bootId = await resolveBootProject();
1134
- // `default` is the boot alias everywhere else in the API; honour it here
1135
- // too rather than 404ing a spelling the cockpit is allowed to use.
1136
- const id = raw === 'default' ? bootId : raw;
1137
- let entry;
1138
- try {
1139
- entry = (await loadWorkspaceConfig()).projects.find((p) => p.id === id);
1140
- }
1141
- catch {
1142
- // unreadable workspace — there is nothing to remove, and saying so is
1143
- // more useful than a 500 the user cannot act on
1144
- }
1145
- if (!entry)
1146
- return c.json({ error: `unknown project: ${id}` }, 404);
1147
- // The boot project is refused, not removed: `cezar serve` re-registers the
1148
- // repo it was started in on every boot, so "removing" it would undo itself
1149
- // at the next restart while breaking this session's sidebar in the
1150
- // meantime. The pane disables the button and says the same thing.
1151
- if (id === bootId) {
1152
- return c.json({
1153
- error: `cezar is serving ${entry.name} right now — it re-registers itself at every start, so it cannot be removed from here`,
1154
- }, 409);
2279
+ if (raw === 'default' || raw === bootId)
2280
+ return { root: bootRoot };
2281
+ const project = (await loadWorkspaceConfig()).projects.find((entry) => entry.id === raw);
2282
+ if (!project)
2283
+ return { status: 404, error: `unknown project: ${raw}` };
2284
+ if ((await probeProjectStatus(project.root)).status === 'missing') {
2285
+ return { status: 409, error: `project folder not found: ${raw}` };
1155
2286
  }
1156
- const active = activeRunCount(id);
1157
- if (active > 0) {
1158
- return c.json({
1159
- error: `${entry.name} has ${active} running task${active === 1 ? '' : 's'} — cancel or finish ${active === 1 ? 'it' : 'them'} before removing the project`,
1160
- runningTasks: active,
1161
- }, 409);
1162
- }
1163
- let removed;
2287
+ return { root: project.root };
2288
+ };
2289
+ const skillsUpdateResponse = async (state) => {
2290
+ const config = await loadWorkspaceConfig();
2291
+ return { ...state, autoUpdateEnabled: effectiveSkillsAutoUpdate(config), inherited: config.skillsAutoUpdate === undefined };
2292
+ };
2293
+ // ---- chained family: skills updates (workspace-level) ----
2294
+ const skillsUpdateRoutes = new Hono()
2295
+ .get('/workspace/skills-update', queryZodValidator(skillsUpdateInputSchema, { message: 'projectId is required' }), async (c) => {
2296
+ const parsed = { data: c.req.valid('query') };
2297
+ const resolved = await resolveSkillsUpdateRoot(parsed.data.projectId);
2298
+ if ('error' in resolved)
2299
+ return c.json({ error: resolved.error }, resolved.status);
2300
+ const state = skillsUpdate.snapshot(resolved.root);
2301
+ void skillsUpdate.check(resolved.root).catch(() => { });
2302
+ return c.json(await skillsUpdateResponse(state));
2303
+ })
2304
+ .post('/workspace/skills-update/check', jsonZodValidator(skillsUpdateInputSchema, { message: 'body must contain only projectId' }), async (c) => {
2305
+ const parsed = { data: c.req.valid('json') };
2306
+ const resolved = await resolveSkillsUpdateRoot(parsed.data.projectId);
2307
+ if ('error' in resolved)
2308
+ return c.json({ error: resolved.error }, resolved.status);
2309
+ return c.json(await skillsUpdateResponse(await skillsUpdate.check(resolved.root, true)));
2310
+ })
2311
+ .post('/workspace/skills-update/apply', jsonZodValidator(skillsUpdateInputSchema, { message: 'body must contain only projectId' }), async (c) => {
2312
+ const parsed = { data: c.req.valid('json') };
2313
+ const resolved = await resolveSkillsUpdateRoot(parsed.data.projectId);
2314
+ if ('error' in resolved)
2315
+ return c.json({ error: resolved.error }, resolved.status);
1164
2316
  try {
1165
- removed = await removeProject(id);
2317
+ return c.json(await skillsUpdateResponse(await skillsUpdate.update(resolved.root, true)));
1166
2318
  }
1167
- catch (err) {
1168
- // e.g. a read-only home — nothing was persisted (atomic tmp+rename).
1169
- return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
2319
+ catch (error) {
2320
+ if (error instanceof SkillsUpdateConflictError) {
2321
+ return c.json({ error: 'another skills update operation is running', state: await skillsUpdateResponse(skillsUpdate.snapshot(resolved.root)) }, 409);
2322
+ }
2323
+ throw error;
1170
2324
  }
1171
- // Lost a race with another writer (or another cezar process): the entry is
1172
- // gone, which is what the caller wanted, but say it honestly.
1173
- if (!removed)
1174
- return c.json({ error: `unknown project: ${id}` }, 404);
1175
- // In-process handles for a project no route can reach any more: store
1176
- // closed (index flushed), manager's timers and usage subscription dropped.
1177
- contexts.dispose(id);
1178
- workspaceEvents.emit('project-removed', { id });
1179
- const body = { removed: true, id };
1180
- return c.json(body);
1181
2325
  });
1182
2326
  // Edit one field of an existing registry entry (spec
1183
2327
  // 2026-07-22-per-project-concurrency): the per-project concurrency ceiling.
@@ -1187,69 +2331,12 @@ export function createApp(deps) {
1187
2331
  // cap". Bounds mirror `workspaceProjectSchema` (config.ts) exactly, so a
1188
2332
  // value this route accepts can never be degraded away by the next load's
1189
2333
  // `.catch`.
1190
- const updateProjectSchema = z.object({
1191
- maxParallel: z.number().int().min(1).max(16).nullable(),
1192
- });
1193
- app.patch('/api/projects/:projectId', async (c) => {
1194
- if (capabilities().singleProject) {
1195
- return c.json(singleProjectRefusal('editing projects'), 409);
1196
- }
1197
- const raw = c.req.param('projectId');
1198
- // Same gate + 404 wording as DELETE: a malformed id is an unknown project.
1199
- if (!projectIdSchema.safeParse(raw).success) {
1200
- return c.json({ error: `unknown project: ${raw}` }, 404);
1201
- }
1202
- const parsed = updateProjectSchema.safeParse(await c.req.json().catch(() => null));
1203
- if (!parsed.success) {
1204
- return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
1205
- }
1206
- // `default` is the boot alias the cockpit is allowed to use everywhere else.
1207
- const id = raw === 'default' ? await resolveBootProject() : raw;
1208
- const { maxParallel } = parsed.data;
1209
- // Read-first (mirroring DELETE, server.ts:1252-1258): a well-formed but
1210
- // unknown id must 404 WITHOUT rewriting the config — otherwise it would both
1211
- // do a needless full-config tmp+rename and, on a read-only home, surface the
1212
- // write failure as a 500 where the honest answer is 404.
1213
- let known = false;
1214
- try {
1215
- known = (await loadWorkspaceConfig()).projects.some((p) => p.id === id);
1216
- }
1217
- catch {
1218
- // unreadable workspace — treat as unknown; the read-only case answers 404,
1219
- // not a 500 the caller cannot act on (same reasoning as DELETE).
1220
- }
1221
- if (!known)
1222
- return c.json({ error: `unknown project: ${id}` }, 404);
1223
- let updated;
1224
- try {
1225
- await mergeWriteWorkspaceConfig((config) => {
1226
- const entry = config.projects.find((p) => p.id === id);
1227
- if (!entry)
1228
- return; // lost a race with a concurrent remove — answered below
1229
- // null clears the override; a number sets it. Mutated in place so
1230
- // `.passthrough()` keys on the entry survive.
1231
- if (maxParallel === null)
1232
- delete entry.maxParallel;
1233
- else
1234
- entry.maxParallel = maxParallel;
1235
- updated = entry;
1236
- });
1237
- }
1238
- catch (err) {
1239
- // e.g. a read-only home — nothing was persisted (atomic tmp+rename).
1240
- return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
1241
- }
1242
- // Raced with a concurrent removal between the read and the write.
1243
- if (!updated)
1244
- return c.json({ error: `unknown project: ${id}` }, 404);
1245
- // The new ceiling takes effect WITHOUT a restart: refresh the shared
1246
- // semaphore's snapshot and pump every manager — the same live-apply hook
1247
- // `PUT /api/workspace/config` fires for a workspace-cap change.
1248
- await deps.semaphore?.refresh();
1249
- const body = {
1250
- project: { ...updated, ...(await probeProjectStatus(updated.root)) },
1251
- };
1252
- return c.json(body);
2334
+ //
2335
+ // Deliberately NOT the home of the agent-account selection: that lives in
2336
+ // `~/.cezar/agent-accounts.json` beside the accounts it names, so a cezar version that has
2337
+ // never heard of accounts cannot drop it (see workspace/agent-accounts.ts).
2338
+ const updateProjectSchema = z.object({
2339
+ maxParallel: z.number().int().min(1).max(16).nullable(),
1253
2340
  });
1254
2341
  // ---- GUI clone (multi-project spec, step 4.3) ----------------------------
1255
2342
  // "Add project → Clone from GitHub": clone into the checkout root, then
@@ -1267,41 +2354,6 @@ export function createApp(deps) {
1267
2354
  name: z.string().trim().max(128).optional(),
1268
2355
  checkoutId: z.string().trim().max(128).optional(),
1269
2356
  });
1270
- app.post('/api/projects/checkout', async (c) => {
1271
- if (capabilities().singleProject) {
1272
- return c.json(singleProjectRefusal('adding projects'), 409);
1273
- }
1274
- const parsed = checkoutSchema.safeParse(await c.req.json().catch(() => null));
1275
- if (!parsed.success)
1276
- return c.json({ error: 'url must be a GitHub repository' }, 400);
1277
- const { url, name, checkoutId } = parsed.data;
1278
- const result = await checkoutRepo({
1279
- url,
1280
- name,
1281
- checkoutId,
1282
- projectsDir: expandTilde(await workspaceProjectsDir()),
1283
- onProgress: (event) => workspaceEvents.emit('checkout-progress', event),
1284
- // A closed dialog / navigated-away tab aborts the request; the clone is
1285
- // killed and its partial directory removed rather than left running.
1286
- signal: c.req.raw.signal,
1287
- ...(deps.cloneRunner ? { run: deps.cloneRunner } : {}),
1288
- });
1289
- if (!result.ok) {
1290
- // `reason` rides along on the 503 (`gh` unavailable) — the spec's
1291
- // `{ error, reason }` degradation, mirroring the GitHub pane.
1292
- return c.json('reason' in result ? { error: result.error, reason: result.reason } : { error: result.error }, result.status);
1293
- }
1294
- const { status, body } = await registerFolder(result.target, 'checkout');
1295
- if (status !== 200) {
1296
- // The clone SUCCEEDED and its files are legitimately the user's, so this
1297
- // path deliberately does NOT clean up — an unregisterable checkout is a
1298
- // registry problem, not a reason to delete a repo we just fetched. Say
1299
- // where it is so they can register it by hand.
1300
- const error = 'error' in body && body.error ? body.error : 'could not register the checkout';
1301
- return c.json({ error: `${error} (the clone is at ${result.target})` }, status);
1302
- }
1303
- return c.json(body, 200);
1304
- });
1305
2357
  // ---- workspace settings (multi-project spec, step 2.7) -------------------
1306
2358
  // WORKSPACE-level routes: single-mount (never mirrored under /api/p/),
1307
2359
  // same-origin. The config routes carry the settings UI's slice of
@@ -1311,33 +2363,40 @@ export function createApp(deps) {
1311
2363
  const workspaceConfigBody = (config) => ({
1312
2364
  browseRoot: config.browseRoot,
1313
2365
  projectsDir: config.projectsDir,
2366
+ skillsAutoUpdate: config.skillsAutoUpdate ?? null,
2367
+ effectiveSkillsAutoUpdate: effectiveSkillsAutoUpdate(config),
2368
+ composerDefaults: {
2369
+ autonomous: config.composerDefaults.autonomous ?? null,
2370
+ worktree: config.composerDefaults.worktree ?? null,
2371
+ inheritedAutonomous: process.env.CEZ_AUTONOMOUS_DEFAULT === '0'
2372
+ ? false
2373
+ : process.env.CEZ_AUTONOMOUS_DEFAULT === '1'
2374
+ ? true
2375
+ : 'source-dependent',
2376
+ inheritedWorktree: effectiveComposerDefault(undefined, process.env.CEZ_WORKTREE_DEFAULT, true),
2377
+ },
1314
2378
  resources: {
1315
2379
  maxParallel: config.resources.maxParallel,
2380
+ maxMonitoringSessions: config.resources.maxMonitoringSessions,
2381
+ monitoringWakeIntervalMinutes: config.resources.monitoringWakeIntervalMinutes,
2382
+ autoResumeOnUsageLimit: config.resources.autoResumeOnUsageLimit,
1316
2383
  memoryLimitMb: config.resources.memoryLimitMb,
1317
2384
  worktreeRetentionDefault: config.resources.worktreeRetentionDefault,
1318
2385
  },
2386
+ // SPREAD, never `runner: maybeUndefined`: hono would type the key as always-present while
2387
+ // `JSON.stringify` drops it, which is the exact drift `contract-parity` catches. And absent has
2388
+ // to keep meaning "no opinion" here, or the fallback collapses into "always claude".
2389
+ agentDefaults: {
2390
+ ...(config.agentDefaults.runner !== undefined ? { runner: config.agentDefaults.runner } : {}),
2391
+ ...(config.agentDefaults.models !== undefined ? { models: config.agentDefaults.models } : {}),
2392
+ },
1319
2393
  });
1320
- app.get('/api/workspace/config', async (c) => c.json(workspaceConfigBody(await loadWorkspaceConfig())));
1321
- // Partial updates only — absent keys stay untouched. Bounds mirror the
1322
- // workspace schema (src/workspace/config.ts, step 1.2) exactly, so a value
1323
- // this route accepts can never be degraded away by the next load's `.catch`.
1324
- const workspaceConfigUpdateSchema = z.object({
1325
- browseRoot: z.string().trim().min(1).max(4096).optional(),
1326
- projectsDir: z.string().trim().min(1).max(4096).optional(),
1327
- resources: z
1328
- .object({
1329
- maxParallel: z.number().int().min(1).max(16).optional(),
1330
- memoryLimitMb: z.number().int().min(0).max(1_048_576).nullable().optional(),
1331
- worktreeRetentionDefault: z.number().int().min(0).max(1000).optional(),
1332
- })
1333
- .optional(),
1334
- });
1335
- app.put('/api/workspace/config', async (c) => {
1336
- const parsed = workspaceConfigUpdateSchema.safeParse(await c.req.json().catch(() => null));
1337
- if (!parsed.success) {
1338
- return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
1339
- }
1340
- const { browseRoot, projectsDir, resources } = parsed.data;
2394
+ // ---- chained family: workspace settings + GUI prefs (workspace-level) ----
2395
+ const workspaceConfigRoutes = new Hono()
2396
+ .get('/workspace/config', async (c) => c.json(workspaceConfigBody(await loadWorkspaceConfig())))
2397
+ .put('/workspace/config', jsonZodValidator(() => workspaceConfigUpdateSchema), async (c) => {
2398
+ const parsed = { data: c.req.valid('json') };
2399
+ const { browseRoot, projectsDir, skillsAutoUpdate, composerDefaults, resources, agentDefaults } = parsed.data;
1341
2400
  for (const [configuredRoot, create] of [
1342
2401
  [browseRoot, false],
1343
2402
  [projectsDir, true],
@@ -1376,13 +2435,57 @@ export function createApp(deps) {
1376
2435
  config.browseRoot = browseRoot;
1377
2436
  if (projectsDir !== undefined)
1378
2437
  config.projectsDir = projectsDir;
2438
+ if (skillsAutoUpdate === null)
2439
+ delete config.skillsAutoUpdate;
2440
+ else if (skillsAutoUpdate !== undefined)
2441
+ config.skillsAutoUpdate = skillsAutoUpdate;
2442
+ if (composerDefaults?.autonomous === null)
2443
+ delete config.composerDefaults.autonomous;
2444
+ else if (composerDefaults?.autonomous !== undefined) {
2445
+ config.composerDefaults.autonomous = composerDefaults.autonomous;
2446
+ }
2447
+ if (composerDefaults?.worktree === null)
2448
+ delete config.composerDefaults.worktree;
2449
+ else if (composerDefaults?.worktree !== undefined) {
2450
+ config.composerDefaults.worktree = composerDefaults.worktree;
2451
+ }
1379
2452
  if (resources?.maxParallel !== undefined)
1380
2453
  config.resources.maxParallel = resources.maxParallel;
2454
+ if (resources?.maxMonitoringSessions !== undefined) {
2455
+ config.resources.maxMonitoringSessions = resources.maxMonitoringSessions;
2456
+ }
2457
+ if (resources?.monitoringWakeIntervalMinutes !== undefined) {
2458
+ config.resources.monitoringWakeIntervalMinutes = resources.monitoringWakeIntervalMinutes;
2459
+ }
2460
+ if (resources?.autoResumeOnUsageLimit !== undefined) {
2461
+ config.resources.autoResumeOnUsageLimit = resources.autoResumeOnUsageLimit;
2462
+ }
1381
2463
  if (resources?.memoryLimitMb !== undefined)
1382
2464
  config.resources.memoryLimitMb = resources.memoryLimitMb;
1383
2465
  if (resources?.worktreeRetentionDefault !== undefined) {
1384
2466
  config.resources.worktreeRetentionDefault = resources.worktreeRetentionDefault;
1385
2467
  }
2468
+ // `null` CLEARS back to "no opinion" — a partial patch cannot say that by omission,
2469
+ // and leaving a stale runner behind would keep overriding repos that never chose.
2470
+ if (agentDefaults?.runner === null)
2471
+ delete config.agentDefaults.runner;
2472
+ else if (agentDefaults?.runner !== undefined)
2473
+ config.agentDefaults.runner = agentDefaults.runner;
2474
+ for (const runner of PROVIDER_IDS) {
2475
+ const model = agentDefaults?.models?.[runner];
2476
+ if (model === undefined)
2477
+ continue;
2478
+ const models = config.agentDefaults.models ?? {};
2479
+ if (model === null)
2480
+ delete models[runner];
2481
+ else
2482
+ models[runner] = model;
2483
+ // An empty object would persist a key that says nothing; absence is the same answer.
2484
+ if (Object.keys(models).length === 0)
2485
+ delete config.agentDefaults.models;
2486
+ else
2487
+ config.agentDefaults.models = models;
2488
+ }
1386
2489
  });
1387
2490
  }
1388
2491
  catch (err) {
@@ -1394,15 +2497,19 @@ export function createApp(deps) {
1394
2497
  if (resources !== undefined)
1395
2498
  await deps.semaphore?.refresh();
1396
2499
  return c.json(workspaceConfigBody(written));
1397
- });
1398
- // Global GUI state (`~/.cezar/ui-state.json`) — same parse/key-cap/shallow-
1399
- // merge semantics as the per-repo /api/ui-state route below (the shared half
1400
- // is `parseUiStateBody`), but backed by the workspace file.
1401
- app.get('/api/workspace/ui-state', async (c) => c.json(await readWorkspaceUiState()));
1402
- app.put('/api/workspace/ui-state', bodyLimit({ maxSize: UI_STATE_BODY_LIMIT }), async (c) => {
1403
- const parsed = parseUiStateBody(workspaceUiStateSchema, await c.req.json().catch(() => null));
1404
- if ('error' in parsed)
1405
- return c.json({ error: parsed.error }, 400);
2500
+ })
2501
+ // Global GUI state (`~/.cezar/ui-state.json`) — same parse/key-cap/shallow-
2502
+ // merge semantics as the per-repo /api/v1/ui-state route below (the shared half
2503
+ // is `uiStateBodySchema`), but backed by the workspace file.
2504
+ .get('/workspace/ui-state', async (c) => c.json(await readWorkspaceUiState()))
2505
+ // The tighter body cap rides on `use` rather than inline on the route: `bodyLimit` is typed
2506
+ // as a bare MiddlewareHandler, and passing one to `.put()` collapses the route's schema, so
2507
+ // the PUT went missing from `AppType` and `hc` could not see its body at all. `use` runs at
2508
+ // the same point (before the handler, so the cap still precedes any read) and leaves the
2509
+ // chain's type accumulation alone. Method-agnostic here, which the GET does not mind.
2510
+ .use('/workspace/ui-state', bodyLimit({ maxSize: UI_STATE_BODY_LIMIT }))
2511
+ .put('/workspace/ui-state', jsonZodValidator(workspaceUiStateBody), async (c) => {
2512
+ const parsed = { data: c.req.valid('json') };
1406
2513
  try {
1407
2514
  return c.json(await mergeWriteWorkspaceUiState((state) => ({
1408
2515
  ...state,
@@ -1414,67 +2521,118 @@ export function createApp(deps) {
1414
2521
  return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
1415
2522
  }
1416
2523
  });
1417
- // ---- filesystem browse (multi-project spec, step 4.1) --------------------
1418
- // WORKSPACE-level and same-origin: the directory picker behind "Add project
1419
- // → open local folder". Directories only, and every answer is contained in a
1420
- // single root — see src/server/fs-browse.ts for the containment rule and why
1421
- // it is realpath-based. The independently configured browse root is read per
1422
- // request, so a successful settings save applies without a restart.
1423
- app.get('/api/fs/browse', async (c) => {
2524
+ // Partial updates only — absent keys stay untouched. Bounds mirror the
2525
+ // workspace schema (src/workspace/config.ts, step 1.2) exactly, so a value
2526
+ // this route accepts can never be degraded away by the next load's `.catch`.
2527
+ const workspaceConfigUpdateSchema = z.object({
2528
+ browseRoot: z.string().trim().min(1).max(4096).optional(),
2529
+ projectsDir: z.string().trim().min(1).max(4096).optional(),
2530
+ skillsAutoUpdate: z.boolean().nullable().optional(),
2531
+ composerDefaults: z
2532
+ .object({
2533
+ autonomous: z.boolean().nullable().optional(),
2534
+ worktree: z.boolean().nullable().optional(),
2535
+ })
2536
+ .optional(),
2537
+ resources: z
2538
+ .object({
2539
+ maxParallel: z.number().int().min(1).max(16).optional(),
2540
+ maxMonitoringSessions: z.number().int().min(0).max(16).optional(),
2541
+ monitoringWakeIntervalMinutes: z.number().int().min(1).max(60).nullable().optional(),
2542
+ autoResumeOnUsageLimit: z.boolean().optional(),
2543
+ memoryLimitMb: z.number().int().min(0).max(1_048_576).nullable().optional(),
2544
+ worktreeRetentionDefault: z.number().int().min(0).max(1000).optional(),
2545
+ })
2546
+ .optional(),
2547
+ // Bounds mirror `src/workspace/config.ts`, so a value this accepts is never degraded away by
2548
+ // the next load's `.catch`. `null` clears a key back to "no opinion".
2549
+ agentDefaults: z
2550
+ .object({
2551
+ runner: z.enum(PROVIDER_IDS).nullable().optional(),
2552
+ models: z
2553
+ .object({
2554
+ claude: z.string().trim().min(1).max(200).nullable().optional(),
2555
+ codex: z.string().trim().min(1).max(200).nullable().optional(),
2556
+ opencode: z.string().trim().min(1).max(200).nullable().optional(),
2557
+ })
2558
+ .optional(),
2559
+ })
2560
+ .optional(),
2561
+ });
2562
+ // ---- chained family: filesystem browse (workspace-level) ----
2563
+ const fsBrowseRoutes = new Hono()
2564
+ .get('/fs/browse', queryZodValidator(z.object({ path: queryValue, showHidden: queryValue })), async (c) => {
1424
2565
  if (capabilities().singleProject) {
1425
2566
  return c.json(singleProjectRefusal('folder browsing'), 409);
1426
2567
  }
2568
+ const query = c.req.valid('query');
1427
2569
  const root = resolveBrowseRoot(await workspaceBrowseRoot());
1428
2570
  const result = await browseDirectory({
1429
2571
  root,
1430
- path: c.req.query('path'),
1431
- showHidden: c.req.query('showHidden') === '1',
2572
+ path: query.path,
2573
+ showHidden: query.showHidden === '1',
1432
2574
  });
1433
2575
  if (!result.ok)
1434
2576
  return c.json({ error: result.error }, result.status);
1435
2577
  return c.json(result.body);
1436
2578
  });
1437
- // The bookmarklet generator bakes this key into the `javascript:` URLs —
1438
- // `/new?auto=1` is honored only with it (spec 011). Same-origin only.
1439
- api.get('/launch-key', (c) => c.json({ key: c.get('project').launchKey }));
1440
- api.get('/skills', async (c) => {
2579
+ // ---- chained family: launch-key (project-scoped) ----
2580
+ const launchKeyRoutes = new Hono()
2581
+ .get('/launch-key', (c) => c.json({ key: c.get('project').launchKey }));
2582
+ // ---- chained family: skills (project-scoped) ----
2583
+ const skillsRoutes = new Hono()
2584
+ .get('/skills', queryZodValidator(waitQuery), async (c) => {
1441
2585
  const repoRoot = c.get('project').root;
1442
2586
  // The default read stays fast and starts the team load in the background.
1443
2587
  // The cockpit follows it with `wait=1`, off the render path, so a cold
1444
2588
  // cache converges without polling or a manual reload (spec 005 / #555).
1445
- if (c.req.query('wait') === '1')
2589
+ if (c.req.valid('query').wait === '1')
1446
2590
  await waitForTeamSkills(repoRoot);
1447
2591
  return c.json(await discoverSkills(repoRoot));
1448
- });
1449
- // The opt-in catalog for the "Import skills" panel: every skill a default
1450
- // (vendor) repo offers — `open-mercato/skills` — regardless of import state,
1451
- // so the panel can present them all with a per-skill toggle. Empty once a repo
1452
- // configures its own `skillsRepos` (nothing is gated then). `wait=1` lets the
1453
- // panel wait out a cold team-skill cache, same as `GET /skills` (spec 005).
1454
- api.get('/skills/importable', async (c) => {
2592
+ })
2593
+ // The opt-in catalog for the "Import skills" panel: every skill a default
2594
+ // (vendor) repo offers — `open-mercato/skills` — regardless of import state,
2595
+ // so the panel can present them all with a per-skill toggle. Empty once a repo
2596
+ // configures its own `skillsRepos` (nothing is gated then). `wait=1` lets the
2597
+ // panel wait out a cold team-skill cache, same as `GET /skills` (spec 005).
2598
+ .get('/skills/importable', queryZodValidator(waitQuery), async (c) => {
1455
2599
  const repoRoot = c.get('project').root;
1456
2600
  const gated = await gatedSkillsRepos(repoRoot);
1457
2601
  if (gated.size === 0)
1458
2602
  return c.json([]);
1459
- if (c.req.query('wait') === '1')
2603
+ if (c.req.valid('query').wait === '1')
1460
2604
  await waitForTeamSkills(repoRoot);
1461
2605
  const importable = getTeamSkillsCached(repoRoot)
1462
2606
  .filter((skill) => skill.team && gated.has(skill.team.repo))
1463
- .map((skill) => ({ name: skill.name, description: skill.description }));
2607
+ // Spread `description` rather than writing it unconditionally: an undefined VALUE is
2608
+ // dropped by JSON.stringify, so the key is absent on the wire, and writing it always
2609
+ // typed the route as sending a key it does not. contract/skills.ts says `.optional()`,
2610
+ // which is what the client actually receives.
2611
+ .map((skill) => ({
2612
+ name: skill.name,
2613
+ ...(skill.description !== undefined ? { description: skill.description } : {}),
2614
+ }));
1464
2615
  return c.json(importable);
2616
+ })
2617
+ // Refresh team skills (spec 005): clone/fetch the configured skills repos,
2618
+ // then return the merged catalog. Degrades quietly — offline just means the
2619
+ // team entries stay as they were (or absent).
2620
+ .post('/skills/refresh', async (c) => {
2621
+ const { root: repoRoot } = c.get('project');
2622
+ await refreshTeamSkills(repoRoot);
2623
+ return c.json(await discoverSkills(repoRoot));
1465
2624
  });
1466
- // ---- GUI prefs (ui-state.json) --------------------------------------------
1467
- // The read path is shared with the CLI (`src/ui-state.ts`) so `cezar serve` can honour a
1468
- // preference set here — #391's dismissed skills banner — from one notion of the file.
1469
- api.get('/ui-state', async (c) => c.json(await readUiState(c.get('project').root)));
1470
- api.put('/ui-state', bodyLimit({ maxSize: UI_STATE_BODY_LIMIT }), async (c) => {
2625
+ // ---- chained family: GUI prefs / ui-state (project-scoped) ----
2626
+ const uiStateRoutes = new Hono()
2627
+ .get('/ui-state', async (c) => c.json(await readUiState(c.get('project').root)))
2628
+ // On `use`, not inline on the route — see the workspace ui-state PUT above.
2629
+ .use('/ui-state', bodyLimit({ maxSize: UI_STATE_BODY_LIMIT }))
2630
+ .put('/ui-state', jsonZodValidator(uiStateBody), async (c) => {
1471
2631
  const { root: repoRoot, dataDir } = c.get('project');
1472
2632
  // `.passthrough()` keeps unknown prefs (BACKWARD_COMPATIBILITY §3), but a
1473
2633
  // single request may not stuff an unbounded key set (#429) — the shared
1474
- // parse+cap half of both ui-state routes lives in parseUiStateBody.
1475
- const parsed = parseUiStateBody(uiStateSchema, await c.req.json().catch(() => null));
1476
- if ('error' in parsed)
1477
- return c.json({ error: parsed.error }, 400);
2634
+ // schema+cap half of both ui-state routes lives in `uiStateBody`.
2635
+ const parsed = { data: c.req.valid('json') };
1478
2636
  const merged = { ...(await readUiState(repoRoot)), ...parsed.data };
1479
2637
  try {
1480
2638
  await mkdir(dataDir, { recursive: true });
@@ -1485,24 +2643,18 @@ export function createApp(deps) {
1485
2643
  }
1486
2644
  return c.json(merged);
1487
2645
  });
1488
- // Refresh team skills (spec 005): clone/fetch the configured skills repos,
1489
- // then return the merged catalog. Degrades quietly — offline just means the
1490
- // team entries stay as they were (or absent).
1491
- api.post('/skills/refresh', async (c) => {
1492
- const { root: repoRoot } = c.get('project');
1493
- await refreshTeamSkills(repoRoot);
1494
- return c.json(await discoverSkills(repoRoot));
1495
- });
1496
- api.get('/workflows', async (c) => c.json(await loadWorkflows(c.get('project').root)));
1497
- // Save an approved plan as a reusable chain (spec 008): YAML in
1498
- // `.ai/cezar/workflows/<slug>.yaml` — from then on it's in the dropdown
1499
- // like any other workflow.
1500
- api.post('/workflows', async (c) => {
2646
+ // ---- chained family: workflows (project-scoped) --------------------------
2647
+ // One chained expression, mounted by `createApp` into BOTH the legacy `api`
2648
+ // table and the versioned `v1` one — see `healthRoutes` for why the chain
2649
+ // shape (not the statement shape) is what carries the types.
2650
+ const workflowsRoutes = new Hono()
2651
+ .get('/workflows', async (c) => c.json(await loadWorkflows(c.get('project').root)))
2652
+ // Save an approved plan as a reusable chain (spec 008): YAML in
2653
+ // `.ai/cezar/workflows/<slug>.yaml` — from then on it's in the dropdown
2654
+ // like any other workflow.
2655
+ .post('/workflows', jsonZodValidator(saveWorkflowSchema), async (c) => {
1501
2656
  const { root: repoRoot } = c.get('project');
1502
- const parsed = saveWorkflowSchema.safeParse(await c.req.json().catch(() => null));
1503
- if (!parsed.success) {
1504
- return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
1505
- }
2657
+ const parsed = { data: c.req.valid('json') };
1506
2658
  const steps = parsed.data.steps ?? skillsToSteps(parsed.data.skills ?? []);
1507
2659
  const issue = stepsIssue(steps);
1508
2660
  if (issue)
@@ -1534,10 +2686,10 @@ export function createApp(deps) {
1534
2686
  return c.json({ error: message }, 500);
1535
2687
  }
1536
2688
  return c.json({ path, name: parsed.data.name }, 201);
1537
- });
1538
- // Delete a saved workflow (spec 012 follow-up): file workflows only —
1539
- // built-ins have no file and always come back.
1540
- api.delete('/workflows/:name', async (c) => {
2689
+ })
2690
+ // Delete a saved workflow (spec 012 follow-up): file workflows only —
2691
+ // built-ins have no file and always come back.
2692
+ .delete('/workflows/:name', async (c) => {
1541
2693
  const { root: repoRoot } = c.get('project');
1542
2694
  const name = c.req.param('name');
1543
2695
  const { workflows } = await loadWorkflows(repoRoot);
@@ -1559,15 +2711,12 @@ export function createApp(deps) {
1559
2711
  return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
1560
2712
  }
1561
2713
  return c.json({ ok: true, path: target });
1562
- });
1563
- // Import support for the builder (spec 012): parse + validate a pasted
1564
- // workflow YAML (either form) and hand back the normalized definition. The
1565
- // server owns YAML parsing — the GUI stays dependency-free.
1566
- api.post('/workflows/parse', async (c) => {
1567
- const parsed = parseWorkflowSchema.safeParse(await c.req.json().catch(() => null));
1568
- if (!parsed.success) {
1569
- return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
1570
- }
2714
+ })
2715
+ // Import support for the builder (spec 012): parse + validate a pasted
2716
+ // workflow YAML (either form) and hand back the normalized definition. The
2717
+ // server owns YAML parsing — the GUI stays dependency-free.
2718
+ .post('/workflows/parse', jsonZodValidator(parseWorkflowSchema), async (c) => {
2719
+ const parsed = { data: c.req.valid('json') };
1571
2720
  let raw;
1572
2721
  try {
1573
2722
  raw = parseYaml(parsed.data.yaml);
@@ -1586,17 +2735,250 @@ export function createApp(deps) {
1586
2735
  return c.json({ error: issue }, 400);
1587
2736
  return c.json(normalized);
1588
2737
  });
1589
- // Chain-from-prompt (spec 008): one cheap claude call proposes a chain of
1590
- // steps for the task. Never blocks — degraded answers come back as a
1591
- // one-step quick-task plan with `fallback: true`.
1592
- api.post('/plan', async (c) => {
2738
+ // ---- chained family: plan (project-scoped) ----
2739
+ const planRoutes = new Hono()
2740
+ .post('/plan', jsonZodValidator(planSchema), async (c) => {
1593
2741
  const { root: repoRoot } = c.get('project');
1594
- const parsed = planSchema.safeParse(await c.req.json().catch(() => null));
1595
- if (!parsed.success) {
1596
- return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
1597
- }
2742
+ const parsed = { data: c.req.valid('json') };
2743
+ const blocked = await providerActionError([(await loadConfig(repoRoot)).defaultRunner]);
2744
+ if (blocked)
2745
+ return c.json({ error: blocked }, 409);
1598
2746
  return c.json(await planChain(repoRoot, parsed.data.task));
1599
2747
  });
2748
+ const manualChecks = new Map();
2749
+ // ---- chained family: GitHub automations (project-scoped) ----
2750
+ // Every handler below reads `c.get('project')` — the definitions, their runtime state and the
2751
+ // execution log are per-project files — so the family is project-scoped and mounted with the
2752
+ // rest of the mirrored table. The one exception is the manual-check read, which touches no
2753
+ // project at all; it is its own workspace-level family below.
2754
+ const automationsRoutes = new Hono()
2755
+ .get('/automations', async (c) => {
2756
+ const { root, automationStore } = c.get('project');
2757
+ const forge = resolveForge(await getRepoInfo(root));
2758
+ // Annotated, so the two branches are ONE shape rather than a union of two: the fallback
2759
+ // literal always carries `reason`, the cached answer only sometimes does, and the route
2760
+ // type is what `contract/src/automations.ts` has to describe.
2761
+ const availability = forge?.detectCached() ?? {
2762
+ available: false,
2763
+ reason: forge ? 'GitHub availability is still being checked' : 'No GitHub remote is configured',
2764
+ };
2765
+ const automations = automationStore.list().map((automation) => {
2766
+ const logs = automationStore.logs({ automationId: automation.id, limit: 100 });
2767
+ const state = automationStore.state(automation.id);
2768
+ const latestLog = logs[0];
2769
+ return {
2770
+ ...automation,
2771
+ // Spread conditionally, never `state: maybeUndefined`: the latter types the key as
2772
+ // always-present while `JSON.stringify` drops it from the wire, so the contract would
2773
+ // have to describe a key consumers never receive.
2774
+ ...(state ? { state } : {}),
2775
+ ...(latestLog ? { latestLog } : {}),
2776
+ counts: {
2777
+ matches: logs.filter((row) => row.result === 'launched' || row.result === 'duplicate').length,
2778
+ launched: logs.filter((row) => row.result === 'launched').length,
2779
+ duplicates: logs.filter((row) => row.result === 'duplicate').length,
2780
+ errors: logs.filter((row) => row.result === 'error' || row.result === 'rate-limited').length,
2781
+ },
2782
+ };
2783
+ });
2784
+ const nextDue = automations.map((item) => item.state?.nextCheckAt).filter(Boolean).sort()[0];
2785
+ return c.json({
2786
+ ...availability,
2787
+ scheduler: {
2788
+ // `as const` on both arms: in an object literal a conditional of two string literals
2789
+ // widens to `string`, which would erase the two states this key can hold.
2790
+ state: automations.some((item) => item.enabled) ? 'scheduled' : 'idle',
2791
+ ...(nextDue ? { nextDue } : {}),
2792
+ },
2793
+ automations,
2794
+ });
2795
+ })
2796
+ .post('/automations', jsonZodValidator(() => automationCreateSchema), async (c) => {
2797
+ const { automationStore } = c.get('project');
2798
+ const parsed = { data: c.req.valid('json') };
2799
+ const promptIssue = validateAutomationPrompt(parsed.data.task.prompt);
2800
+ if (promptIssue)
2801
+ return c.json({ error: promptIssue }, 400);
2802
+ const { enable, ...input } = parsed.data;
2803
+ try {
2804
+ const automation = automationStore.create({ ...input, enabled: enable === true });
2805
+ if (enable) {
2806
+ const baselineAt = new Date().toISOString();
2807
+ automationStore.setState(automation.id, {
2808
+ revision: automation.revision,
2809
+ baselineAt,
2810
+ cursor: { timestamp: baselineAt },
2811
+ nextCheckAt: new Date(Date.now() + automation.intervalSeconds * 1_000).toISOString(),
2812
+ });
2813
+ }
2814
+ emitAutomationChange(c.get('project'), automation.id, automation.revision);
2815
+ automationsChanged();
2816
+ return c.json({ automation }, 201);
2817
+ }
2818
+ catch (error) {
2819
+ return c.json({ error: error instanceof Error ? error.message : String(error) }, 400);
2820
+ }
2821
+ })
2822
+ .get('/automations/:id', (c) => {
2823
+ const { automationStore } = c.get('project');
2824
+ const automation = automationStore.get(c.req.param('id'));
2825
+ if (!automation)
2826
+ return c.json({ error: 'not found' }, 404);
2827
+ const state = automationStore.state(automation.id);
2828
+ const latestLog = automationStore.logs({ automationId: automation.id, limit: 1 })[0];
2829
+ return c.json({
2830
+ automation,
2831
+ ...(state ? { state } : {}),
2832
+ ...(latestLog ? { latestLog } : {}),
2833
+ });
2834
+ })
2835
+ .put('/automations/:id', jsonZodValidator(() => automationUpdateSchema), async (c) => {
2836
+ const { automationStore } = c.get('project');
2837
+ const parsed = { data: c.req.valid('json') };
2838
+ const promptIssue = validateAutomationPrompt(parsed.data.task.prompt);
2839
+ if (promptIssue)
2840
+ return c.json({ error: promptIssue }, 400);
2841
+ const { expectedRevision, ...input } = parsed.data;
2842
+ if (!automationStore.get(c.req.param('id')))
2843
+ return c.json({ error: 'not found' }, 404);
2844
+ try {
2845
+ const automation = automationStore.update(c.req.param('id'), expectedRevision, { ...input, enabled: input.enabled ?? false });
2846
+ emitAutomationChange(c.get('project'), automation.id, automation.revision);
2847
+ automationsChanged();
2848
+ return c.json({ automation });
2849
+ }
2850
+ catch (error) {
2851
+ const message = error instanceof Error ? error.message : String(error);
2852
+ return c.json({ error: message }, message.includes('conflict') ? 409 : 400);
2853
+ }
2854
+ })
2855
+ .delete('/automations/:id', (c) => {
2856
+ const id = c.req.param('id');
2857
+ const store = c.get('project').automationStore;
2858
+ const current = store.get(id);
2859
+ if (!current || !store.delete(id))
2860
+ return c.json({ error: 'not found' }, 404);
2861
+ emitAutomationChange(c.get('project'), id, current.revision, true);
2862
+ automationsChanged();
2863
+ return c.body(null, 204);
2864
+ })
2865
+ .post('/automations/:id/enable', (c) => {
2866
+ const store = c.get('project').automationStore;
2867
+ const current = store.get(c.req.param('id'));
2868
+ if (!current)
2869
+ return c.json({ error: 'not found' }, 404);
2870
+ const automation = store.update(current.id, current.revision, { ...editableAutomation(current), enabled: true });
2871
+ const baselineAt = new Date().toISOString();
2872
+ store.setState(automation.id, {
2873
+ ...store.state(automation.id),
2874
+ revision: automation.revision,
2875
+ baselineAt,
2876
+ cursor: { timestamp: baselineAt },
2877
+ nextCheckAt: new Date(Date.now() + automation.intervalSeconds * 1_000).toISOString(),
2878
+ });
2879
+ store.appendLog({ automationId: automation.id, revision: automation.revision, result: 'baseline', reason: 'Enabled from a current-time baseline; existing records were not launched.' });
2880
+ emitAutomationChange(c.get('project'), automation.id, automation.revision);
2881
+ automationsChanged();
2882
+ return c.json({ automation });
2883
+ })
2884
+ .post('/automations/:id/pause', (c) => {
2885
+ const store = c.get('project').automationStore;
2886
+ const current = store.get(c.req.param('id'));
2887
+ if (!current)
2888
+ return c.json({ error: 'not found' }, 404);
2889
+ const automation = store.update(current.id, current.revision, { ...editableAutomation(current), enabled: false });
2890
+ emitAutomationChange(c.get('project'), automation.id, automation.revision);
2891
+ automationsChanged();
2892
+ return c.json({ automation });
2893
+ })
2894
+ // The body is validated as MIDDLEWARE, which is what puts it in the route type — and moves
2895
+ // the 400 ahead of this route's 404: `POST /automations/<unknown>/check` with a malformed
2896
+ // body now answers 400 rather than 404. Nothing else about either answer changed.
2897
+ .post('/automations/:id/check', jsonZodValidator(() => automationCheckRequestSchema), async (c) => {
2898
+ const project = c.get('project');
2899
+ const store = project.automationStore;
2900
+ const automation = store.get(c.req.param('id'));
2901
+ if (!automation)
2902
+ return c.json({ error: 'not found' }, 404);
2903
+ const parsed = { data: c.req.valid('json') };
2904
+ // `string`, not `randomUUID`'s template-literal type: the wire carries an opaque id, and
2905
+ // leaking `${string}-${string}-…` into the route type would make the contract describe the
2906
+ // generator rather than the answer.
2907
+ const id = randomUUID();
2908
+ const check = { id, automationId: automation.id, mode: parsed.data.mode, status: 'queued', createdAt: new Date().toISOString() };
2909
+ if (manualChecks.size >= 200)
2910
+ manualChecks.delete(manualChecks.keys().next().value);
2911
+ manualChecks.set(id, check);
2912
+ void (async () => {
2913
+ check.status = 'running';
2914
+ try {
2915
+ const remote = parseRemote((await getRepoInfo(project.root))?.remote ?? '');
2916
+ if (!remote || remote.host !== 'github.com')
2917
+ throw new Error('No GitHub remote is configured');
2918
+ const scheduler = new ProjectAutomationScheduler({
2919
+ projectId: project.id,
2920
+ owner: remote.owner,
2921
+ repo: remote.repo,
2922
+ store,
2923
+ poller: new GithubPoller(),
2924
+ launch: parsed.data.mode === 'execute'
2925
+ ? (definition, candidate, receiptId) => launchAutomationRun({ root: project.root, manager: project.manager, store: project.store, definition, candidate, receiptId })
2926
+ : undefined,
2927
+ onChange: (automationId, revision) => emitAutomationChange(project, automationId, revision),
2928
+ });
2929
+ const result = await scheduler.check(automation, parsed.data.mode);
2930
+ Object.assign(check, { status: 'complete', completedAt: new Date().toISOString(), matches: result.candidates.length, truncated: result.truncated });
2931
+ }
2932
+ catch (error) {
2933
+ Object.assign(check, { status: 'error', completedAt: new Date().toISOString(), error: error instanceof Error ? error.message : String(error) });
2934
+ }
2935
+ })();
2936
+ return c.json({ checkId: id }, 202);
2937
+ })
2938
+ .get('/automation-log', queryZodValidator(automationLogQuerySchema), (c) => {
2939
+ return c.json({ records: c.get('project').automationStore.logs(c.req.valid('query')) });
2940
+ })
2941
+ .post('/automation-log/:receiptId/retry', async (c) => {
2942
+ const project = c.get('project');
2943
+ const store = project.automationStore;
2944
+ const receipt = [...store.latestReceipts().values()].find((row) => row.receiptId === c.req.param('receiptId'));
2945
+ if (!receipt)
2946
+ return c.json({ error: 'not found' }, 404);
2947
+ if (receipt.status !== 'launch-error' || receipt.runId)
2948
+ return c.json({ error: 'receipt is not retryable' }, 409);
2949
+ if (!receipt.candidate)
2950
+ return c.json({ error: 'receipt predates retry context and cannot be retried safely' }, 409);
2951
+ const definition = store.get(receipt.automationId);
2952
+ if (!definition)
2953
+ return c.json({ error: 'automation not found' }, 404);
2954
+ const lease = store.acquireLease();
2955
+ if (!lease)
2956
+ return c.json({ error: 'automation polling lease is held by another process' }, 409);
2957
+ const reserved = { ...receipt, status: 'reserved', error: undefined, updatedAt: new Date().toISOString() };
2958
+ store.appendReceipt(reserved);
2959
+ try {
2960
+ const launched = await launchAutomationRun({ root: project.root, manager: project.manager, store: project.store, definition, candidate: receipt.candidate, receiptId: receipt.receiptId });
2961
+ store.appendReceipt({ ...reserved, status: 'launched', runId: launched.runId, updatedAt: new Date().toISOString() });
2962
+ emitAutomationChange(project, definition.id, definition.revision);
2963
+ return c.json({ receiptId: receipt.receiptId, runId: launched.runId }, 202);
2964
+ }
2965
+ catch (error) {
2966
+ store.appendReceipt({ ...reserved, status: 'launch-error', error: error instanceof Error ? error.message : String(error), updatedAt: new Date().toISOString() });
2967
+ return c.json({ error: error instanceof Error ? error.message : String(error) }, 409);
2968
+ }
2969
+ finally {
2970
+ lease.release();
2971
+ }
2972
+ });
2973
+ // ---- chained family: manual automation checks (workspace-level) ----
2974
+ // Workspace-level because the handler reads no project: a check lives in the server-memory map
2975
+ // above, keyed by an unguessable id that the project-scoped POST hands back. Mounting it under
2976
+ // `/api/v1/p/:projectId` too would be a second spelling of a lookup that consults no project.
2977
+ const automationChecksRoutes = new Hono()
2978
+ .get('/automation-checks/:checkId', (c) => {
2979
+ const check = manualChecks.get(c.req.param('checkId'));
2980
+ return check ? c.json(check) : c.json({ error: 'not found' }, 404);
2981
+ });
1600
2982
  // ---- runs ----------------------------------------------------------------
1601
2983
  // Additive `usage` field (#348): the latest CPU/RSS/proc-count sample of the
1602
2984
  // run's live process tree — absent for finished runs and when `ps` yields
@@ -1625,27 +3007,49 @@ export function createApp(deps) {
1625
3007
  console.warn(`[cezar] could not mark inbox entry ${todoId} started: ${String(err)}`);
1626
3008
  }
1627
3009
  };
1628
- api.get('/runs', (c) => c.json(c.get('project').store.listRuns().map(withUsage)));
1629
- // Registered before the `/:id/...` routes so "archive-finished" never
1630
- // matches as a run id.
1631
- api.post('/runs/archive-finished', (c) => c.json({ archived: c.get('project').store.archiveFinished() }));
1632
- api.post('/runs/:id/archive', async (c) => {
3010
+ // ---- chained family: runs lifecycle + artifacts (project-scoped) ----
3011
+ const runsRoutes = new Hono()
3012
+ .get('/runs', (c) => c.json(c.get('project').store.listRuns().map(withUsage)))
3013
+ // Registered before the `/:id/...` routes so "archive-finished" and "read-all"
3014
+ // never match as a run id.
3015
+ .post('/runs/archive-finished', (c) => c.json({ archived: c.get('project').store.archiveFinished() }))
3016
+ // The read-receipt sweep (#unread-done-items) — the mark-read twin of the archive
3017
+ // sweep above, and under the same registration-order guard.
3018
+ .post('/runs/read-all', (c) => c.json({ read: c.get('project').store.markAllRead() }))
3019
+ .post('/runs/:id/archive', jsonZodValidator(archiveSchema, { absent: ({}) }), async (c) => {
1633
3020
  const { store } = c.get('project');
1634
3021
  const id = c.req.param('id');
1635
3022
  // An empty/absent body archives (the common case); a malformed body degrades
1636
3023
  // to `{}` just as before, but a wrong-typed `archived` is now a 400 (#429).
1637
- const parsed = archiveSchema.safeParse(await c.req.json().catch(() => ({})));
1638
- if (!parsed.success) {
1639
- return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
1640
- }
3024
+ // Archiving also retires any pending usage-limit resume, but that rule belongs to
3025
+ // `setArchived` itself — the bulk sweep must obey it too (spec
3026
+ // 2026-08-03-auto-resume-after-usage-limit).
3027
+ const parsed = { data: c.req.valid('json') };
1641
3028
  const run = store.setArchived(id, parsed.data.archived !== false);
1642
3029
  return run ? c.json(run) : c.json({ error: 'not found' }, 404);
1643
- });
1644
- api.post('/runs', async (c) => {
3030
+ })
3031
+ // The per-task off switch for that resume (the workspace setting is Settings → Resources).
3032
+ // Idempotent: a run with nothing pending answers 200 too, because "this task will not
3033
+ // resume itself" is equally true either way.
3034
+ .delete('/runs/:id/auto-resume', (c) => {
3035
+ const { store, manager } = c.get('project');
3036
+ const id = c.req.param('id');
3037
+ if (!store.getRun(id))
3038
+ return c.json({ error: 'not found' }, 404);
3039
+ manager.cancelAutoResume(id);
3040
+ return c.json({ cancelled: true });
3041
+ })
3042
+ .post('/runs/:id/read', (c) => {
3043
+ // No body: opening a thread marks it read, full stop. Stamps `seenAt = now` and
3044
+ // returns the updated record (which also rides the `run` SSE via `touch`).
3045
+ const run = c.get('project').store.setRead(c.req.param('id'));
3046
+ return run ? c.json(run) : c.json({ error: 'not found' }, 404);
3047
+ })
3048
+ .post('/runs', jsonZodValidator(startRunSchema), async (c) => {
1645
3049
  const { root: repoRoot, dataDir, manager } = c.get('project');
1646
- const parsed = startRunSchema.safeParse(await c.req.json().catch(() => null));
1647
- if (!parsed.success) {
1648
- return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
3050
+ const parsed = { data: c.req.valid('json') };
3051
+ if (agentModelsLocked(repoRoot) && parsed.data.model?.trim()) {
3052
+ return c.json({ error: AGENT_MODELS_LOCKED_ERROR }, 409);
1649
3053
  }
1650
3054
  let workflow;
1651
3055
  if (parsed.data.steps) {
@@ -1653,166 +3057,91 @@ export function createApp(deps) {
1653
3057
  const issue = stepsIssue(parsed.data.steps);
1654
3058
  if (issue)
1655
3059
  return c.json({ error: issue }, 400);
1656
- workflow = {
1657
- name: '(planned)',
1658
- source: 'built-in',
1659
- steps: parsed.data.steps,
1660
- };
1661
- }
1662
- else {
1663
- const { workflows } = await loadWorkflows(repoRoot);
1664
- workflow = workflows.find((w) => w.name === parsed.data.workflow);
1665
- if (!workflow)
1666
- return c.json({ error: `unknown workflow: ${parsed.data.workflow}` }, 404);
1667
- }
1668
- const images = parsed.data.images?.map((img) => ({
1669
- type: 'image',
1670
- source: { type: 'base64', media_type: img.mediaType, data: img.data },
1671
- }));
1672
- const input = {
1673
- task: parsed.data.task,
1674
- model: parsed.data.model,
1675
- runner: parsed.data.runner,
1676
- images,
1677
- systemPrompt: parsed.data.systemPrompt,
1678
- worktree: parsed.data.worktree,
1679
- autonomous: parsed.data.autonomous,
1680
- // Opt-in inbox (#471): the capability is the ceiling, so a client asking
1681
- // for follow-ups on a server that has them off gets a plain `false`
1682
- // rather than an error — the run is still perfectly valid without them.
1683
- // One decision here feeds the run record, the system prompt and
1684
- // CEZ_TODOS_FILE alike (RunManager.agentEnv).
1685
- generateFollowups: capabilities().followups ? parsed.data.generateFollowups : false,
1686
- };
1687
- const variants = parsed.data.variants ?? 1;
1688
- if (variants > 1) {
1689
- // Variants live in worktrees — without git there's nothing to isolate
1690
- // them with, so this degrades to a clear 400 instead of stepping on
1691
- // one shared working tree.
1692
- const repo = await getRepoInfo(repoRoot);
1693
- if (!repo) {
1694
- return c.json({
1695
- error: 'parallel variants need a git repository (each variant runs in its own worktree) — run ×1 here, or start cezar inside a git repo',
1696
- }, 400);
1697
- }
1698
- const runs = manager.startVariants(workflow, input, variants);
1699
- // The entry points at the first variant — the thread the composer navigates to.
1700
- const first = runs[0];
1701
- if (parsed.data.todoId && first)
1702
- await noteTodoStarted(dataDir, parsed.data.todoId, first.id);
1703
- return c.json({ runs }, 201);
1704
- }
1705
- const run = manager.startRun(workflow, input);
1706
- if (parsed.data.todoId)
1707
- await noteTodoStarted(dataDir, parsed.data.todoId, run.id);
1708
- return c.json(run, 201);
1709
- });
1710
- // ---- parallel variants (spec 010) -----------------------------------------
1711
- const groupRuns = (store, groupId) => store
1712
- .listRuns()
1713
- .filter((r) => r.groupId === groupId)
1714
- .sort((a, b) => (a.variant ?? '').localeCompare(b.variant ?? ''));
1715
- // Comparison data: per variant the status, cost, `git diff --stat` and the
1716
- // first Progress-log lines from the handoff. The full diff is fetched per
1717
- // variant via the existing GET /api/runs/:id/diff.
1718
- api.get('/groups/:groupId', async (c) => {
1719
- const { dataDir, store } = c.get('project');
1720
- const runs = groupRuns(store, c.req.param('groupId'));
1721
- if (runs.length === 0)
1722
- return c.json({ error: 'not found' }, 404);
1723
- const detailed = await Promise.all(runs.map(async (r) => ({
1724
- id: r.id,
1725
- variant: r.variant ?? '?',
1726
- title: r.title,
1727
- status: r.status,
1728
- archived: r.archived,
1729
- tokensUsed: r.tokensUsed,
1730
- costUsd: r.costUsd,
1731
- diffStat: r.worktreePath && existsSync(r.worktreePath)
1732
- ? await worktreeDiffStat(r.worktreePath, r.baseBranch ?? 'HEAD')
1733
- : '',
1734
- handoffExcerpt: handoffProgressExcerpt(readHandoff(dataDir, r.id)),
1735
- })));
1736
- return c.json({
1737
- groupId: c.req.param('groupId'),
1738
- runs: detailed,
1739
- });
1740
- });
1741
- // "Pick this one": the winner rests at `review` (spec 009 takes it from
1742
- // there — send back / draft PR / finish); the losers are cancelled if
1743
- // alive, archived, and their worktrees + branches removed.
1744
- api.post('/groups/:groupId/pick', async (c) => {
1745
- const { root: repoRoot, dataDir, store, manager } = c.get('project');
1746
- const runs = groupRuns(store, c.req.param('groupId'));
1747
- if (runs.length === 0)
1748
- return c.json({ error: 'not found' }, 404);
1749
- const parsed = pickSchema.safeParse(await c.req.json().catch(() => null));
1750
- if (!parsed.success) {
1751
- return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
1752
- }
1753
- const winner = runs.find((r) => r.id === parsed.data.runId);
1754
- if (!winner)
1755
- return c.json({ error: 'runId is not part of this group' }, 404);
1756
- if (manager.isActive(winner.id)) {
1757
- return c.json({ error: 'this variant is still active — wait for it to finish first' }, 409);
1758
- }
1759
- // Winner: a non-review terminal state with a non-empty diff flips to
1760
- // `review` (the settleSuccess rule) — but only when the review gate applies
1761
- // (#489): it is enabled (`reviewGateEnabled`, default off) AND the winner is
1762
- // not autonomous. An autonomous / gate-off winner keeps its `done` state with
1763
- // the diff left in the worktree; an empty diff (or no worktree) stays too.
1764
- if (winner.status !== 'review' &&
1765
- winner.worktreePath &&
1766
- existsSync(winner.worktreePath) &&
1767
- winner.autonomous !== true &&
1768
- reviewGateEnabled(await loadConfig(repoRoot))) {
1769
- const diff = await worktreeDiff(winner.worktreePath, winner.baseBranch ?? 'HEAD');
1770
- if (diff.trim().length > 0 && !diff.startsWith('(diff failed')) {
1771
- store.updateRun(winner.id, { status: 'review' });
1772
- }
3060
+ workflow = {
3061
+ name: '(planned)',
3062
+ source: 'built-in',
3063
+ steps: parsed.data.steps,
3064
+ };
1773
3065
  }
1774
- const losers = runs.filter((r) => r.id !== winner.id);
1775
- store.appendEvent(winner.id, {
1776
- type: 'lifecycle',
1777
- message: `picked from ${runs.length} variants — ${losers.length} other variant(s) archived`,
1778
- });
1779
- appendHandoffHeartbeat(dataDir, winner.id, `picked from ${runs.length} variants`);
1780
- for (const loser of losers) {
1781
- if (manager.isActive(loser.id))
1782
- manager.cancel(loser.id);
1783
- if (loser.worktreePath)
1784
- await removeWorktree(repoRoot, loser.worktreePath, loser.branch);
1785
- store.updateRun(loser.id, { worktreePath: undefined, branch: undefined });
1786
- store.setArchived(loser.id, true);
1787
- store.appendEvent(loser.id, {
1788
- type: 'lifecycle',
1789
- message: `variant ${winner.variant ?? '?'} was picked — this variant is archived, its worktree removed`,
1790
- });
3066
+ else {
3067
+ const { workflows } = await loadWorkflows(repoRoot);
3068
+ workflow = workflows.find((w) => w.name === parsed.data.workflow);
3069
+ if (!workflow)
3070
+ return c.json({ error: `unknown workflow: ${parsed.data.workflow}` }, 404);
1791
3071
  }
1792
- return c.json({
1793
- winner: store.getRun(winner.id),
1794
- });
1795
- });
1796
- api.get('/runs/:id', (c) => {
3072
+ const fallback = parsed.data.runner ?? (await loadConfig(repoRoot)).defaultRunner;
3073
+ const blocked = await providerActionError(providersRequiredByWorkflow(workflow, fallback));
3074
+ if (blocked)
3075
+ return c.json({ error: blocked }, 409);
3076
+ // A composer override names an account the user just picked, so a stale id (deleted since
3077
+ // the page loaded) is answered honestly instead of quietly running on the default — the
3078
+ // opposite of how RESOLUTION treats a dangling reference, and deliberately so: a run
3079
+ // replaying a stored id has no better answer than the default, a user does.
3080
+ if (parsed.data.agentProfile !== undefined) {
3081
+ const account = await resolveWorkspaceProfile(fallback, parsed.data.agentProfile);
3082
+ if ('error' in account)
3083
+ return c.json({ error: account.error }, 400);
3084
+ }
3085
+ const images = parsed.data.images?.map((img) => ({
3086
+ type: 'image',
3087
+ source: { type: 'base64', media_type: img.mediaType, data: img.data },
3088
+ }));
3089
+ const input = {
3090
+ task: parsed.data.task,
3091
+ model: parsed.data.model,
3092
+ runner: parsed.data.runner,
3093
+ agentProfile: parsed.data.agentProfile,
3094
+ images,
3095
+ systemPrompt: parsed.data.systemPrompt,
3096
+ worktree: parsed.data.worktree,
3097
+ autonomous: parsed.data.autonomous,
3098
+ // Opt-in inbox (#471): the capability is the ceiling, so a client asking
3099
+ // for follow-ups on a server that has them off gets a plain `false`
3100
+ // rather than an error — the run is still perfectly valid without them.
3101
+ // One decision here feeds the run record, the system prompt and
3102
+ // CEZ_TODOS_FILE alike (RunManager.agentEnv).
3103
+ generateFollowups: capabilities().followups ? parsed.data.generateFollowups : false,
3104
+ };
3105
+ const variants = parsed.data.variants ?? 1;
3106
+ if (variants > 1) {
3107
+ // Variants live in worktrees — without git there's nothing to isolate
3108
+ // them with, so this degrades to a clear 400 instead of stepping on
3109
+ // one shared working tree.
3110
+ const repo = await getRepoInfo(repoRoot);
3111
+ if (!repo) {
3112
+ return c.json({
3113
+ error: 'parallel variants need a git repository (each variant runs in its own worktree) — run ×1 here, or start cezar inside a git repo',
3114
+ }, 400);
3115
+ }
3116
+ const runs = manager.startVariants(workflow, input, variants);
3117
+ // The entry points at the first variant — the thread the composer navigates to.
3118
+ const first = runs[0];
3119
+ if (parsed.data.todoId && first)
3120
+ await noteTodoStarted(dataDir, parsed.data.todoId, first.id);
3121
+ return c.json({ runs }, 201);
3122
+ }
3123
+ const run = manager.startRun(workflow, input);
3124
+ if (parsed.data.todoId)
3125
+ await noteTodoStarted(dataDir, parsed.data.todoId, run.id);
3126
+ return c.json(run, 201);
3127
+ })
3128
+ .get('/runs/:id', (c) => {
1797
3129
  const { store } = c.get('project');
1798
3130
  const run = store.getRun(c.req.param('id'));
1799
3131
  return run ? c.json(withUsage(run)) : c.json({ error: 'not found' }, 404);
1800
- });
1801
- // Editable titles (#389). The UI displays `titleSummary ?? title`, so a
1802
- // user edit sets BOTH: `title` (the record's own name — the raw task stops
1803
- // being it the moment the user renames the run) and `titleSummary` (what
1804
- // actually displays). The auto-summarizer only ever fills an *unset*
1805
- // titleSummary (RunManager.recordTurnEnd), so an edit wins over any past or
1806
- // future auto-summary. Answers the updated record.
1807
- api.patch('/runs/:id', async (c) => {
3132
+ })
3133
+ // Editable titles (#389). The UI displays `titleSummary ?? title`, so a
3134
+ // user edit sets BOTH: `title` (the record's own name — the raw task stops
3135
+ // being it the moment the user renames the run) and `titleSummary` (what
3136
+ // actually displays). The auto-summarizer only ever fills an *unset*
3137
+ // titleSummary (RunManager.recordTurnEnd), so an edit wins over any past or
3138
+ // future auto-summary. Answers the updated record.
3139
+ .patch('/runs/:id', jsonZodValidator(patchRunSchema), async (c) => {
1808
3140
  const { store, manager } = c.get('project');
1809
3141
  const id = c.req.param('id');
1810
3142
  if (!store.getRun(id))
1811
3143
  return c.json({ error: 'not found' }, 404);
1812
- const parsed = patchRunSchema.safeParse(await c.req.json().catch(() => null));
1813
- if (!parsed.success) {
1814
- return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
1815
- }
3144
+ const parsed = { data: c.req.valid('json') };
1816
3145
  // The prompt is editable only while the run is still queued (#472). Checked
1817
3146
  // BEFORE the title write so a rejected PATCH is a no-op rather than a partial
1818
3147
  // one. `title` itself keeps working on any status — no regression to #389.
@@ -1837,25 +3166,33 @@ export function createApp(deps) {
1837
3166
  });
1838
3167
  }
1839
3168
  return c.json(store.getRun(id));
1840
- });
1841
- api.post('/runs/:id/cancel', (c) => {
3169
+ })
3170
+ .post('/runs/:id/cancel', (c) => {
1842
3171
  const { store, manager } = c.get('project');
1843
3172
  const id = c.req.param('id');
1844
3173
  if (!store.getRun(id))
1845
3174
  return c.json({ error: 'not found' }, 404);
1846
3175
  const cancelled = manager.cancel(id);
1847
3176
  return c.json({ cancelled });
1848
- });
1849
- // Live-session participation (spec 002): deliver a user message (text +
1850
- // pasted screenshots) into the run's open claude session.
1851
- api.post('/runs/:id/messages', async (c) => {
3177
+ })
3178
+ // Live-session participation (spec 002): deliver a user message (text +
3179
+ // pasted screenshots) into the run's open claude session.
3180
+ .post('/runs/:id/messages', jsonZodValidator(messageSchema), async (c) => {
1852
3181
  const { store, manager } = c.get('project');
1853
3182
  const id = c.req.param('id');
1854
- if (!store.getRun(id))
3183
+ const run = store.getRun(id);
3184
+ if (!run)
1855
3185
  return c.json({ error: 'not found' }, 404);
1856
- const parsed = messageSchema.safeParse(await c.req.json().catch(() => null));
1857
- if (!parsed.success) {
1858
- return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
3186
+ const parsed = { data: c.req.valid('json') };
3187
+ // Stacking onto a queued prompt mutates an existing task and invokes no provider.
3188
+ // Provider availability still gates live delivery after the record leaves `queued`, but
3189
+ // must not strand prompt authoring just because an unrelated fallback provider is
3190
+ // disconnected (provider-auth spec: disabling never blocks existing-task mutations).
3191
+ // In the dequeue race, the ladder below safely turns this into a starting-state buffer.
3192
+ if (run.status !== 'queued') {
3193
+ const blocked = await providerActionError([providerForActiveRun(run)]);
3194
+ if (blocked)
3195
+ return c.json({ error: blocked }, 409);
1859
3196
  }
1860
3197
  const content = [
1861
3198
  ...parsed.data.images.map((img) => ({
@@ -1871,14 +3208,14 @@ export function createApp(deps) {
1871
3208
  // starting up → buffered · anything else → 409, exactly as before
1872
3209
  if (manager.sendMessage(id, content))
1873
3210
  return c.json({ delivered: true });
1874
- const run = store.getRun(id);
1875
- const stack = run?.queuedMessages ?? [];
3211
+ const currentRun = store.getRun(id);
3212
+ const stack = currentRun?.queuedMessages ?? [];
1876
3213
  // Bounds apply only to a message that is actually about to be stacked. Without this
1877
3214
  // gate an over-long message posted to a *finished* run would answer `400 prompt too
1878
3215
  // long` when the truthful answer is `409 session closed`. The status read is safe
1879
3216
  // here because it only decides whether to reject EARLY — `enqueueMessage` still
1880
3217
  // re-checks against the engine's own queue before writing anything.
1881
- if (run?.status === 'queued') {
3218
+ if (currentRun?.status === 'queued') {
1882
3219
  if (stack.length >= MAX_QUEUED_MESSAGES) {
1883
3220
  return c.json({ error: `too many queued messages — ${MAX_QUEUED_MESSAGES} message limit` }, 400);
1884
3221
  }
@@ -1886,7 +3223,7 @@ export function createApp(deps) {
1886
3223
  if (stackedImages + parsed.data.images.length > MAX_QUEUED_IMAGES) {
1887
3224
  return c.json({ error: `too many queued images — ${MAX_QUEUED_IMAGES} image limit across the stack` }, 400);
1888
3225
  }
1889
- const prospective = foldedLength(run.task, [...stack, { text: parsed.data.text }]);
3226
+ const prospective = foldedLength(currentRun.task, [...stack, { text: parsed.data.text }]);
1890
3227
  if (prospective > MAX_FOLDED_TASK_CHARS) {
1891
3228
  return c.json({
1892
3229
  error: `prompt too long — ${MAX_FOLDED_TASK_CHARS} character limit across the task and its queued messages (would be ${prospective})`,
@@ -1899,19 +3236,16 @@ export function createApp(deps) {
1899
3236
  if (manager.deferMessage(id, content))
1900
3237
  return c.json({ deferred: true });
1901
3238
  return c.json({ error: 'session closed' }, 409);
1902
- });
1903
- // Edit / remove a stacked message (#472). Registered before any conflicting
1904
- // `/:id` route so `queued-messages` never matches as a run id.
1905
- api.patch('/runs/:id/queued-messages/:msgId', async (c) => {
3239
+ })
3240
+ // Edit / remove a stacked message (#472). Registered before any conflicting
3241
+ // `/:id` route so `queued-messages` never matches as a run id.
3242
+ .patch('/runs/:id/queued-messages/:msgId', jsonZodValidator(queuedMessagePatchSchema), async (c) => {
1906
3243
  const { store, manager } = c.get('project');
1907
3244
  const id = c.req.param('id');
1908
3245
  const run = store.getRun(id);
1909
3246
  if (!run)
1910
3247
  return c.json({ error: 'not found' }, 404);
1911
- const parsed = queuedMessagePatchSchema.safeParse(await c.req.json().catch(() => null));
1912
- if (!parsed.success) {
1913
- return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
1914
- }
3248
+ const parsed = { data: c.req.valid('json') };
1915
3249
  const msgId = c.req.param('msgId');
1916
3250
  const stack = run.queuedMessages ?? [];
1917
3251
  const existing = stack.find((m) => m.id === msgId);
@@ -1944,8 +3278,8 @@ export function createApp(deps) {
1944
3278
  if (!message)
1945
3279
  return c.json({ error: 'run already started' }, 409);
1946
3280
  return c.json({ message });
1947
- });
1948
- api.delete('/runs/:id/queued-messages/:msgId', (c) => {
3281
+ })
3282
+ .delete('/runs/:id/queued-messages/:msgId', (c) => {
1949
3283
  const { store, manager } = c.get('project');
1950
3284
  const id = c.req.param('id');
1951
3285
  const run = store.getRun(id);
@@ -1958,9 +3292,9 @@ export function createApp(deps) {
1958
3292
  if (!manager.removeQueuedMessage(id, msgId))
1959
3293
  return c.json({ error: 'run already started' }, 409);
1960
3294
  return c.json({ removed: true });
1961
- });
1962
- // "Finish": gracefully close a waiting session — the run completes as done.
1963
- api.post('/runs/:id/finish', (c) => {
3295
+ })
3296
+ // "Finish": gracefully close a waiting session — the run completes as done.
3297
+ .post('/runs/:id/finish', (c) => {
1964
3298
  const { store, manager } = c.get('project');
1965
3299
  const id = c.req.param('id');
1966
3300
  if (!store.getRun(id))
@@ -1969,19 +3303,23 @@ export function createApp(deps) {
1969
3303
  if (!finished)
1970
3304
  return c.json({ error: 'no open session' }, 409);
1971
3305
  return c.json({ finished: true });
1972
- });
1973
- // "Continue" (spec 003): reopen a finished run's session in-process.
1974
- api.post('/runs/:id/continue', async (c) => {
1975
- const { store, manager } = c.get('project');
3306
+ })
3307
+ // "Continue" (spec 003): reopen a finished run's session in-process.
3308
+ .post('/runs/:id/continue', jsonZodValidator(continueSchema, { absent: ({}) }), async (c) => {
3309
+ const { root: repoRoot, store, manager } = c.get('project');
1976
3310
  const id = c.req.param('id');
1977
- if (!store.getRun(id))
3311
+ const run = store.getRun(id);
3312
+ if (!run)
1978
3313
  return c.json({ error: 'not found' }, 404);
1979
3314
  // Bounded resume text (#429); an empty/absent body still just re-runs on the
1980
3315
  // run's current backend, and a runner/model override reopens on that engine (#401).
1981
- const parsed = continueSchema.safeParse(await c.req.json().catch(() => ({})));
1982
- if (!parsed.success) {
1983
- return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
3316
+ const parsed = { data: c.req.valid('json') };
3317
+ if (agentModelsLocked(repoRoot) && parsed.data.model?.trim()) {
3318
+ return c.json({ error: AGENT_MODELS_LOCKED_ERROR }, 409);
1984
3319
  }
3320
+ const blocked = await providerActionError([providerForExistingRun(run, parsed.data.runner)]);
3321
+ if (blocked)
3322
+ return c.json({ error: blocked }, 409);
1985
3323
  const result = manager.continueRun(id, {
1986
3324
  text: parsed.data.text,
1987
3325
  images: parsed.data.images?.map((img) => ({
@@ -1994,10 +3332,10 @@ export function createApp(deps) {
1994
3332
  if (!result.ok)
1995
3333
  return c.json({ error: result.error }, 409);
1996
3334
  return c.json({ continued: true });
1997
- });
1998
- // "Open in terminal" (spec 003): hand the session off to a real terminal —
1999
- // in the task's worktree when it still exists (spec 006).
2000
- api.post('/runs/:id/open-in-cli', async (c) => {
3335
+ })
3336
+ // "Open in terminal" (spec 003): hand the session off to a real terminal —
3337
+ // in the task's worktree when it still exists (spec 006).
3338
+ .post('/runs/:id/open-in-cli', async (c) => {
2001
3339
  const { root: repoRoot, store } = c.get('project');
2002
3340
  const id = c.req.param('id');
2003
3341
  const run = store.getRun(id);
@@ -2010,28 +3348,36 @@ export function createApp(deps) {
2010
3348
  error: 'local handoff is disabled — this cockpit runs in hosted mode (CEZ_REMOTE); resume the session from a machine that has the checkout',
2011
3349
  }, 409);
2012
3350
  }
2013
- const sessionId = [...run.steps].reverse().find((s) => s.sessionId)?.sessionId;
3351
+ const sessionStep = [...run.steps].reverse().find((s) => s.sessionId);
3352
+ const sessionId = sessionStep?.sessionId;
2014
3353
  if (!sessionId)
2015
3354
  return c.json({ error: 'no agent session to resume' }, 409);
3355
+ const blocked = await providerActionError([providerForExistingRun(run)]);
3356
+ if (blocked)
3357
+ return c.json({ error: blocked }, 409);
2016
3358
  const cwd = run.worktreePath && existsSync(run.worktreePath) ? run.worktreePath : repoRoot;
2017
3359
  const command = resumeCommand(run.runner, sessionId);
2018
3360
  // Fails closed on an id we do not recognise — see resumeCommand (#431).
2019
3361
  if (!command)
2020
3362
  return c.json({ error: 'the recorded session id has an unexpected shape' }, 409);
2021
- const opened = await openInTerminal(cwd, command);
3363
+ // The account that OWNS this session, not the project's current one (spec 2026-07-29).
3364
+ const account = await handoffEnv(run.runner ?? 'claude', sessionStep?.profileId);
3365
+ if ('error' in account)
3366
+ return c.json({ error: account.error }, 409);
3367
+ const fallback = handoffFallbackCommand(cwd, command, account.env);
3368
+ // Fail closed for the same reason as the session id: a terminal opened without the
3369
+ // account's config dir resumes nothing and says nothing about why.
3370
+ if (fallback === null) {
3371
+ return c.json({ error: 'this account\'s folder cannot be used in a terminal command' }, 409);
3372
+ }
3373
+ const opened = await openInTerminal(cwd, command, account.env);
2022
3374
  if (!opened) {
2023
- return c.json({
2024
- error: 'no terminal emulator found',
2025
- command: `cd '${cwd}' && ${command}`,
2026
- }, 409);
3375
+ return c.json({ error: 'no terminal emulator found', command: fallback }, 409);
2027
3376
  }
2028
3377
  return c.json({ opened: true, command });
2029
- });
2030
- // "Open in…" session takeover (#open-in): the editors/file-manager/terminal
2031
- // detected on THIS machine. Empty in hosted mode (no local desktop to open).
2032
- api.get('/open-targets', (c) => c.json({ targets: capabilities().localHandoff ? detectOpenTargets() : [] }));
2033
- // Open a run's worktree (or the repo root) in the chosen local app.
2034
- api.post('/runs/:id/open-in', async (c) => {
3378
+ })
3379
+ // Open a run's worktree (or the repo root) in the chosen local app.
3380
+ .post('/runs/:id/open-in', jsonZodValidator(openInSchema), async (c) => {
2035
3381
  const { root: repoRoot, store } = c.get('project');
2036
3382
  const id = c.req.param('id');
2037
3383
  const run = store.getRun(id);
@@ -2044,10 +3390,7 @@ export function createApp(deps) {
2044
3390
  }
2045
3391
  // Follows the safeParse convention (#429); the downstream allowlist match is the real
2046
3392
  // injection guard, this just validates the shape.
2047
- const parsedBody = openInSchema.safeParse(await c.req.json().catch(() => null));
2048
- if (!parsedBody.success) {
2049
- return c.json({ error: parsedBody.error.issues.map((i) => i.message).join('; ') }, 400);
2050
- }
3393
+ const parsedBody = { data: c.req.valid('json') };
2051
3394
  const { target, path: relPath } = parsedBody.data;
2052
3395
  const dir = run.worktreePath && existsSync(run.worktreePath) ? run.worktreePath : repoRoot;
2053
3396
  // Diff pane "open in OS default app" (#365): one worktree file, opened with the platform's
@@ -2105,18 +3448,32 @@ export function createApp(deps) {
2105
3448
  // and what the client's cliTargetResumes now labels. Resume-after-finish is untouched.
2106
3449
  const cliRunner = agentCliRunner(target);
2107
3450
  if (cliRunner) {
3451
+ const blocked = await providerActionError([cliRunner]);
3452
+ if (blocked)
3453
+ return c.json({ error: blocked }, 409);
2108
3454
  const engineOwnsSession = run.status === 'running' || run.status === 'queued' || run.status === 'waiting';
2109
- const sessionId = engineOwnsSession ? undefined : [...run.steps].reverse().find((s) => s.sessionId)?.sessionId;
3455
+ const sessionStep = engineOwnsSession ? undefined : [...run.steps].reverse().find((s) => s.sessionId);
3456
+ const sessionId = sessionStep?.sessionId;
2110
3457
  // An id resumeCommand refuses (#431) degrades to a fresh CLI in the worktree,
2111
3458
  // exactly like a run that never recorded a session.
2112
3459
  const resume = sessionId && cliRunner === (run.runner ?? 'claude') ? resumeCommand(cliRunner, sessionId) : null;
2113
3460
  const command = resume ?? cliRunner;
2114
- const opened = await openInTerminal(dir, command);
3461
+ // BOTH branches carry the account (spec 2026-07-29-agent-profiles): a resume needs the
3462
+ // config dir that holds its session, and a FRESH CLI in this worktree should still open
3463
+ // on the account the project works under — otherwise "Open in → Claude CLI" quietly
3464
+ // hands the user a different subscription than every task in the same project uses.
3465
+ const account = resume
3466
+ ? await handoffEnv(cliRunner, sessionStep?.profileId)
3467
+ : { env: (await resolveProfileEnvForRoot(repoRoot, cliRunner)).env };
3468
+ if ('error' in account)
3469
+ return c.json({ error: account.error }, 409);
3470
+ const fallback = handoffFallbackCommand(dir, command, account.env);
3471
+ if (fallback === null) {
3472
+ return c.json({ error: 'this account\'s folder cannot be used in a terminal command' }, 409);
3473
+ }
3474
+ const opened = await openInTerminal(dir, command, account.env);
2115
3475
  if (!opened) {
2116
- return c.json({
2117
- error: 'no terminal emulator found',
2118
- command: `cd '${dir}' && ${command}`,
2119
- }, 409);
3476
+ return c.json({ error: 'no terminal emulator found', command: fallback }, 409);
2120
3477
  }
2121
3478
  return c.json({ opened: true, path: dir, command });
2122
3479
  }
@@ -2124,10 +3481,10 @@ export function createApp(deps) {
2124
3481
  if (!opened)
2125
3482
  return c.json({ error: `could not open ${target}`, path: dir }, 409);
2126
3483
  return c.json({ opened: true, path: dir });
2127
- });
2128
- // Handoff journal (spec 007): the per-task handoff.md as markdown. 404 only
2129
- // when the task is unknown; a task without a (yet) seeded file returns ''.
2130
- api.get('/runs/:id/handoff', (c) => {
3484
+ })
3485
+ // Handoff journal (spec 007): the per-task handoff.md as markdown. 404 only
3486
+ // when the task is unknown; a task without a (yet) seeded file returns ''.
3487
+ .get('/runs/:id/handoff', (c) => {
2131
3488
  const { dataDir, store } = c.get('project');
2132
3489
  const run = store.getRun(c.req.param('id'));
2133
3490
  if (!run)
@@ -2135,16 +3492,8 @@ export function createApp(deps) {
2135
3492
  return c.text(readHandoff(dataDir, run.id), 200, {
2136
3493
  'content-type': 'text/markdown; charset=utf-8',
2137
3494
  });
2138
- });
2139
- // Agent screenshots — image blocks the run manager persisted out of tool
2140
- // results (persistImage). `basename` pins reads inside the run's own dir.
2141
- const IMAGE_TYPES = {
2142
- png: 'image/png',
2143
- jpg: 'image/jpeg',
2144
- webp: 'image/webp',
2145
- gif: 'image/gif',
2146
- };
2147
- api.get('/runs/:id/images/:file', (c) => {
3495
+ })
3496
+ .get('/runs/:id/images/:file', (c) => {
2148
3497
  const { dataDir, store } = c.get('project');
2149
3498
  const run = store.getRun(c.req.param('id'));
2150
3499
  if (!run)
@@ -2160,9 +3509,9 @@ export function createApp(deps) {
2160
3509
  'cache-control': 'private, max-age=31536000, immutable',
2161
3510
  },
2162
3511
  });
2163
- });
2164
- // Task diff (spec 006): what this run changed — its worktree vs its base.
2165
- api.get('/runs/:id/diff', async (c) => {
3512
+ })
3513
+ // Task diff (spec 006): what this run changed — its worktree vs its base.
3514
+ .get('/runs/:id/diff', async (c) => {
2166
3515
  const { store } = c.get('project');
2167
3516
  const run = store.getRun(c.req.param('id'));
2168
3517
  if (!run)
@@ -2171,94 +3520,111 @@ export function createApp(deps) {
2171
3520
  return c.text('(no worktree — this task ran directly in the repo working tree)');
2172
3521
  }
2173
3522
  return c.text(await worktreeDiff(run.worktreePath, run.baseBranch ?? 'HEAD'));
2174
- });
2175
- // ---- session git view (redesign R5 Step 1.2 — §"Git/session API additions").
2176
- // Structured sibling of the text-blob /diff above (which stays untouched —
2177
- // protected surface). Same worktree/base resolution; every predictable git
2178
- // failure degrades to 409 + human-readable reason, 404 only for unknown ids.
2179
- const worktreeOf = (run) => run.worktreePath && existsSync(run.worktreePath) ? run.worktreePath : null;
2180
- const NO_WORKTREE = 'no worktree — this task ran directly in the repo working tree';
2181
- api.get('/runs/:id/changes', async (c) => {
2182
- const { store } = c.get('project');
3523
+ })
3524
+ .get('/runs/:id/changes', async (c) => {
3525
+ const { root: repoRoot, store } = c.get('project');
2183
3526
  const run = store.getRun(c.req.param('id'));
2184
3527
  if (!run)
2185
3528
  return c.json({ error: 'not found' }, 404);
2186
- const worktree = worktreeOf(run);
2187
- if (!worktree)
3529
+ const workingDirectory = workingDirectoryOf(run, repoRoot);
3530
+ if (!workingDirectory)
2188
3531
  return c.json({ error: NO_WORKTREE }, 409);
2189
- const result = await collectChanges(worktree, run.baseBranch ?? 'HEAD', { taskBranch: run.branch });
3532
+ const result = await collectChanges(workingDirectory, run.baseBranch ?? 'HEAD', {
3533
+ taskBranch: run.branch,
3534
+ // A read-only GET against the user's real checkout must never modify its index.
3535
+ intentToAdd: run.worktreePath ? undefined : false,
3536
+ });
2190
3537
  if (!result.ok)
2191
3538
  return c.json({ error: result.error }, 409);
2192
3539
  return c.json(result.changes);
2193
- });
2194
- // The run's own commits (<base>..HEAD on the worktree branch) — the Commits tab.
2195
- api.get('/runs/:id/commits', async (c) => {
2196
- const { store } = c.get('project');
3540
+ })
3541
+ // The run's own commits (<base>..HEAD on the worktree branch) — the Commits tab.
3542
+ .get('/runs/:id/commits', async (c) => {
3543
+ const { root: repoRoot, store } = c.get('project');
2197
3544
  const run = store.getRun(c.req.param('id'));
2198
3545
  if (!run)
2199
3546
  return c.json({ error: 'not found' }, 404);
2200
- const worktree = worktreeOf(run);
2201
- if (!worktree)
3547
+ const workingDirectory = workingDirectoryOf(run, repoRoot);
3548
+ if (!workingDirectory)
2202
3549
  return c.json({ error: NO_WORKTREE }, 409);
2203
- const result = await collectRunCommits(worktree, run.baseBranch ?? 'HEAD');
3550
+ const result = await collectRunCommits(workingDirectory, run.baseBranch ?? 'HEAD');
2204
3551
  if (!result.ok)
2205
3552
  return c.json({ error: result.error }, 409);
2206
3553
  return c.json({ commits: result.commits });
2207
- });
2208
- // One of the run's commits, structured like the Changes tab (reuses collectCommitChanges).
2209
- api.get('/runs/:id/commit/:sha', async (c) => {
2210
- const { store } = c.get('project');
3554
+ })
3555
+ // One of the run's commits, structured like the Changes tab (reuses collectCommitChanges).
3556
+ .get('/runs/:id/commit/:sha', async (c) => {
3557
+ const { root: repoRoot, store } = c.get('project');
2211
3558
  const run = store.getRun(c.req.param('id'));
2212
3559
  if (!run)
2213
3560
  return c.json({ error: 'not found' }, 404);
2214
- const worktree = worktreeOf(run);
2215
- if (!worktree)
3561
+ const workingDirectory = workingDirectoryOf(run, repoRoot);
3562
+ if (!workingDirectory)
2216
3563
  return c.json({ error: NO_WORKTREE }, 409);
2217
- const result = await collectCommitChanges(worktree, c.req.param('sha'));
3564
+ const result = await collectCommitChanges(workingDirectory, c.req.param('sha'));
2218
3565
  if (!result.ok)
2219
3566
  return c.json({ error: result.error }, 409);
2220
3567
  return c.json(result.commit);
2221
- });
2222
- // Files tab: directory listing (path omitted or a dir) or file content
2223
- // (size-capped, binary flagged). Traversal-safe — readWorktreePath rejects
2224
- // anything escaping the worktree. `raw=1` (R5 Step 1.6) serves the BYTES of
2225
- // image files only, for the preview's inline <img> — never HTML/JS/etc., so
2226
- // no worktree file can become a same-origin document, and never past the
2227
- // size cap. The no-script CSP neutralizes SVG opened as a top-level URL.
2228
- api.get('/runs/:id/files', async (c) => {
2229
- const { store } = c.get('project');
3568
+ })
3569
+ // Files tab: directory listing (path omitted or a dir) or file content
3570
+ // (size-capped, binary flagged). Traversal-safe — readWorktreePath rejects
3571
+ // anything escaping the worktree. `raw=1` (R5 Step 1.6) serves the BYTES of
3572
+ // image files only, for the preview's inline <img> — never HTML/JS/etc., so
3573
+ // no worktree file can become a same-origin document, and never past the
3574
+ // size cap. The no-script CSP neutralizes SVG opened as a top-level URL.
3575
+ //
3576
+ // An `Accept` that asks for images reaches the same raw branch without the flag — which is
3577
+ // what an `<img>` sends — while the flag still wins whenever it is present and `*<slash>*`
3578
+ // (every `fetch`) still gets the JSON listing. See `negotiate`.
3579
+ .get('/runs/:id/files', queryZodValidator(z.object({ path: queryValue, raw: queryValue })), async (c) => {
3580
+ const { root: repoRoot, store } = c.get('project');
3581
+ const query = c.req.valid('query');
3582
+ c.header('vary', 'Accept');
3583
+ const wantsRaw = query.raw !== undefined
3584
+ ? query.raw === '1'
3585
+ : negotiate(c.req.header('accept'), FILE_FORMATS) === 'image/*';
2230
3586
  const run = store.getRun(c.req.param('id'));
2231
3587
  if (!run)
2232
3588
  return c.json({ error: 'not found' }, 404);
2233
- const worktree = worktreeOf(run);
2234
- if (!worktree)
3589
+ const workingDirectory = workingDirectoryOf(run, repoRoot);
3590
+ if (!workingDirectory)
2235
3591
  return c.json({ error: NO_WORKTREE }, 409);
2236
- const result = await readWorktreePath(worktree, c.req.query('path') ?? '');
3592
+ const result = await readWorktreePath(workingDirectory, query.path ?? '');
2237
3593
  if (result.kind === 'invalid' || result.kind === 'missing') {
2238
3594
  return c.json({ error: result.error }, 409);
2239
3595
  }
2240
3596
  if (result.kind === 'dir') {
2241
3597
  return c.json({
3598
+ // `as const` or the literal widens to `string` during Hono's route-type inference,
3599
+ // which erases the discriminant a consumer narrows on — `entry.type === 'dir'` then
3600
+ // leaves `never` and every field access on it fails. The wire was always 'dir'.
2242
3601
  type: 'dir',
2243
3602
  path: result.path,
2244
3603
  entries: result.entries,
2245
3604
  });
2246
3605
  }
2247
- if (c.req.query('raw') === '1') {
3606
+ if (wantsRaw) {
2248
3607
  const mime = imageMimeType(result.path);
2249
- if (!mime)
2250
- return c.json({ error: `raw serving is limited to images: ${result.path}` }, 409);
2251
- if (result.tooLarge) {
2252
- return c.json({
2253
- error: `file too large to serve raw (${result.size} bytes): ${result.path}`,
2254
- }, 409);
3608
+ if (mime === null || result.tooLarge) {
3609
+ // `?raw=1` ASKED for bytes, so it hears why it cannot have them — that 409 and its
3610
+ // wording are the protected surface (§2). An `Accept` is only a preference, so a
3611
+ // resource with no image representation falls THROUGH to the JSON answer below rather
3612
+ // than turning a browser's navigation to a text file into an error.
3613
+ if (query.raw !== undefined) {
3614
+ const error = mime === null
3615
+ ? `raw serving is limited to images: ${result.path}`
3616
+ : `file too large to serve raw (${result.size} bytes): ${result.path}`;
3617
+ return c.json({ error }, 409);
3618
+ }
3619
+ }
3620
+ else {
3621
+ const bytes = await readFile(join(workingDirectory, result.path));
3622
+ return c.body(new Uint8Array(bytes).buffer, 200, {
3623
+ 'content-type': mime,
3624
+ 'x-content-type-options': 'nosniff',
3625
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; sandbox",
3626
+ });
2255
3627
  }
2256
- const bytes = await readFile(join(worktree, result.path));
2257
- return c.body(new Uint8Array(bytes).buffer, 200, {
2258
- 'content-type': mime,
2259
- 'x-content-type-options': 'nosniff',
2260
- 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; sandbox",
2261
- });
2262
3628
  }
2263
3629
  return c.json({
2264
3630
  type: 'file',
@@ -2268,8 +3634,8 @@ export function createApp(deps) {
2268
3634
  tooLarge: result.tooLarge,
2269
3635
  ...(result.content !== undefined ? { content: result.content } : {}),
2270
3636
  });
2271
- });
2272
- api.post('/runs/:id/git/commit', async (c) => {
3637
+ })
3638
+ .post('/runs/:id/git/commit', jsonZodValidator(gitCommitSchema), async (c) => {
2273
3639
  const { store } = c.get('project');
2274
3640
  const run = store.getRun(c.req.param('id'));
2275
3641
  if (!run)
@@ -2277,16 +3643,13 @@ export function createApp(deps) {
2277
3643
  const worktree = worktreeOf(run);
2278
3644
  if (!worktree)
2279
3645
  return c.json({ error: NO_WORKTREE }, 409);
2280
- const parsed = gitCommitSchema.safeParse(await c.req.json().catch(() => null));
2281
- if (!parsed.success) {
2282
- return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
2283
- }
3646
+ const parsed = { data: c.req.valid('json') };
2284
3647
  const result = await commitAll(worktree, parsed.data.message);
2285
3648
  if (!result.ok)
2286
3649
  return c.json({ error: result.error }, 409);
2287
3650
  return c.json({ committed: true, sha: result.sha });
2288
- });
2289
- api.post('/runs/:id/git/push', async (c) => {
3651
+ })
3652
+ .post('/runs/:id/git/push', async (c) => {
2290
3653
  const { store } = c.get('project');
2291
3654
  const run = store.getRun(c.req.param('id'));
2292
3655
  if (!run)
@@ -2303,12 +3666,12 @@ export function createApp(deps) {
2303
3666
  remote: result.remote,
2304
3667
  upstreamSet: result.upstreamSet,
2305
3668
  });
2306
- });
2307
- // Draft PR from the review gate (spec 009): final autosave → push →
2308
- // `gh pr create --draft`; on success the run completes as done with the PR
2309
- // badge. Failures come back as 409 with a `manual` merge command the GUI
2310
- // shows next to the toast. CEZ_DRY_RUN=1 fakes the URL (no push, no gh).
2311
- api.post('/runs/:id/pr', async (c) => {
3669
+ })
3670
+ // Draft PR from the review gate (spec 009): final autosave → push →
3671
+ // `gh pr create --draft`; on success the run completes as done with the PR
3672
+ // badge. Failures come back as 409 with a `manual` merge command the GUI
3673
+ // shows next to the toast. CEZ_DRY_RUN=1 fakes the URL (no push, no gh).
3674
+ .post('/runs/:id/pr', async (c) => {
2312
3675
  const { root: repoRoot, dataDir, store, manager } = c.get('project');
2313
3676
  const id = c.req.param('id');
2314
3677
  const run = store.getRun(id);
@@ -2339,10 +3702,10 @@ export function createApp(deps) {
2339
3702
  message: `draft PR created: ${outcome.url}${outcome.dryRun ? ' (dry run — no real PR)' : ''}`,
2340
3703
  });
2341
3704
  return c.json({ url: outcome.url, dryRun: outcome.dryRun }, 201);
2342
- });
2343
- // Archived tasks keep their worktree for inspection; this is the explicit
2344
- // "🧹 Remove worktree" cleanup (spec 006).
2345
- api.post('/runs/:id/remove-worktree', async (c) => {
3705
+ })
3706
+ // Archived tasks keep their worktree for inspection; this is the explicit
3707
+ // "🧹 Remove worktree" cleanup (spec 006).
3708
+ .post('/runs/:id/remove-worktree', async (c) => {
2346
3709
  const { root: repoRoot, store, manager } = c.get('project');
2347
3710
  const id = c.req.param('id');
2348
3711
  const run = store.getRun(id);
@@ -2354,8 +3717,8 @@ export function createApp(deps) {
2354
3717
  await removeWorktree(repoRoot, run.worktreePath, run.branch);
2355
3718
  store.updateRun(id, { worktreePath: undefined, branch: undefined });
2356
3719
  return c.json({ removed: true });
2357
- });
2358
- api.delete('/runs/:id', async (c) => {
3720
+ })
3721
+ .delete('/runs/:id', async (c) => {
2359
3722
  const { root: repoRoot, store, manager } = c.get('project');
2360
3723
  const id = c.req.param('id');
2361
3724
  if (manager.isActive(id))
@@ -2368,11 +3731,116 @@ export function createApp(deps) {
2368
3731
  await removeWorktree(repoRoot, run.worktreePath, run.branch);
2369
3732
  return store.deleteRun(id) ? c.json({ deleted: true }) : c.json({ error: 'not found' }, 404);
2370
3733
  });
2371
- // ---- worktree management panel (#483) --------------------------------------
2372
- // List materialized task worktrees with disk usage + retention state, and a
2373
- // "Reclaim now" action. Both additive; the per-row delete reuses the existing
2374
- // /api/runs/:id/remove-worktree route above.
2375
- api.get('/worktrees', async (c) => {
3734
+ // ---- parallel variants (spec 010) -----------------------------------------
3735
+ const groupRuns = (store, groupId) => store
3736
+ .listRuns()
3737
+ .filter((r) => r.groupId === groupId)
3738
+ .sort((a, b) => (a.variant ?? '').localeCompare(b.variant ?? ''));
3739
+ // ---- chained family: variant groups (project-scoped) ----
3740
+ const groupsRoutes = new Hono()
3741
+ .get('/groups/:groupId', async (c) => {
3742
+ const { dataDir, store } = c.get('project');
3743
+ const runs = groupRuns(store, c.req.param('groupId'));
3744
+ if (runs.length === 0)
3745
+ return c.json({ error: 'not found' }, 404);
3746
+ const detailed = await Promise.all(runs.map(async (r) => ({
3747
+ id: r.id,
3748
+ variant: r.variant ?? '?',
3749
+ title: r.title,
3750
+ status: r.status,
3751
+ archived: r.archived,
3752
+ tokensUsed: r.tokensUsed,
3753
+ ...(r.inputTokens !== undefined ? { inputTokens: r.inputTokens } : {}),
3754
+ ...(r.outputTokens !== undefined ? { outputTokens: r.outputTokens } : {}),
3755
+ ...(r.costUsd !== undefined ? { costUsd: r.costUsd } : {}),
3756
+ diffStat: r.worktreePath && existsSync(r.worktreePath)
3757
+ ? await worktreeDiffStat(r.worktreePath, r.baseBranch ?? 'HEAD')
3758
+ : '',
3759
+ handoffExcerpt: handoffProgressExcerpt(readHandoff(dataDir, r.id)),
3760
+ })));
3761
+ return c.json({
3762
+ groupId: c.req.param('groupId'),
3763
+ runs: detailed,
3764
+ });
3765
+ })
3766
+ // "Pick this one": the winner rests at `review` (spec 009 takes it from
3767
+ // there — send back / draft PR / finish); the losers are cancelled if
3768
+ // alive, archived, and their worktrees + branches removed.
3769
+ .post('/groups/:groupId/pick', jsonZodValidator(pickSchema), async (c) => {
3770
+ const { root: repoRoot, dataDir, store, manager } = c.get('project');
3771
+ const runs = groupRuns(store, c.req.param('groupId'));
3772
+ if (runs.length === 0)
3773
+ return c.json({ error: 'not found' }, 404);
3774
+ const parsed = { data: c.req.valid('json') };
3775
+ const winner = runs.find((r) => r.id === parsed.data.runId);
3776
+ if (!winner)
3777
+ return c.json({ error: 'runId is not part of this group' }, 404);
3778
+ if (manager.isActive(winner.id)) {
3779
+ return c.json({ error: 'this variant is still active — wait for it to finish first' }, 409);
3780
+ }
3781
+ // Winner: a non-review terminal state with a non-empty diff flips to
3782
+ // `review` (the settleSuccess rule) — but only when the review gate applies
3783
+ // (#489): it is enabled (`reviewGateEnabled`, default off) AND the winner is
3784
+ // not autonomous. An autonomous / gate-off winner keeps its `done` state with
3785
+ // the diff left in the worktree; an empty diff (or no worktree) stays too.
3786
+ if (winner.status !== 'review' &&
3787
+ winner.worktreePath &&
3788
+ existsSync(winner.worktreePath) &&
3789
+ winner.autonomous !== true &&
3790
+ reviewGateEnabled(await loadConfig(repoRoot))) {
3791
+ const diff = await worktreeDiff(winner.worktreePath, winner.baseBranch ?? 'HEAD');
3792
+ if (diff.trim().length > 0 && !diff.startsWith('(diff failed')) {
3793
+ store.updateRun(winner.id, { status: 'review' });
3794
+ }
3795
+ }
3796
+ const losers = runs.filter((r) => r.id !== winner.id);
3797
+ store.appendEvent(winner.id, {
3798
+ type: 'lifecycle',
3799
+ message: `picked from ${runs.length} variants — ${losers.length} other variant(s) archived`,
3800
+ });
3801
+ appendHandoffHeartbeat(dataDir, winner.id, `picked from ${runs.length} variants`);
3802
+ for (const loser of losers) {
3803
+ if (manager.isActive(loser.id))
3804
+ manager.cancel(loser.id);
3805
+ if (loser.worktreePath)
3806
+ await removeWorktree(repoRoot, loser.worktreePath, loser.branch);
3807
+ store.updateRun(loser.id, { worktreePath: undefined, branch: undefined });
3808
+ store.setArchived(loser.id, true);
3809
+ store.appendEvent(loser.id, {
3810
+ type: 'lifecycle',
3811
+ message: `variant ${winner.variant ?? '?'} was picked — this variant is archived, its worktree removed`,
3812
+ });
3813
+ }
3814
+ // Spread: `getRun` may answer undefined, and an undefined VALUE is dropped by
3815
+ // JSON.stringify — so writing the key unconditionally typed the route as sending a key it
3816
+ // does not. contract/workflows.ts says `.optional()`, which is what a client receives.
3817
+ const picked = store.getRun(winner.id);
3818
+ return c.json({ ...(picked !== undefined ? { winner: picked } : {}) });
3819
+ });
3820
+ // ---- chained family: open-targets (project-scoped) ----
3821
+ const openTargetsRoutes = new Hono()
3822
+ .get('/open-targets', (c) => c.json({ targets: capabilities().localHandoff ? detectOpenTargets() : [] }));
3823
+ // Agent screenshots — image blocks the run manager persisted out of tool
3824
+ // results (persistImage). `basename` pins reads inside the run's own dir.
3825
+ const IMAGE_TYPES = {
3826
+ png: 'image/png',
3827
+ jpg: 'image/jpeg',
3828
+ webp: 'image/webp',
3829
+ gif: 'image/gif',
3830
+ };
3831
+ // ---- session git view (redesign R5 Step 1.2 — §"Git/session API additions").
3832
+ // Structured sibling of the text-blob /diff above (which stays untouched —
3833
+ // protected surface). Isolated runs read their worktree; worktree-off runs
3834
+ // read the repo checkout they executed in. Every predictable git failure
3835
+ // degrades to 409 + human-readable reason, 404 only for unknown ids.
3836
+ const worktreeOf = (run) => run.worktreePath && existsSync(run.worktreePath) ? run.worktreePath : null;
3837
+ const workingDirectoryOf = (run, repoRoot) => run.worktree === false
3838
+ ? repoRoot
3839
+ : worktreeOf(run);
3840
+ const NO_WORKTREE = 'no worktree — this task ran directly in the repo working tree';
3841
+ // ---- chained family: worktrees (project-scoped) ----
3842
+ const worktreesRoutes = new Hono()
3843
+ .get('/worktrees', async (c) => {
2376
3844
  const { root: repoRoot, store } = c.get('project');
2377
3845
  // The keep-limit the panel reports is the one the enforcer will actually
2378
3846
  // apply — inherited from the workspace default when this repo sets none.
@@ -2392,61 +3860,69 @@ export function createApp(deps) {
2392
3860
  const totalBytes = worktrees.some((w) => w.sizeBytes === null)
2393
3861
  ? null
2394
3862
  : worktrees.reduce((sum, w) => sum + (w.sizeBytes ?? 0), 0);
2395
- return c.json({ worktrees, totalBytes, keep });
2396
- });
2397
- const reclaimBodySchema = z.object({}).passthrough();
2398
- api.post('/worktrees/reclaim', async (c) => {
3863
+ return c.json({ worktrees, totalBytes, keep });
3864
+ })
3865
+ .post('/worktrees/reclaim', jsonZodValidator(() => reclaimBodySchema, { absent: ({}), message: 'invalid body' }), async (c) => {
2399
3866
  const { root: repoRoot, store } = c.get('project');
2400
- // Accept an empty or `{}` body; retention is best-effort, so 200 always.
2401
- const parsed = reclaimBodySchema.safeParse(await c.req.json().catch(() => ({})));
2402
- if (!parsed.success)
2403
- return c.json({ error: 'invalid body' }, 400);
3867
+ // The body is validated (an empty or `{}` one is accepted) but carries nothing this
3868
+ // handler reads; retention is best-effort, so 200 always.
2404
3869
  const reclaimed = await reclaimWorktrees(repoRoot, store, await resolveWorktreeRetention(repoRoot));
2405
3870
  return c.json({ reclaimed });
2406
3871
  });
2407
- // ---- inbox (spec 007) ------------------------------------------------------
2408
- // Opt-in via CEZ_FOLLOWUPS=1 (#471). Off, the reader degrades to an empty
2409
- // inbox (a 404 would make old clients surface an error for a feature that is
2410
- // merely switched off) and the mutators 409 as defense in depth — the shape
2411
- // the hosted-mode open-in-* handlers already use. Existing todos.json entries
2412
- // are never touched, so flipping the env back on restores them.
2413
- api.get('/todos', async (c) => c.json(capabilities().followups ? await readTodos(c.get('project').dataDir) : []));
2414
- // Check off = delete the entry.
2415
- api.delete('/todos/:id', async (c) => {
3872
+ const reclaimBodySchema = z.object({}).passthrough();
3873
+ /**
3874
+ * "The inbox is on and this entry exists" — the 409/404 half of `POST /todos/:id/start`, lifted
3875
+ * out of the handler and in FRONT of the body validator.
3876
+ *
3877
+ * That position is the whole point. The route's contract is that an unknown id 404s before the
3878
+ * body is looked at, and Hono only records a body in the route type when it is validated as
3879
+ * MIDDLEWARE — which necessarily runs before the handler. Registering this guard first satisfies
3880
+ * both: the documented status order is unchanged, and `startTodoSchema` becomes visible to
3881
+ * `AppType` (and so to `hc`) instead of being parsed invisibly inside the handler.
3882
+ *
3883
+ * Deliberately NOT annotated with a return type: the inferred one carries the two typed
3884
+ * responses, which is what keeps the 409 and 404 branches in the route's schema for the client.
3885
+ */
3886
+ const todoMustExist = async (c, next) => {
3887
+ if (!capabilities().followups)
3888
+ return c.json({ error: FOLLOWUPS_OFF }, 409);
3889
+ const todo = (await readTodos(c.get('project').dataDir)).find((t) => t.id === c.req.param('id'));
3890
+ if (!todo)
3891
+ return c.json({ error: 'not found' }, 404);
3892
+ c.set('todo', todo);
3893
+ await next();
3894
+ };
3895
+ // ---- chained family: follow-up inbox / todos (project-scoped) ----
3896
+ const todosRoutes = new Hono()
3897
+ .get('/todos', async (c) => c.json(capabilities().followups ? await readTodos(c.get('project').dataDir) : []))
3898
+ // Check off = delete the entry.
3899
+ .delete('/todos/:id', async (c) => {
2416
3900
  const { dataDir } = c.get('project');
2417
3901
  if (!capabilities().followups)
2418
3902
  return c.json({ error: FOLLOWUPS_OFF }, 409);
2419
3903
  const removed = await removeTodo(dataDir, c.req.param('id'));
2420
3904
  return removed ? c.json({ removed: true }) : c.json({ error: 'not found' }, 404);
2421
- });
2422
- // "▶ Run": turn an inbox entry into a task — a one-off single-step workflow
2423
- // around the suggested skill when it exists, plain quick-task otherwise.
2424
- api.post('/todos/:id/start', async (c) => {
3905
+ })
3906
+ // "▶ Run": turn an inbox entry into a task — a one-off single-step workflow
3907
+ // around the suggested skill when it exists, plain quick-task otherwise.
3908
+ //
3909
+ // TWO middlewares, and their ORDER is the contract. This route's documented status order
3910
+ // (pinned by todos-start.test.ts) is that a disabled inbox 409s and an unknown id 404s BEFORE
3911
+ // the body is looked at — which is why the body used to be parsed inline, invisible to `hc`.
3912
+ // Hono runs route middleware in registration order, so `todoMustExist` FIRST keeps that order
3913
+ // exactly while `jsonZodValidator` second is what records the body in the route type.
3914
+ //
3915
+ // The two no-body cases the old inline parse distinguished are carried by the validator's
3916
+ // `absent`/`malformed` options: no body at all is `undefined` (the pre-#401 bodyless POST,
3917
+ // which the optional schema accepts → 201), a truncated payload is `null` (which it rejects
3918
+ // → 400, rather than passing as "no body" and silently starting a run).
3919
+ .post('/todos/:id/start', todoMustExist, jsonZodValidator(startTodoSchema, { absent: undefined, malformed: null }), async (c) => {
2425
3920
  const { root: repoRoot, dataDir, manager } = c.get('project');
2426
- if (!capabilities().followups)
2427
- return c.json({ error: FOLLOWUPS_OFF }, 409);
2428
3921
  const id = c.req.param('id');
2429
- const todo = (await readTodos(dataDir)).find((t) => t.id === id);
2430
- if (!todo)
2431
- return c.json({ error: 'not found' }, 404);
2432
- // Body is optional and read exactly once (runner/model #401 + prompt #413 share it). A
2433
- // request with none at all (the pre-pills/pre-composer client) stays `undefined`, same as an
2434
- // empty `{}`. A body that IS present but is not valid JSON becomes `null`, which the schema
2435
- // rejects → 400 (the `.catch(() => null)` pattern every other mutating route uses); mapping
2436
- // it to `undefined` too would let a broken payload pass as "no body" and silently 201.
2437
- const rawBody = await c.req.text().catch(() => '');
2438
- let body;
2439
- if (rawBody.trim().length > 0) {
2440
- try {
2441
- body = JSON.parse(rawBody);
2442
- }
2443
- catch {
2444
- body = null;
2445
- }
2446
- }
2447
- const parsed = startTodoSchema.safeParse(body);
2448
- if (!parsed.success) {
2449
- return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
3922
+ const todo = c.get('todo');
3923
+ const parsed = { data: c.req.valid('json') };
3924
+ if (agentModelsLocked(repoRoot) && parsed.data?.model?.trim()) {
3925
+ return c.json({ error: AGENT_MODELS_LOCKED_ERROR }, 409);
2450
3926
  }
2451
3927
  if (todo.startedTaskId)
2452
3928
  return c.json({ error: 'already started' }, 409);
@@ -2476,6 +3952,10 @@ export function createApp(deps) {
2476
3952
  const { workflows } = await loadWorkflows(repoRoot);
2477
3953
  workflow = workflows.find((w) => w.name === 'quick-task') ?? QUICK_TASK_WORKFLOW;
2478
3954
  }
3955
+ const fallback = parsed.data?.runner ?? (await loadConfig(repoRoot)).defaultRunner;
3956
+ const blocked = await providerActionError(providersRequiredByWorkflow(workflow, fallback));
3957
+ if (blocked)
3958
+ return c.json({ error: blocked }, 409);
2479
3959
  const run = manager.startRun(workflow, {
2480
3960
  task,
2481
3961
  runner: parsed.data?.runner,
@@ -2484,10 +3964,9 @@ export function createApp(deps) {
2484
3964
  await markStarted(dataDir, id, run.id);
2485
3965
  return c.json({ run }, 201);
2486
3966
  });
2487
- // Per-run SSE: full replay from the NDJSON file, then live events. The
2488
- // listener attaches before the replay and buffers, so nothing emitted
2489
- // during the replay is lost or duplicated (dedup by seq).
2490
- api.get('/runs/:id/events', (c) => {
3967
+ // ---- chained family: SSE streams (project-scoped) ----
3968
+ const sseRoutes = new Hono()
3969
+ .get('/runs/:id/events', (c) => {
2491
3970
  const { store } = c.get('project');
2492
3971
  const id = c.req.param('id');
2493
3972
  if (!store.getRun(id))
@@ -2543,13 +4022,13 @@ export function createApp(deps) {
2543
4022
  await stream.sleep(15_000);
2544
4023
  }
2545
4024
  });
2546
- });
2547
- // Global SSE: run-summary updates for the list view + inbox changes.
2548
- // Scoped `/p/:projectId/events` carries that project's stream in today's
2549
- // shape; the legacy unprefixed alias stays bound to the boot project ONLY
2550
- // (spec "Legacy aliases" — widening it would be a silent behavioral break;
2551
- // the all-project stream arrives as `/api/workspace/events` in step 2.8).
2552
- api.get('/events', (c) => {
4025
+ })
4026
+ // Global SSE: run-summary updates for the list view + inbox changes.
4027
+ // Scoped `/p/:projectId/events` carries that project's stream in today's
4028
+ // shape; the legacy unprefixed alias stays bound to the boot project ONLY
4029
+ // (spec "Legacy aliases" — widening it would be a silent behavioral break;
4030
+ // the all-project stream arrives as `/api/workspace/events` in step 2.8).
4031
+ .get('/events', (c) => {
2553
4032
  const { dataDir, store } = c.get('project');
2554
4033
  return streamSSENoBuffer(c, async (stream) => {
2555
4034
  const onRun = (run) => void stream.writeSSE({ event: 'run', data: JSON.stringify(run) });
@@ -2595,22 +4074,9 @@ export function createApp(deps) {
2595
4074
  }
2596
4075
  });
2597
4076
  });
2598
- // ---- workspace SSE (multi-project spec, step 2.8) ------------------------
2599
- // The cockpit's future single EventSource: one stream, every project.
2600
- // WORKSPACE-level (single-mount on `app`, never mirrored under /api/p/).
2601
- // Same event names as the per-project stream, but every payload is stamped
2602
- // with the owning `project` id — additively where the legacy payload is an
2603
- // object (`run` grows a `project` key, `run-deleted` becomes
2604
- // `{id, project}`), wrapped where it is not (`todos` → `{project, items}`,
2605
- // `usage` → `{project, usage}` — a bare array/record has nowhere to carry a
2606
- // stamp). The legacy `/api/events` alias above keeps its UN-stamped,
2607
- // boot-filtered shape — that stream is a protected surface.
2608
- //
2609
- // Subscribing NEVER force-instantiates a project: only the boot context
2610
- // (always live) and already-built lazy contexts are attached at connect;
2611
- // contexts built later join via the `onContextBuilt` hook, so a project's
2612
- // first API touch makes its events flow to streams already open.
2613
- app.get('/api/workspace/events', (c) => {
4077
+ // ---- chained family: workspace SSE stream (workspace-level) ----
4078
+ const workspaceEventsRoutes = new Hono()
4079
+ .get('/workspace/events', (c) => {
2614
4080
  return streamSSENoBuffer(c, async (stream) => {
2615
4081
  // One detach bundle per attached project — the id guard makes a double
2616
4082
  // attach (connect-time snapshot vs. the built hook) impossible.
@@ -2682,11 +4148,12 @@ export function createApp(deps) {
2682
4148
  }
2683
4149
  });
2684
4150
  // Workspace-level events (project-added / project-removed /
2685
- // checkout-progress) — relayed verbatim under their own names. A
2686
- // removal also drops the project's attach entry: the id guard in
2687
- // `attach` would otherwise pin the DISPOSED context forever, so a
2688
- // project removed and re-added on the same slug would rebuild a fresh
2689
- // context whose events never reach this already-open stream.
4151
+ // checkout-progress plus host-wide unstamped provider-status) — relayed
4152
+ // verbatim under their own names. A removal also drops the project's
4153
+ // attach entry: the id guard in `attach` would otherwise pin the
4154
+ // DISPOSED context forever, so a project removed and re-added on the
4155
+ // same slug would rebuild a fresh context whose events never reach this
4156
+ // already-open stream.
2690
4157
  const offWorkspace = workspaceEvents.on((event, data) => {
2691
4158
  if (event === 'project-removed') {
2692
4159
  const removed = data.id;
@@ -2711,23 +4178,25 @@ export function createApp(deps) {
2711
4178
  }
2712
4179
  });
2713
4180
  });
2714
- // ---- GitHub tab ------------------------------------------------------------
2715
- // Issues + PRs of the repo's origin, read through the logged-in `gh` CLI.
2716
- // Degrades to `{available:false, reason}` — no gh / no remote / offline all
2717
- // just render as a hint in the tab, never an error.
2718
- api.get('/github', async (c) => {
4181
+ // ---- chained family: GitHub (project-scoped) ----
4182
+ // These sit ABOVE the routes rather than with the family's other schemas below it, because a
4183
+ // validator argument is evaluated when the route is REGISTERED — a schema declared further down
4184
+ // would be in its temporal dead zone. (The schemas below are all read inside a handler, or
4185
+ // passed as a thunk, which defers them past that point.)
4186
+ const mergeNumberParams = z.object({ number: z.coerce.number().int().positive() });
4187
+ const prChangesParams = z.object({ number: z.coerce.number().int().positive().safe() });
4188
+ const prChangesQuery = z.object({ refresh: queryValue.refine((v) => v === undefined || v === '1') });
4189
+ const githubRoutes = new Hono()
4190
+ .get('/github',
4191
+ // `limit` stays a bare string: the handler's `Number.parseInt`/`Number.isFinite` fallback to
4192
+ // 30 already accepts `?limit=banana`, and a numeric schema would 400 it instead.
4193
+ queryZodValidator(z.object({ limit: queryValue, refresh: queryValue })), async (c) => {
2719
4194
  const { root: repoRoot } = c.get('project');
2720
- const limit = Number.parseInt(c.req.query('limit') ?? '', 10);
2721
- return c.json(await fetchGithub(repoRoot, c.req.query('refresh') === '1', Number.isFinite(limit) ? limit : 30));
2722
- });
2723
- // The full comment thread for one issue/PR (#499). Additive sibling of /api/github — lazy
2724
- // (fetched only while a detail view is open), zod-validated params, 400 on garbage, and the
2725
- // same in-payload availability degrade (gh missing / offline / 404 all render as a hint).
2726
- const commentsParams = z.object({
2727
- kind: z.enum(['issue', 'pr']),
2728
- number: z.coerce.number().int().positive(),
2729
- });
2730
- api.get('/github/comments/:kind/:number', async (c) => {
4195
+ const query = c.req.valid('query');
4196
+ const limit = Number.parseInt(query.limit ?? '', 10);
4197
+ return c.json(await fetchGithub(repoRoot, query.refresh === '1', Number.isFinite(limit) ? limit : 30));
4198
+ })
4199
+ .get('/github/comments/:kind/:number', queryZodValidator(refreshQuery), async (c) => {
2731
4200
  const { root: repoRoot } = c.get('project');
2732
4201
  const parsed = commentsParams.safeParse({
2733
4202
  kind: c.req.param('kind'),
@@ -2735,10 +4204,86 @@ export function createApp(deps) {
2735
4204
  });
2736
4205
  if (!parsed.success)
2737
4206
  return c.json({ error: 'invalid kind or number' }, 400);
2738
- return c.json(await fetchGithubComments(repoRoot, parsed.data.kind, parsed.data.number, c.req.query('refresh') === '1'));
4207
+ return c.json(await fetchGithubComments(repoRoot, parsed.data.kind, parsed.data.number, c.req.valid('query').refresh === '1'));
4208
+ })
4209
+ // Lazy checks glyphs for on-screen PR rows (#664). Additive sibling of /api/github — the list
4210
+ // call dropped `statusCheckRollup` (the dominant cost), so the glyph is hydrated here per
4211
+ // visible row. `prs` is a comma-separated list of positive integers, capped at GH_CHECKS_MAX;
4212
+ // anything malformed is a 400. Same in-payload availability degrade as the list (never a 5xx).
4213
+ // `prs` is the one genuinely REQUIRED query key on this server, so it is the one validated
4214
+ // strictly — `.min(1)` because `?prs=` answered `missing prs query` before it answered
4215
+ // `invalid prs query`, and both spellings must keep their own words.
4216
+ .get('/github/checks', queryZodValidator(z.object({ prs: z.string().min(1) }), { message: 'missing prs query' }), async (c) => {
4217
+ const { root: repoRoot } = c.get('project');
4218
+ const raw = c.req.valid('query').prs;
4219
+ const parts = raw.split(',').map((p) => p.trim()).filter(Boolean);
4220
+ if (parts.length === 0 || parts.length > GH_CHECKS_MAX)
4221
+ return c.json({ error: 'invalid prs query' }, 400);
4222
+ const numbers = [];
4223
+ for (const part of parts) {
4224
+ const n = Number(part);
4225
+ if (!Number.isInteger(n) || n <= 0 || String(n) !== part)
4226
+ return c.json({ error: 'invalid prs query' }, 400);
4227
+ numbers.push(n);
4228
+ }
4229
+ return c.json(await fetchGithubChecks(repoRoot, numbers));
4230
+ })
4231
+ .get('/github/prs/:number/merge-state', paramZodValidator(mergeNumberParams, { message: 'invalid pull request number' }), queryZodValidator(refreshQuery), async (c) => {
4232
+ const { root: repoRoot } = c.get('project');
4233
+ const parsed = { data: c.req.valid('param') };
4234
+ const forge = resolveForge(await getRepoInfo(repoRoot));
4235
+ if (!forge?.prMergeState)
4236
+ return c.json({ available: false, reason: 'GitHub merge state is unavailable' });
4237
+ return c.json(await forge.prMergeState(parsed.data.number, { refresh: c.req.valid('query').refresh === '1' }));
4238
+ })
4239
+ .post('/github/prs/:number/merge', paramZodValidator(mergeNumberParams, { message: 'invalid pull request number' }), jsonZodValidator(() => mergeBodySchema, { message: 'invalid merge request' }), async (c) => {
4240
+ const { root: repoRoot } = c.get('project');
4241
+ const parsedNumber = { data: c.req.valid('param') };
4242
+ const body = { data: c.req.valid('json') };
4243
+ const forge = resolveForge(await getRepoInfo(repoRoot));
4244
+ if (!forge?.mergePR)
4245
+ return c.json({ error: 'GitHub merge is unavailable' }, 409);
4246
+ const result = await forge.mergePR(parsedNumber.data.number, body.data);
4247
+ if (result.merged)
4248
+ return c.json(result);
4249
+ return c.json({
4250
+ error: result.error,
4251
+ ...(result.code ? { code: result.code } : {}),
4252
+ ...(result.current ? { current: result.current } : {}),
4253
+ }, result.status);
4254
+ })
4255
+ .get('/github/prs/:number/changes',
4256
+ // Split out of one `safeParse` over both inputs, because a path param and the query string
4257
+ // are separate validation targets to Hono and only a split makes each visible to the route
4258
+ // type. Both keep the single 400 sentence the combined parse answered. `refresh` stays
4259
+ // STRICT here (`?refresh=true` is a 400 today, unlike everywhere else on this server).
4260
+ paramZodValidator(prChangesParams, { message: 'invalid pull request number or refresh flag' }), queryZodValidator(prChangesQuery, { message: 'invalid pull request number or refresh flag' }), async (c) => {
4261
+ const { root: repoRoot } = c.get('project');
4262
+ const parsed = { data: c.req.valid('param') };
4263
+ try {
4264
+ return c.json(await fetchGithubPrDiff(repoRoot, parsed.data.number, c.req.valid('query').refresh === '1'));
4265
+ }
4266
+ catch (err) {
4267
+ if (err instanceof GithubPrNotFoundError)
4268
+ return c.json({ error: err.message }, 404);
4269
+ throw err;
4270
+ }
4271
+ });
4272
+ // The full comment thread for one issue/PR (#499). Additive sibling of /api/github — lazy
4273
+ // (fetched only while a detail view is open), zod-validated params, 400 on garbage, and the
4274
+ // same in-payload availability degrade (gh missing / offline / 404 all render as a hint).
4275
+ const commentsParams = z.object({
4276
+ kind: z.enum(['issue', 'pr']),
4277
+ number: z.coerce.number().int().positive(),
2739
4278
  });
2740
- // ---- repo view -----------------------------------------------------------
2741
- api.get('/repo', async (c) => {
4279
+ const mergeBodySchema = z.object({
4280
+ method: z.enum(['merge', 'squash', 'rebase']),
4281
+ expectedHeadSha: z.string().regex(/^[0-9a-f]{40}$/),
4282
+ overrideRules: z.boolean().optional().default(false),
4283
+ }).strict();
4284
+ // ---- chained family: repo / git (project-scoped) ----
4285
+ const repoRoutes = new Hono()
4286
+ .get('/repo', async (c) => {
2742
4287
  const { root: repoRoot } = c.get('project');
2743
4288
  const info = await getRepoInfo(repoRoot);
2744
4289
  if (!info)
@@ -2762,64 +4307,115 @@ export function createApp(deps) {
2762
4307
  branches,
2763
4308
  baseBranch: config.baseBranch ?? null,
2764
4309
  });
4310
+ })
4311
+ .get('/repo/diff', async (c) => {
4312
+ const { root: repoRoot } = c.get('project');
4313
+ const info = await getRepoInfo(repoRoot);
4314
+ if (!info)
4315
+ return c.text('not a git repository');
4316
+ return c.text(await getDiff(info.root));
4317
+ })
4318
+ // One commit's message + stat + patch — the Repo view expands it inline.
4319
+ // `?structured=1` is the ADDITIVE sibling (R5 Step 1.7): the new repo view's commit-diff
4320
+ // shape `{sha, subject, author, when, files, stat}` with 409 + reason on failure. The
4321
+ // legacy text answer below is a protected surface (BACKWARD_COMPATIBILITY.md §2) — its
4322
+ // shape, including the in-band failure sentences, stays exactly as it was.
4323
+ //
4324
+ // `Accept: application/json` reaches the same structured answer without the flag, and
4325
+ // `Accept: text/plain` asks for the blob; the flag still wins whenever it is present, and a
4326
+ // request with no opinion still gets the blob. See `negotiate`.
4327
+ .get('/repo/commit/:sha', queryZodValidator(z.object({ structured: queryValue })), async (c) => {
4328
+ const { root: repoRoot } = c.get('project');
4329
+ c.header('vary', 'Accept');
4330
+ const { structured } = c.req.valid('query');
4331
+ const wantsJson = structured !== undefined
4332
+ ? structured === '1'
4333
+ : negotiate(c.req.header('accept'), COMMIT_FORMATS) === 'application/json';
4334
+ const info = await getRepoInfo(repoRoot);
4335
+ if (wantsJson) {
4336
+ if (!info)
4337
+ return c.json({ error: 'not a git repository' }, 409);
4338
+ const result = await collectCommitChanges(info.root, c.req.param('sha'));
4339
+ if (!result.ok)
4340
+ return c.json({ error: result.error }, 409);
4341
+ return c.json(result.commit);
4342
+ }
4343
+ if (!info)
4344
+ return c.text('not a git repository');
4345
+ try {
4346
+ return c.text(await getCommit(info.root, c.req.param('sha')));
4347
+ }
4348
+ catch (err) {
4349
+ return c.text(`(git show failed: ${err instanceof Error ? err.message : String(err)})`);
4350
+ }
4351
+ })
4352
+ // Structured sibling of the text-blob /api/repo/diff above (protected
4353
+ // surface, untouched): the same {files, stat} shape the session /changes
4354
+ // route serves, here for the MAIN working tree's uncommitted changes vs
4355
+ // HEAD (redesign R5 Step 1.3 — §"Git/session API additions").
4356
+ .get('/repo/changes', async (c) => {
4357
+ const { root: repoRoot } = c.get('project');
4358
+ const info = await getRepoInfo(repoRoot);
4359
+ if (!info)
4360
+ return c.json({ error: 'not a git repository' }, 409);
4361
+ // The user's REAL working tree — never stage into their index (a GET must not write).
4362
+ const result = await collectChanges(info.root, 'HEAD', {
4363
+ intentToAdd: false,
4364
+ });
4365
+ if (!result.ok)
4366
+ return c.json({ error: result.error }, 409);
4367
+ return c.json(result.changes);
4368
+ })
4369
+ .post('/repo/branch', jsonZodValidator(() => repoBranchSchema), async (c) => {
4370
+ const { root: repoRoot } = c.get('project');
4371
+ const info = await getRepoInfo(repoRoot);
4372
+ if (!info)
4373
+ return c.json({ error: 'not a git repository' }, 409);
4374
+ const parsed = { data: c.req.valid('json') };
4375
+ const result = await createOrSwitchBranch(info.root, parsed.data.name, parsed.data.from);
4376
+ if (!result.ok)
4377
+ return c.json({ error: result.error }, 409);
4378
+ return c.json({ branch: result.branch, created: result.created });
2765
4379
  });
2766
4380
  // The Settings → Agents knobs in one read (R6 Step 1.5) — an ADDITIVE
2767
4381
  // sibling of PUT /api/config below; /api/health keeps its protected shape.
2768
- const configAnswer = (config) => ({
2769
- baseBranch: config.baseBranch ?? null,
2770
- defaultRunner: config.defaultRunner,
2771
- systemPrompt: config.systemPrompt ?? null,
2772
- defaultModels: config.defaultModels ?? {},
2773
- maxParallel: config.maxParallel,
2774
- memoryLimitMb: config.memoryLimitMb ?? null,
2775
- // Count-based worktree retention (#483): keep the last N finished worktrees
2776
- // on disk. 0 = unlimited. Always materialized (schema default 10).
2777
- worktreeRetention: config.worktreeRetention,
2778
- // Live title updates (task auto-naming spec): tri-state — null means "no
2779
- // config key, the CEZ_TITLE_UPDATES env default (ON) decides".
2780
- liveTitleUpdates: config.liveTitleUpdates ?? null,
2781
- // Optional review gate (#489): tri-state — null means "no config key, the
2782
- // CEZ_REVIEW_GATE env default (OFF) decides".
2783
- reviewGate: config.reviewGate ?? null,
2784
- });
2785
- api.get('/config', async (c) => c.json(configAnswer(await loadConfig(c.get('project').root))));
2786
- // Set/clear the agents' config knobs (Settings → Agents; the Repo tab's
2787
- // base-branch picker). Merges into the RAW config.json so user keys
2788
- // (skillsRepos…) survive and schema defaults are never materialized into
2789
- // the file. All fields optional + additive: `null` (and `''` for the
2790
- // R6 keys) clears a knob back to its default.
2791
- const modelPresetSchema = z.string().trim().max(200).nullable().optional();
2792
- const setConfigSchema = z.object({
2793
- baseBranch: z.string().trim().min(1).max(200).nullable().optional(),
2794
- defaultRunner: z.enum(['claude', 'codex', 'opencode']).optional(),
2795
- systemPrompt: z.string().trim().max(20_000, 'systemPrompt must be at most 20000 characters').nullable().optional(),
2796
- defaultModels: z
2797
- .object({
2798
- claude: modelPresetSchema,
2799
- codex: modelPresetSchema,
2800
- opencode: modelPresetSchema,
2801
- })
2802
- .optional(),
2803
- // Concurrency + memory guard (Settings → Resources). maxParallel clamps to
2804
- // the schema's 1–16; memoryLimitMb null/0 clears the ceiling.
2805
- maxParallel: z.number().int().min(1).max(16).optional(),
2806
- memoryLimitMb: z.number().int().min(0).max(1_048_576).nullable().optional(),
2807
- // Worktree retention count (Settings → Resources, #483). 0 = unlimited;
2808
- // null clears the key back to the schema default (10). Unlike memoryLimitMb,
2809
- // 0 is a meaningful value (unlimited), so it is stored, not treated as clear.
2810
- worktreeRetention: z.number().int().min(0).max(1000).nullable().optional(),
2811
- // Live title updates toggle (Settings → Agents): null clears the key back
2812
- // to the env-default behavior.
2813
- liveTitleUpdates: z.boolean().nullable().optional(),
2814
- // Optional review gate toggle (Settings → Agents, #489): null clears the key
2815
- // back to the env-default behavior (OFF).
2816
- reviewGate: z.boolean().nullable().optional(),
2817
- });
2818
- api.put('/config', async (c) => {
4382
+ const configAnswer = async (repoRoot, config) => {
4383
+ const nativeModels = await readAgentModelDefaults(repoRoot);
4384
+ const modelsLocked = agentModelsLocked(repoRoot);
4385
+ return {
4386
+ baseBranch: config.baseBranch ?? null,
4387
+ defaultRunner: config.defaultRunner,
4388
+ systemPrompt: config.systemPrompt ?? null,
4389
+ // Native defaults seed each runner independently. A Cezar preset remains
4390
+ // selectable unless the operator opts into the fixed-model policy.
4391
+ defaultModels: modelsLocked
4392
+ ? nativeModels
4393
+ : { ...nativeModels, ...(config.defaultModels ?? {}) },
4394
+ modelsLocked,
4395
+ maxParallel: config.maxParallel,
4396
+ memoryLimitMb: config.memoryLimitMb ?? null,
4397
+ // Count-based worktree retention (#483): keep the last N finished worktrees
4398
+ // on disk. 0 = unlimited. Always materialized (schema default 10).
4399
+ worktreeRetention: config.worktreeRetention,
4400
+ // Live title updates (task auto-naming spec): tri-state — null means "no
4401
+ // config key, the CEZ_TITLE_UPDATES env default (ON) decides".
4402
+ liveTitleUpdates: config.liveTitleUpdates ?? null,
4403
+ // Optional review gate (#489): tri-state — null means "no config key, the
4404
+ // CEZ_REVIEW_GATE env default (OFF) decides".
4405
+ reviewGate: config.reviewGate ?? null,
4406
+ };
4407
+ };
4408
+ // ---- chained family: per-repo config (project-scoped) ----
4409
+ const configRoutes = new Hono()
4410
+ .get('/config', async (c) => {
4411
+ const repoRoot = c.get('project').root;
4412
+ return c.json(await configAnswer(repoRoot, await loadConfig(repoRoot)));
4413
+ })
4414
+ .put('/config', jsonZodValidator(() => setConfigSchema), async (c) => {
2819
4415
  const { root: repoRoot, dataDir } = c.get('project');
2820
- const parsed = setConfigSchema.safeParse(await c.req.json().catch(() => null));
2821
- if (!parsed.success) {
2822
- return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
4416
+ const parsed = { data: c.req.valid('json') };
4417
+ if (agentModelsLocked(repoRoot) && parsed.data.defaultModels !== undefined) {
4418
+ return c.json({ error: AGENT_MODELS_LOCKED_ERROR }, 409);
2823
4419
  }
2824
4420
  const configPath = join(dataDir, 'config.json');
2825
4421
  let raw = {};
@@ -2905,16 +4501,55 @@ export function createApp(deps) {
2905
4501
  return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
2906
4502
  }
2907
4503
  // Pre-R6 answer shape ({baseBranch, defaultRunner}) + additive R6 fields.
2908
- return c.json(configAnswer(await loadConfig(repoRoot)));
4504
+ return c.json(await configAnswer(repoRoot, await loadConfig(repoRoot)));
4505
+ });
4506
+ // Set/clear the agents' config knobs (Settings → Agents; the Repo tab's
4507
+ // base-branch picker). Merges into the RAW config.json so user keys
4508
+ // (skillsRepos…) survive and schema defaults are never materialized into
4509
+ // the file. All fields optional + additive: `null` (and `''` for the
4510
+ // R6 keys) clears a knob back to its default.
4511
+ const modelPresetSchema = z.string().trim().max(200).nullable().optional();
4512
+ const setConfigSchema = z.object({
4513
+ baseBranch: z.string().trim().min(1).max(200).nullable().optional(),
4514
+ defaultRunner: z.enum(['claude', 'codex', 'opencode']).optional(),
4515
+ systemPrompt: z.string().trim().max(20_000, 'must be at most 20000 characters').nullable().optional(),
4516
+ defaultModels: z
4517
+ .object({
4518
+ claude: modelPresetSchema,
4519
+ codex: modelPresetSchema,
4520
+ opencode: modelPresetSchema,
4521
+ })
4522
+ .optional(),
4523
+ // Concurrency + memory guard (Settings → Resources). maxParallel clamps to
4524
+ // the schema's 1–16; memoryLimitMb null/0 clears the ceiling.
4525
+ maxParallel: z.number().int().min(1).max(16).optional(),
4526
+ memoryLimitMb: z.number().int().min(0).max(1_048_576).nullable().optional(),
4527
+ // Worktree retention count (Settings → Resources, #483). 0 = unlimited;
4528
+ // null clears the key back to the schema default (10). Unlike memoryLimitMb,
4529
+ // 0 is a meaningful value (unlimited), so it is stored, not treated as clear.
4530
+ worktreeRetention: z.number().int().min(0).max(1000).nullable().optional(),
4531
+ // Live title updates toggle (Settings → Agents): null clears the key back
4532
+ // to the env-default behavior.
4533
+ liveTitleUpdates: z.boolean().nullable().optional(),
4534
+ // Optional review gate toggle (Settings → Agents, #489): null clears the key
4535
+ // back to the env-default behavior (OFF).
4536
+ reviewGate: z.boolean().nullable().optional(),
4537
+ });
4538
+ const setAgentConfigSchema = z.object({
4539
+ content: z.string().max(2_000_000),
4540
+ version: z.string().nullable(),
2909
4541
  });
4542
+ // ---- chained family: agent-config (project-scoped) -----------------------
2910
4543
  // Agent config is project-scoped (spec #404, adapted to the multi-project
2911
4544
  // route seam from #521): handlers resolve the selected repo through the
2912
- // same ProjectContext as every other mirrored route.
2913
- api.get('/agent-config', async (c) => {
4545
+ // same ProjectContext as every other mirrored route. Chained (not statements)
4546
+ // so `AppType` carries it — see `healthRoutes`.
4547
+ const agentConfigRoutes = new Hono()
4548
+ .get('/agent-config', async (c) => {
2914
4549
  const editable = capabilities().localHandoff;
2915
4550
  return c.json(await listAgentConfig(c.get('project').root, process.env, editable));
2916
- });
2917
- api.get('/agent-config/:id', async (c) => {
4551
+ })
4552
+ .get('/agent-config/:id', async (c) => {
2918
4553
  const id = c.req.param('id');
2919
4554
  const def = findConfigFile(id);
2920
4555
  if (!def)
@@ -2930,12 +4565,8 @@ export function createApp(deps) {
2930
4565
  if ('error' in read)
2931
4566
  return c.json({ error: read.error }, 500);
2932
4567
  return c.json(read);
2933
- });
2934
- const setAgentConfigSchema = z.object({
2935
- content: z.string().max(2_000_000),
2936
- version: z.string().nullable(),
2937
- });
2938
- api.put('/agent-config/:id', async (c) => {
4568
+ })
4569
+ .put('/agent-config/:id', jsonZodValidator(setAgentConfigSchema), async (c) => {
2939
4570
  // Config files may define hooks and MCP commands, so writes remain a
2940
4571
  // local-machine capability and are re-gated on every request.
2941
4572
  if (!capabilities().localHandoff) {
@@ -2943,10 +4574,7 @@ export function createApp(deps) {
2943
4574
  error: 'editing agent config is disabled in hosted mode (CEZ_REMOTE) — edit it from the machine that owns the checkout',
2944
4575
  }, 409);
2945
4576
  }
2946
- const parsed = setAgentConfigSchema.safeParse(await c.req.json().catch(() => null));
2947
- if (!parsed.success) {
2948
- return c.json({ error: parsed.error.issues.map((issue) => issue.message).join('; ') }, 400);
2949
- }
4577
+ const parsed = { data: c.req.valid('json') };
2950
4578
  const out = await writeConfigFile(c.req.param('id'), parsed.data.content, parsed.data.version, c.get('project').root);
2951
4579
  if (out === null)
2952
4580
  return c.json({ error: 'unknown config file' }, 404);
@@ -2954,55 +4582,6 @@ export function createApp(deps) {
2954
4582
  return c.json({ error: out.error }, out.status);
2955
4583
  return c.json(out.read);
2956
4584
  });
2957
- api.get('/repo/diff', async (c) => {
2958
- const { root: repoRoot } = c.get('project');
2959
- const info = await getRepoInfo(repoRoot);
2960
- if (!info)
2961
- return c.text('not a git repository');
2962
- return c.text(await getDiff(info.root));
2963
- });
2964
- // One commit's message + stat + patch — the Repo view expands it inline.
2965
- // `?structured=1` is the ADDITIVE sibling (R5 Step 1.7): the new repo view's commit-diff
2966
- // shape `{sha, subject, author, when, files, stat}` with 409 + reason on failure. The
2967
- // legacy text answer below is a protected surface (BACKWARD_COMPATIBILITY.md §2) — its
2968
- // shape, including the in-band failure sentences, stays exactly as it was.
2969
- api.get('/repo/commit/:sha', async (c) => {
2970
- const { root: repoRoot } = c.get('project');
2971
- const info = await getRepoInfo(repoRoot);
2972
- if (c.req.query('structured') === '1') {
2973
- if (!info)
2974
- return c.json({ error: 'not a git repository' }, 409);
2975
- const result = await collectCommitChanges(info.root, c.req.param('sha'));
2976
- if (!result.ok)
2977
- return c.json({ error: result.error }, 409);
2978
- return c.json(result.commit);
2979
- }
2980
- if (!info)
2981
- return c.text('not a git repository');
2982
- try {
2983
- return c.text(await getCommit(info.root, c.req.param('sha')));
2984
- }
2985
- catch (err) {
2986
- return c.text(`(git show failed: ${err instanceof Error ? err.message : String(err)})`);
2987
- }
2988
- });
2989
- // Structured sibling of the text-blob /api/repo/diff above (protected
2990
- // surface, untouched): the same {files, stat} shape the session /changes
2991
- // route serves, here for the MAIN working tree's uncommitted changes vs
2992
- // HEAD (redesign R5 Step 1.3 — §"Git/session API additions").
2993
- api.get('/repo/changes', async (c) => {
2994
- const { root: repoRoot } = c.get('project');
2995
- const info = await getRepoInfo(repoRoot);
2996
- if (!info)
2997
- return c.json({ error: 'not a git repository' }, 409);
2998
- // The user's REAL working tree — never stage into their index (a GET must not write).
2999
- const result = await collectChanges(info.root, 'HEAD', {
3000
- intentToAdd: false,
3001
- });
3002
- if (!result.ok)
3003
- return c.json({ error: result.error }, 409);
3004
- return c.json(result.changes);
3005
- });
3006
4585
  // Repo view branch actions: switch to an existing branch, or create one
3007
4586
  // (from `from` or HEAD) and switch. Predictable git failures — invalid
3008
4587
  // name, unknown `from`, dirty-tree checkout conflict — are 409 + reason.
@@ -3010,28 +4589,62 @@ export function createApp(deps) {
3010
4589
  name: z.string().trim().min(1).max(200),
3011
4590
  from: z.string().trim().min(1).max(200).optional(),
3012
4591
  });
3013
- api.post('/repo/branch', async (c) => {
3014
- const { root: repoRoot } = c.get('project');
3015
- const info = await getRepoInfo(repoRoot);
3016
- if (!info)
3017
- return c.json({ error: 'not a git repository' }, 409);
3018
- const parsed = repoBranchSchema.safeParse(await c.req.json().catch(() => null));
3019
- if (!parsed.success) {
3020
- return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
3021
- }
3022
- const result = await createOrSwitchBranch(info.root, parsed.data.name, parsed.data.from);
3023
- if (!result.ok)
3024
- return c.json({ error: result.error }, 409);
3025
- return c.json({ branch: result.branch, created: result.created });
3026
- });
3027
- // ---- mount the mirrored table (multi-project spec, step 2.2) -------------
3028
- // Scoped first, then the legacy aliases. The paths are disjoint (no legacy
3029
- // route starts with `/p/`), so order between the two mounts never decides a
3030
- // match — but the catch-all below must still come last. `route()` re-registers
3031
- // the sub-app's routes under each prefix, handlers shared, internal order
3032
- // (e.g. `/runs/archive-finished` before `/runs/:id/archive`) preserved.
3033
- app.route(SCOPED_PREFIX, api);
3034
- app.route('/api', api);
4592
+ // ---- assemble the chained families --------------------------------------
4593
+ // Every chained family is registered ONCE and mounted into the versioned table. There is no
4594
+ // second, unversioned spelling: `/api/*` was removed once the whole API was reachable under
4595
+ // `/api/v1` (BACKWARD_COMPATIBILITY.md §2). One surface means one thing to keep working, and
4596
+ // it is the one the typed client describes.
4597
+ //
4598
+ // MOUNT ORDER IS REGISTRATION ORDER. Hono matches in the order routes were added, so each
4599
+ // family keeps its internal order and the families keep theirs relative to each other.
4600
+ //
4601
+ // Written as ONE chained expression because that is the only shape Hono can infer route types
4602
+ // from — it is what puts these routes in `AppType`, and so in the typed client.
4603
+ const v1 = new Hono()
4604
+ .use('*', resolveProjectScope)
4605
+ .route('/', launchKeyRoutes)
4606
+ .route('/', skillsRoutes)
4607
+ .route('/', uiStateRoutes)
4608
+ .route('/', workflowsRoutes)
4609
+ .route('/', planRoutes)
4610
+ .route('/', automationsRoutes)
4611
+ .route('/', runsRoutes)
4612
+ .route('/', groupsRoutes)
4613
+ .route('/', openTargetsRoutes)
4614
+ .route('/', worktreesRoutes)
4615
+ .route('/', todosRoutes)
4616
+ .route('/', sseRoutes)
4617
+ .route('/', githubRoutes)
4618
+ .route('/', repoRoutes)
4619
+ .route('/', configRoutes)
4620
+ .route('/', agentConfigRoutes);
4621
+ // Workspace-level families answer for the whole workspace, so they are single-mount: never a
4622
+ // project-scoped spelling, which would be a second surface to protect with no consumer.
4623
+ const workspaceV1 = new Hono()
4624
+ .route('/', healthRoutes)
4625
+ .route('/', modelsRoutes)
4626
+ .route('/', providersRoutes)
4627
+ .route('/', projectsRoutes)
4628
+ .route('/', agentProfilesRoutes)
4629
+ .route('/', skillsUpdateRoutes)
4630
+ .route('/', workspaceConfigRoutes)
4631
+ .route('/', fsBrowseRoutes)
4632
+ .route('/', automationChecksRoutes)
4633
+ .route('/', workspaceEventsRoutes);
4634
+ // ---- mount ---------------------------------------------------------------
4635
+ // Scoped first, then the unscoped alias bound to the boot project. The paths are disjoint (no
4636
+ // route starts with `/p/`), so order between the two never decides a match — but the SPA
4637
+ // catch-all below must still come last. `route()` re-registers the sub-app's routes under
4638
+ // each prefix, handlers shared, internal order preserved.
4639
+ //
4640
+ // Workspace families mount LAST and that is load-bearing: mounting the project table also
4641
+ // mounts its `use('*')` scope resolver over the whole prefix, and Hono runs matched middleware
4642
+ // in registration order. `/health` in particular answers for the workspace, has no project to
4643
+ // resolve, and is the CORS-open discovery route — it must not sit behind the resolver.
4644
+ const routed = app
4645
+ .route(V1_SCOPED_PREFIX, v1)
4646
+ .route(V1_PREFIX, v1)
4647
+ .route(V1_PREFIX, workspaceV1);
3035
4648
  // ---- SPA catch-all -------------------------------------------------------
3036
4649
  // Last, so every route above still wins. Any other GET gets the cockpit shell:
3037
4650
  // react-router owns the route map, including the 404, so `/tasks/:id/changes`
@@ -3040,14 +4653,33 @@ export function createApp(deps) {
3040
4653
  // an unknown API path must never answer with HTML.
3041
4654
  // Without a web/dist build this serves the built-in build-hint page (dev-only
3042
4655
  // state — the published tarball ships web/dist), never a 404.
3043
- app.get('*', (c) => serveShell(c) ?? c.notFound());
3044
- return app;
4656
+ routed.get('*', (c) => serveShell(c) ?? c.notFound());
4657
+ return routed;
3045
4658
  }
3046
4659
  export function startServer(deps, port) {
4660
+ const workspaceEvents = deps.workspaceEvents ?? new WorkspaceEventBus();
4661
+ const skillsUpdate = deps.skillsUpdate ?? new SkillsUpdateService({ invalidateCatalog: refreshTeamSkills });
3047
4662
  // The subscription hub rides the same HTTP server (one port, zero config):
3048
4663
  // createApp registers the topics, the `upgrade` hook below owns the socket.
3049
4664
  const socketHub = deps.socketHub ?? createSocketHub();
3050
- const app = createApp({ ...deps, socketHub });
4665
+ const automationCoordinator = new AutomationCoordinator({ listProjects });
4666
+ const bootProjectId = deps.bootProjectId ?? 'default';
4667
+ const bootAutomationStore = automationCoordinator.store(bootProjectId, deps.repoRoot);
4668
+ const sharedContexts = deps.contexts ?? new ProjectContexts({
4669
+ listProjects,
4670
+ semaphore: deps.semaphore,
4671
+ automationStore: (projectId, root) => automationCoordinator.store(projectId, root),
4672
+ });
4673
+ let rescheduleAutomations = () => { };
4674
+ const app = createApp({
4675
+ ...deps,
4676
+ contexts: sharedContexts,
4677
+ automationStore: bootAutomationStore,
4678
+ workspaceEvents,
4679
+ skillsUpdate,
4680
+ socketHub,
4681
+ automationsChanged: () => rescheduleAutomations(),
4682
+ });
3051
4683
  // SECURITY: default to loopback. This server executes agents locally and its endpoints are
3052
4684
  // same-origin-trusted (only /api/health is CORS-open); binding to a non-loopback host would
3053
4685
  // expose an agent-executing box to the network. `bindHost` exists only for a deliberate
@@ -3058,13 +4690,89 @@ export function startServer(deps, port) {
3058
4690
  port,
3059
4691
  hostname: deps.bindHost ?? '127.0.0.1',
3060
4692
  });
4693
+ const coordinator = new SkillsUpdateCoordinator(skillsUpdate, async () => effectiveSkillsAutoUpdate(await loadWorkspaceConfig()));
4694
+ const automationProjects = new Map();
4695
+ const automationScheduler = new WorkspaceAutomationScheduler({
4696
+ coordinator: automationCoordinator,
4697
+ handle: (projectId, store) => {
4698
+ const project = automationProjects.get(projectId);
4699
+ if (!project)
4700
+ return undefined;
4701
+ return {
4702
+ projectId,
4703
+ owner: project.owner,
4704
+ repo: project.repo,
4705
+ store,
4706
+ poller: new GithubPoller(),
4707
+ onChange: (automationId, revision) => workspaceEvents.emit('automation-change', { project: projectId, automationId, revision }),
4708
+ launch: async (definition, candidate, receiptId) => {
4709
+ const bootId = deps.bootProjectId ?? 'default';
4710
+ const context = projectId === bootId
4711
+ ? { root: deps.repoRoot, manager: deps.manager, store: deps.store }
4712
+ : await sharedContexts.context(projectId);
4713
+ return launchAutomationRun({
4714
+ root: context.root,
4715
+ manager: context.manager,
4716
+ store: context.store,
4717
+ definition,
4718
+ candidate,
4719
+ receiptId,
4720
+ });
4721
+ },
4722
+ };
4723
+ },
4724
+ });
4725
+ rescheduleAutomations = () => { void automationScheduler.reschedule(); };
4726
+ const unsubscribe = workspaceEvents.on((event, data) => {
4727
+ if (event === 'project-added') {
4728
+ const project = data.project;
4729
+ if (project && typeof project.id === 'string' && typeof project.root === 'string' && project.status !== 'missing') {
4730
+ coordinator.add(project.id, project.root);
4731
+ void getRepoInfo(project.root).then((info) => {
4732
+ const parsed = parseRemote(info?.remote ?? '');
4733
+ if (parsed?.host === 'github.com')
4734
+ automationProjects.set(project.id, { root: project.root, owner: parsed.owner, repo: parsed.repo });
4735
+ return automationScheduler.reschedule();
4736
+ });
4737
+ }
4738
+ }
4739
+ else if (event === 'project-removed') {
4740
+ const id = data.id;
4741
+ if (typeof id === 'string')
4742
+ coordinator.remove(id);
4743
+ if (typeof id === 'string') {
4744
+ automationCoordinator.remove(id);
4745
+ automationProjects.delete(id);
4746
+ void automationScheduler.reschedule();
4747
+ }
4748
+ }
4749
+ });
4750
+ server.once('listening', () => {
4751
+ void listProjects().then((projects) => {
4752
+ const all = projects.some((project) => project.root === deps.repoRoot)
4753
+ ? projects : [{ id: deps.bootProjectId ?? 'default', root: deps.repoRoot, status: 'ok' }, ...projects];
4754
+ coordinator.start(all);
4755
+ void Promise.all(all.map(async (project) => {
4756
+ const parsed = parseRemote((await getRepoInfo(project.root))?.remote ?? '');
4757
+ if (parsed?.host === 'github.com')
4758
+ automationProjects.set(project.id, { root: project.root, owner: parsed.owner, repo: parsed.repo });
4759
+ const automationStore = automationCoordinator.store(project.id, project.root);
4760
+ const runStore = project.id === (deps.bootProjectId ?? 'default')
4761
+ ? deps.store
4762
+ : sharedContexts.peek(project.id)?.store;
4763
+ if (automationStore && runStore)
4764
+ reconcileAutomationReceipts(automationStore, runStore);
4765
+ })).then(() => automationScheduler.start()).catch(() => undefined);
4766
+ }).catch(() => undefined);
4767
+ });
4768
+ server.once('close', () => { unsubscribe(); coordinator.stop(); automationScheduler.stop(); });
3061
4769
  socketHub.attach(server, (req) => verifyWsUpgrade(req, deps.bindHost));
3062
4770
  return server;
3063
4771
  }
3064
4772
  /**
3065
4773
  * The WebSocket twin of the `/api/*` request-origin guard (#426), applied
3066
- * before the `/api/ws` handshake. WebSocket is NOT subject to CORS — any web
3067
- * page may open `ws://127.0.0.1:<port>/api/ws` and, unlike a forced HTTP GET,
4774
+ * before the `/api/v1/ws` handshake. WebSocket is NOT subject to CORS — any web
4775
+ * page may open `ws://127.0.0.1:<port>/api/v1/ws` and, unlike a forced HTTP GET,
3068
4776
  * would get to READ what comes back — so this guard is load-bearing:
3069
4777
  *
3070
4778
  * 1. Host allowlist (local mode): a non-loopback Host is a DNS-rebound