@open-mercato/cezar 0.9.1 → 0.9.2-pr772.1071

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