@bevel-software/platform-core-backend 0.26.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (613) hide show
  1. package/agent-guide/access-control.md +17 -0
  2. package/agent-guide/conventions.md +8 -0
  3. package/agent-guide/html-views.md +83 -0
  4. package/agent-guide/new-knowledge-base.md +24 -0
  5. package/agent-guide/tool-manuals.md +10 -0
  6. package/dist/assets.d.ts +19 -0
  7. package/dist/assets.d.ts.map +1 -1
  8. package/dist/assets.js +26 -2
  9. package/dist/assets.js.map +1 -1
  10. package/dist/core/catalog-revision.d.ts +19 -1
  11. package/dist/core/catalog-revision.d.ts.map +1 -1
  12. package/dist/core/catalog-revision.js +14 -3
  13. package/dist/core/catalog-revision.js.map +1 -1
  14. package/dist/core/create-core-server.d.ts +5 -0
  15. package/dist/core/create-core-server.d.ts.map +1 -1
  16. package/dist/core/create-core-server.js +54 -3
  17. package/dist/core/create-core-server.js.map +1 -1
  18. package/dist/core/create-core-services.d.ts +26 -0
  19. package/dist/core/create-core-services.d.ts.map +1 -1
  20. package/dist/core/create-core-services.js +100 -8
  21. package/dist/core/create-core-services.js.map +1 -1
  22. package/dist/core/lifecycle.d.ts +16 -1
  23. package/dist/core/lifecycle.d.ts.map +1 -1
  24. package/dist/core/lifecycle.js +18 -1
  25. package/dist/core/lifecycle.js.map +1 -1
  26. package/dist/core-config.d.ts +21 -0
  27. package/dist/core-config.d.ts.map +1 -1
  28. package/dist/core-config.js +22 -1
  29. package/dist/core-config.js.map +1 -1
  30. package/dist/index.d.ts +1 -1
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +2 -2
  33. package/dist/index.js.map +1 -1
  34. package/dist/modules/access/access-control.interface.d.ts +8 -0
  35. package/dist/modules/access/access-control.interface.d.ts.map +1 -1
  36. package/dist/modules/access/access-control.service.d.ts +1 -0
  37. package/dist/modules/access/access-control.service.d.ts.map +1 -1
  38. package/dist/modules/access/access-control.service.js +11 -0
  39. package/dist/modules/access/access-control.service.js.map +1 -1
  40. package/dist/modules/access/directory-sync-bot.js +1 -1
  41. package/dist/modules/access/directory-sync-bot.js.map +1 -1
  42. package/dist/modules/agent-guide/agent-guide.d.ts +6 -0
  43. package/dist/modules/agent-guide/agent-guide.d.ts.map +1 -1
  44. package/dist/modules/agent-guide/agent-guide.js +8 -0
  45. package/dist/modules/agent-guide/agent-guide.js.map +1 -1
  46. package/dist/modules/agent-guide/index.d.ts +1 -1
  47. package/dist/modules/agent-guide/index.d.ts.map +1 -1
  48. package/dist/modules/agent-guide/index.js +1 -1
  49. package/dist/modules/agent-guide/index.js.map +1 -1
  50. package/dist/modules/agent-instructions/compose.d.ts +5 -0
  51. package/dist/modules/agent-instructions/compose.d.ts.map +1 -1
  52. package/dist/modules/agent-instructions/compose.js +19 -2
  53. package/dist/modules/agent-instructions/compose.js.map +1 -1
  54. package/dist/modules/agent-instructions/shared-file-rules.js +19 -19
  55. package/dist/modules/agent-instructions/shared-file-rules.js.map +1 -1
  56. package/dist/modules/audit/agent-audit.service.d.ts +21 -2
  57. package/dist/modules/audit/agent-audit.service.d.ts.map +1 -1
  58. package/dist/modules/audit/agent-audit.service.js +43 -2
  59. package/dist/modules/audit/agent-audit.service.js.map +1 -1
  60. package/dist/modules/audit/agent-connection.routes.d.ts +34 -0
  61. package/dist/modules/audit/agent-connection.routes.d.ts.map +1 -0
  62. package/dist/modules/audit/agent-connection.routes.js +38 -0
  63. package/dist/modules/audit/agent-connection.routes.js.map +1 -0
  64. package/dist/modules/audit/audit.contract.d.ts +24 -0
  65. package/dist/modules/audit/audit.contract.d.ts.map +1 -1
  66. package/dist/modules/audit/audit.contract.js.map +1 -1
  67. package/dist/modules/audit/index.d.ts +1 -0
  68. package/dist/modules/audit/index.d.ts.map +1 -1
  69. package/dist/modules/audit/index.js +1 -0
  70. package/dist/modules/audit/index.js.map +1 -1
  71. package/dist/modules/auth/account.routes.d.ts.map +1 -1
  72. package/dist/modules/auth/account.routes.js +10 -3
  73. package/dist/modules/auth/account.routes.js.map +1 -1
  74. package/dist/modules/auth/auth.middleware.d.ts +7 -0
  75. package/dist/modules/auth/auth.middleware.d.ts.map +1 -1
  76. package/dist/modules/auth/auth.middleware.js +1 -1
  77. package/dist/modules/auth/auth.middleware.js.map +1 -1
  78. package/dist/modules/code-mode/code-mode.tool.d.ts.map +1 -1
  79. package/dist/modules/code-mode/code-mode.tool.js +11 -3
  80. package/dist/modules/code-mode/code-mode.tool.js.map +1 -1
  81. package/dist/modules/database/core-schema.d.ts +96 -0
  82. package/dist/modules/database/core-schema.d.ts.map +1 -1
  83. package/dist/modules/database/core-schema.js +32 -3
  84. package/dist/modules/database/core-schema.js.map +1 -1
  85. package/dist/modules/embed/account-link.service.d.ts +42 -0
  86. package/dist/modules/embed/account-link.service.d.ts.map +1 -0
  87. package/dist/modules/embed/account-link.service.js +50 -0
  88. package/dist/modules/embed/account-link.service.js.map +1 -0
  89. package/dist/modules/embed/embed-link.d.ts +58 -0
  90. package/dist/modules/embed/embed-link.d.ts.map +1 -0
  91. package/dist/modules/embed/embed-link.js +160 -0
  92. package/dist/modules/embed/embed-link.js.map +1 -0
  93. package/dist/modules/embed/embed.errors.d.ts +30 -0
  94. package/dist/modules/embed/embed.errors.d.ts.map +1 -0
  95. package/dist/modules/embed/embed.errors.js +42 -0
  96. package/dist/modules/embed/embed.errors.js.map +1 -0
  97. package/dist/modules/embed/embed.interface.d.ts +204 -0
  98. package/dist/modules/embed/embed.interface.d.ts.map +1 -0
  99. package/dist/modules/embed/embed.interface.js +2 -0
  100. package/dist/modules/embed/embed.interface.js.map +1 -0
  101. package/dist/modules/embed/embed.routes.d.ts +59 -0
  102. package/dist/modules/embed/embed.routes.d.ts.map +1 -0
  103. package/dist/modules/embed/embed.routes.js +343 -0
  104. package/dist/modules/embed/embed.routes.js.map +1 -0
  105. package/dist/modules/embed/embed.service.d.ts +169 -0
  106. package/dist/modules/embed/embed.service.d.ts.map +1 -0
  107. package/dist/modules/embed/embed.service.js +627 -0
  108. package/dist/modules/embed/embed.service.js.map +1 -0
  109. package/dist/modules/embed/embed.tools.d.ts +51 -0
  110. package/dist/modules/embed/embed.tools.d.ts.map +1 -0
  111. package/dist/modules/embed/embed.tools.js +170 -0
  112. package/dist/modules/embed/embed.tools.js.map +1 -0
  113. package/dist/modules/embed/mcp-app.d.ts +64 -0
  114. package/dist/modules/embed/mcp-app.d.ts.map +1 -0
  115. package/dist/modules/embed/mcp-app.js +147 -0
  116. package/dist/modules/embed/mcp-app.js.map +1 -0
  117. package/dist/modules/embed/mcp-app.routes.d.ts +21 -0
  118. package/dist/modules/embed/mcp-app.routes.d.ts.map +1 -0
  119. package/dist/modules/embed/mcp-app.routes.js +36 -0
  120. package/dist/modules/embed/mcp-app.routes.js.map +1 -0
  121. package/dist/modules/github-app/github-app.connection.d.ts +15 -0
  122. package/dist/modules/github-app/github-app.connection.d.ts.map +1 -1
  123. package/dist/modules/github-app/github-app.connection.js +34 -3
  124. package/dist/modules/github-app/github-app.connection.js.map +1 -1
  125. package/dist/modules/kb-fs/locking-filesystem.d.ts +65 -0
  126. package/dist/modules/kb-fs/locking-filesystem.d.ts.map +1 -1
  127. package/dist/modules/kb-fs/locking-filesystem.js +300 -0
  128. package/dist/modules/kb-fs/locking-filesystem.js.map +1 -1
  129. package/dist/modules/kb-sync/kb-sync.interface.d.ts +5 -0
  130. package/dist/modules/kb-sync/kb-sync.interface.d.ts.map +1 -1
  131. package/dist/modules/kb-sync/kb-sync.service.d.ts.map +1 -1
  132. package/dist/modules/kb-sync/kb-sync.service.js +6 -0
  133. package/dist/modules/kb-sync/kb-sync.service.js.map +1 -1
  134. package/dist/modules/mcp/mcp-auth.middleware.d.ts.map +1 -1
  135. package/dist/modules/mcp/mcp-auth.middleware.js +2 -1
  136. package/dist/modules/mcp/mcp-auth.middleware.js.map +1 -1
  137. package/dist/modules/mcp/mcp.service.d.ts +28 -1
  138. package/dist/modules/mcp/mcp.service.d.ts.map +1 -1
  139. package/dist/modules/mcp/mcp.service.js +64 -8
  140. package/dist/modules/mcp/mcp.service.js.map +1 -1
  141. package/dist/modules/mcp/oauth/bevel-oauth-provider.d.ts +24 -0
  142. package/dist/modules/mcp/oauth/bevel-oauth-provider.d.ts.map +1 -1
  143. package/dist/modules/mcp/oauth/bevel-oauth-provider.js +32 -4
  144. package/dist/modules/mcp/oauth/bevel-oauth-provider.js.map +1 -1
  145. package/dist/modules/onboarding/onboarding.contract.d.ts +80 -0
  146. package/dist/modules/onboarding/onboarding.contract.d.ts.map +1 -0
  147. package/dist/modules/onboarding/onboarding.contract.js +7 -0
  148. package/dist/modules/onboarding/onboarding.contract.js.map +1 -0
  149. package/dist/modules/onboarding/onboarding.routes.d.ts +18 -0
  150. package/dist/modules/onboarding/onboarding.routes.d.ts.map +1 -0
  151. package/dist/modules/onboarding/onboarding.routes.js +81 -0
  152. package/dist/modules/onboarding/onboarding.routes.js.map +1 -0
  153. package/dist/modules/onboarding/starter-pack.service.d.ts +213 -0
  154. package/dist/modules/onboarding/starter-pack.service.d.ts.map +1 -0
  155. package/dist/modules/onboarding/starter-pack.service.js +492 -0
  156. package/dist/modules/onboarding/starter-pack.service.js.map +1 -0
  157. package/dist/modules/onboarding/starter-packs.d.ts +78 -0
  158. package/dist/modules/onboarding/starter-packs.d.ts.map +1 -0
  159. package/dist/modules/onboarding/starter-packs.js +156 -0
  160. package/dist/modules/onboarding/starter-packs.js.map +1 -0
  161. package/dist/modules/plugins/index.d.ts +1 -1
  162. package/dist/modules/plugins/index.d.ts.map +1 -1
  163. package/dist/modules/plugins/index.js +1 -1
  164. package/dist/modules/plugins/index.js.map +1 -1
  165. package/dist/modules/plugins/plugin-provision.service.d.ts +19 -0
  166. package/dist/modules/plugins/plugin-provision.service.d.ts.map +1 -1
  167. package/dist/modules/plugins/plugin-provision.service.js +18 -1
  168. package/dist/modules/plugins/plugin-provision.service.js.map +1 -1
  169. package/dist/modules/plugins/plugins.routes.d.ts +0 -36
  170. package/dist/modules/plugins/plugins.routes.d.ts.map +1 -1
  171. package/dist/modules/plugins/plugins.routes.js +31 -0
  172. package/dist/modules/plugins/plugins.routes.js.map +1 -1
  173. package/dist/modules/settings/deployment-settings.service.d.ts +34 -0
  174. package/dist/modules/settings/deployment-settings.service.d.ts.map +1 -1
  175. package/dist/modules/settings/deployment-settings.service.js +134 -1
  176. package/dist/modules/settings/deployment-settings.service.js.map +1 -1
  177. package/dist/modules/settings/repository-source.d.ts +1 -0
  178. package/dist/modules/settings/repository-source.d.ts.map +1 -1
  179. package/dist/modules/settings/repository-source.js +3 -3
  180. package/dist/modules/settings/repository-source.js.map +1 -1
  181. package/dist/modules/skills/skills.tools.d.ts.map +1 -1
  182. package/dist/modules/skills/skills.tools.js +50 -32
  183. package/dist/modules/skills/skills.tools.js.map +1 -1
  184. package/dist/modules/tool-auth/connection-key-rejection.d.ts +10 -1
  185. package/dist/modules/tool-auth/connection-key-rejection.d.ts.map +1 -1
  186. package/dist/modules/tool-auth/connection-key-rejection.js +11 -3
  187. package/dist/modules/tool-auth/connection-key-rejection.js.map +1 -1
  188. package/dist/modules/tool-auth/external-api-key.interface.d.ts +8 -0
  189. package/dist/modules/tool-auth/external-api-key.interface.d.ts.map +1 -1
  190. package/dist/modules/tool-auth/external-api-key.service.d.ts +24 -2
  191. package/dist/modules/tool-auth/external-api-key.service.d.ts.map +1 -1
  192. package/dist/modules/tool-auth/external-api-key.service.js +59 -2
  193. package/dist/modules/tool-auth/external-api-key.service.js.map +1 -1
  194. package/dist/modules/tool-auth/tool-auth.middleware.d.ts.map +1 -1
  195. package/dist/modules/tool-auth/tool-auth.middleware.js +9 -4
  196. package/dist/modules/tool-auth/tool-auth.middleware.js.map +1 -1
  197. package/dist/modules/tool-helpers/index.d.ts +28 -1
  198. package/dist/modules/tool-helpers/index.d.ts.map +1 -1
  199. package/dist/modules/tool-helpers/index.js +28 -1
  200. package/dist/modules/tool-helpers/index.js.map +1 -1
  201. package/dist/modules/tool-helpers/route-argument-check.d.ts +10 -0
  202. package/dist/modules/tool-helpers/route-argument-check.d.ts.map +1 -0
  203. package/dist/modules/tool-helpers/route-argument-check.js +132 -0
  204. package/dist/modules/tool-helpers/route-argument-check.js.map +1 -0
  205. package/dist/modules/tool-helpers/route-tool-schemas.d.ts +89 -0
  206. package/dist/modules/tool-helpers/route-tool-schemas.d.ts.map +1 -0
  207. package/dist/modules/tool-helpers/route-tool-schemas.js +113 -0
  208. package/dist/modules/tool-helpers/route-tool-schemas.js.map +1 -0
  209. package/dist/modules/tool-helpers/tool-def.d.ts +71 -0
  210. package/dist/modules/tool-helpers/tool-def.d.ts.map +1 -1
  211. package/dist/modules/tool-helpers/tool-def.js +70 -6
  212. package/dist/modules/tool-helpers/tool-def.js.map +1 -1
  213. package/dist/modules/tool-helpers/tool-handler.d.ts +46 -6
  214. package/dist/modules/tool-helpers/tool-handler.d.ts.map +1 -1
  215. package/dist/modules/tool-helpers/tool-handler.js +157 -8
  216. package/dist/modules/tool-helpers/tool-handler.js.map +1 -1
  217. package/dist/modules/tool-helpers/tool.contract.d.ts +9 -0
  218. package/dist/modules/tool-helpers/tool.contract.d.ts.map +1 -1
  219. package/dist/modules/tool-helpers/tool.contract.js.map +1 -1
  220. package/dist/modules/tool-manuals/tool-manuals.tools.d.ts.map +1 -1
  221. package/dist/modules/tool-manuals/tool-manuals.tools.js +14 -5
  222. package/dist/modules/tool-manuals/tool-manuals.tools.js.map +1 -1
  223. package/dist/modules/tool-registry/description-length.d.ts +6 -2
  224. package/dist/modules/tool-registry/description-length.d.ts.map +1 -1
  225. package/dist/modules/tool-registry/description-length.js +27 -5
  226. package/dist/modules/tool-registry/description-length.js.map +1 -1
  227. package/dist/modules/tool-registry/guide-first.d.ts +4 -0
  228. package/dist/modules/tool-registry/guide-first.d.ts.map +1 -1
  229. package/dist/modules/tool-registry/guide-first.js +9 -1
  230. package/dist/modules/tool-registry/guide-first.js.map +1 -1
  231. package/dist/modules/workflow/agent-tools/change-request-read.tools.d.ts +53 -0
  232. package/dist/modules/workflow/agent-tools/change-request-read.tools.d.ts.map +1 -1
  233. package/dist/modules/workflow/agent-tools/change-request-read.tools.js +97 -68
  234. package/dist/modules/workflow/agent-tools/change-request-read.tools.js.map +1 -1
  235. package/dist/modules/workflow/agent-tools/workflow.tools.d.ts +8 -1
  236. package/dist/modules/workflow/agent-tools/workflow.tools.d.ts.map +1 -1
  237. package/dist/modules/workflow/agent-tools/workflow.tools.js +124 -37
  238. package/dist/modules/workflow/agent-tools/workflow.tools.js.map +1 -1
  239. package/dist/modules/workflow/file-lock.service.d.ts +29 -5
  240. package/dist/modules/workflow/file-lock.service.d.ts.map +1 -1
  241. package/dist/modules/workflow/file-lock.service.js +62 -5
  242. package/dist/modules/workflow/file-lock.service.js.map +1 -1
  243. package/dist/modules/workflow/git/git.service.d.ts +72 -1
  244. package/dist/modules/workflow/git/git.service.d.ts.map +1 -1
  245. package/dist/modules/workflow/git/git.service.js +172 -36
  246. package/dist/modules/workflow/git/git.service.js.map +1 -1
  247. package/dist/modules/workflow/git/node-git-runner.d.ts +15 -0
  248. package/dist/modules/workflow/git/node-git-runner.d.ts.map +1 -1
  249. package/dist/modules/workflow/git/node-git-runner.js +78 -6
  250. package/dist/modules/workflow/git/node-git-runner.js.map +1 -1
  251. package/dist/modules/workflow/pending-commits.service.d.ts +15 -0
  252. package/dist/modules/workflow/pending-commits.service.d.ts.map +1 -1
  253. package/dist/modules/workflow/pending-commits.service.js +25 -1
  254. package/dist/modules/workflow/pending-commits.service.js.map +1 -1
  255. package/dist/modules/workflow/pending-commits.worker.d.ts +6 -1
  256. package/dist/modules/workflow/pending-commits.worker.d.ts.map +1 -1
  257. package/dist/modules/workflow/pending-commits.worker.js +23 -6
  258. package/dist/modules/workflow/pending-commits.worker.js.map +1 -1
  259. package/dist/modules/workflow/recovery-bot.js +1 -1
  260. package/dist/modules/workflow/recovery-bot.js.map +1 -1
  261. package/dist/modules/workflow/review-workflow/review-workflow.service.d.ts.map +1 -1
  262. package/dist/modules/workflow/review-workflow/review-workflow.service.js +2 -1
  263. package/dist/modules/workflow/review-workflow/review-workflow.service.js.map +1 -1
  264. package/dist/modules/workflow/sanitize-error.d.ts +16 -0
  265. package/dist/modules/workflow/sanitize-error.d.ts.map +1 -1
  266. package/dist/modules/workflow/sanitize-error.js +45 -0
  267. package/dist/modules/workflow/sanitize-error.js.map +1 -1
  268. package/dist/modules/workflow/workflow.service.d.ts +183 -15
  269. package/dist/modules/workflow/workflow.service.d.ts.map +1 -1
  270. package/dist/modules/workflow/workflow.service.js +805 -106
  271. package/dist/modules/workflow/workflow.service.js.map +1 -1
  272. package/dist/modules/workspace/agent-download.builder.d.ts +105 -0
  273. package/dist/modules/workspace/agent-download.builder.d.ts.map +1 -0
  274. package/dist/modules/workspace/agent-download.builder.js +238 -0
  275. package/dist/modules/workspace/agent-download.builder.js.map +1 -0
  276. package/dist/modules/workspace/agent-download.routes.d.ts +77 -0
  277. package/dist/modules/workspace/agent-download.routes.d.ts.map +1 -0
  278. package/dist/modules/workspace/agent-download.routes.js +156 -0
  279. package/dist/modules/workspace/agent-download.routes.js.map +1 -0
  280. package/dist/modules/workspace/agent-download.store.d.ts +225 -0
  281. package/dist/modules/workspace/agent-download.store.d.ts.map +1 -0
  282. package/dist/modules/workspace/agent-download.store.js +423 -0
  283. package/dist/modules/workspace/agent-download.store.js.map +1 -0
  284. package/dist/modules/workspace/agent-upload.store.d.ts +10 -1
  285. package/dist/modules/workspace/agent-upload.store.d.ts.map +1 -1
  286. package/dist/modules/workspace/agent-upload.store.js +16 -6
  287. package/dist/modules/workspace/agent-upload.store.js.map +1 -1
  288. package/dist/modules/workspace/file-readers/raw-mime.d.ts +6 -0
  289. package/dist/modules/workspace/file-readers/raw-mime.d.ts.map +1 -0
  290. package/dist/modules/workspace/file-readers/raw-mime.js +38 -0
  291. package/dist/modules/workspace/file-readers/raw-mime.js.map +1 -0
  292. package/dist/modules/workspace/file-readers/text-reader.d.ts +5 -5
  293. package/dist/modules/workspace/file-readers/text-reader.d.ts.map +1 -1
  294. package/dist/modules/workspace/file-readers/text-reader.js +5 -8
  295. package/dist/modules/workspace/file-readers/text-reader.js.map +1 -1
  296. package/dist/modules/workspace/first-run.d.ts +111 -0
  297. package/dist/modules/workspace/first-run.d.ts.map +1 -0
  298. package/dist/modules/workspace/first-run.js +181 -0
  299. package/dist/modules/workspace/first-run.js.map +1 -0
  300. package/dist/modules/workspace/move-links.d.ts +92 -0
  301. package/dist/modules/workspace/move-links.d.ts.map +1 -0
  302. package/dist/modules/workspace/move-links.js +173 -0
  303. package/dist/modules/workspace/move-links.js.map +1 -0
  304. package/dist/modules/workspace/startup/steps/seed-tree.d.ts.map +1 -1
  305. package/dist/modules/workspace/startup/steps/seed-tree.js +3 -13
  306. package/dist/modules/workspace/startup/steps/seed-tree.js.map +1 -1
  307. package/dist/modules/workspace/workspace.routes.d.ts.map +1 -1
  308. package/dist/modules/workspace/workspace.routes.js +63 -22
  309. package/dist/modules/workspace/workspace.routes.js.map +1 -1
  310. package/dist/modules/workspace/workspace.service.d.ts +75 -2
  311. package/dist/modules/workspace/workspace.service.d.ts.map +1 -1
  312. package/dist/modules/workspace/workspace.service.js +197 -24
  313. package/dist/modules/workspace/workspace.service.js.map +1 -1
  314. package/dist/modules/workspace/workspace.tools.d.ts +59 -1
  315. package/dist/modules/workspace/workspace.tools.d.ts.map +1 -1
  316. package/dist/modules/workspace/workspace.tools.js +443 -65
  317. package/dist/modules/workspace/workspace.tools.js.map +1 -1
  318. package/dist/modules/write-access/write-access.d.ts.map +1 -1
  319. package/dist/modules/write-access/write-access.js +9 -0
  320. package/dist/modules/write-access/write-access.js.map +1 -1
  321. package/dist/shared/domain-errors.d.ts +73 -1
  322. package/dist/shared/domain-errors.d.ts.map +1 -1
  323. package/dist/shared/domain-errors.js +86 -12
  324. package/dist/shared/domain-errors.js.map +1 -1
  325. package/dist/shared/git.contract.d.ts +10 -1
  326. package/dist/shared/git.contract.d.ts.map +1 -1
  327. package/dist/shared/git.contract.js.map +1 -1
  328. package/dist/shared/utf8-text.d.ts +15 -0
  329. package/dist/shared/utf8-text.d.ts.map +1 -0
  330. package/dist/shared/utf8-text.js +20 -0
  331. package/dist/shared/utf8-text.js.map +1 -0
  332. package/dist/tenancy/static-tenant-source.d.ts +2 -1
  333. package/dist/tenancy/static-tenant-source.d.ts.map +1 -1
  334. package/dist/tenancy/static-tenant-source.js +9 -2
  335. package/dist/tenancy/static-tenant-source.js.map +1 -1
  336. package/mcp-app/page.html +349 -0
  337. package/migrations/0017_atlassian_account_links.sql +37 -0
  338. package/migrations/meta/0017_snapshot.json +2396 -0
  339. package/migrations/meta/_journal.json +8 -1
  340. package/package.json +5 -3
  341. package/src/__tests__/packaged-assets-ship.test.ts +16 -4
  342. package/src/assets.ts +28 -2
  343. package/src/core/__tests__/catalog-revision.test.ts +40 -0
  344. package/src/core/__tests__/gated-boot.test.ts +1 -0
  345. package/src/core/__tests__/lifecycle.test.ts +14 -0
  346. package/src/core/catalog-revision.ts +15 -2
  347. package/src/core/create-core-server.ts +67 -3
  348. package/src/core/create-core-services.ts +140 -6
  349. package/src/core/lifecycle.ts +28 -2
  350. package/src/core-config.ts +24 -1
  351. package/src/index.ts +2 -2
  352. package/src/modules/access/__tests__/access-control.service.test.ts +19 -0
  353. package/src/modules/access/access-control.interface.ts +13 -0
  354. package/src/modules/access/access-control.service.ts +16 -0
  355. package/src/modules/access/directory-sync-bot.ts +1 -1
  356. package/src/modules/agent-guide/__tests__/agent-guide.test.ts +58 -0
  357. package/src/modules/agent-guide/__tests__/agent-guide.tools.test.ts +19 -1
  358. package/src/modules/agent-guide/agent-guide.ts +9 -0
  359. package/src/modules/agent-guide/index.ts +1 -0
  360. package/src/modules/agent-instructions/__tests__/shared-file-rules.test.ts +14 -0
  361. package/src/modules/agent-instructions/compose.ts +17 -2
  362. package/src/modules/agent-instructions/shared-file-rules.ts +19 -19
  363. package/src/modules/audit/__tests__/agent-audit.service.test.ts +64 -4
  364. package/src/modules/audit/__tests__/agent-connection.routes.test.ts +102 -0
  365. package/src/modules/audit/agent-audit.service.ts +58 -3
  366. package/src/modules/audit/agent-connection.routes.ts +56 -0
  367. package/src/modules/audit/audit.contract.ts +26 -0
  368. package/src/modules/audit/index.ts +1 -0
  369. package/src/modules/auth/__tests__/account.routes.test.ts +5 -3
  370. package/src/modules/auth/account.routes.ts +10 -3
  371. package/src/modules/auth/auth.middleware.ts +1 -1
  372. package/src/modules/code-mode/__tests__/code-mode.tool.test.ts +18 -2
  373. package/src/modules/code-mode/code-mode.tool.ts +13 -2
  374. package/src/modules/database/core-schema.ts +33 -3
  375. package/src/modules/embed/__tests__/account-links.migration.test.ts +98 -0
  376. package/src/modules/embed/__tests__/embed-link.test.ts +122 -0
  377. package/src/modules/embed/__tests__/embed.routes.test.ts +362 -0
  378. package/src/modules/embed/__tests__/embed.service.lock.test.ts +193 -0
  379. package/src/modules/embed/__tests__/embed.service.test.ts +805 -0
  380. package/src/modules/embed/__tests__/embed.tools.test.ts +304 -0
  381. package/src/modules/embed/__tests__/mcp-app.test.ts +207 -0
  382. package/src/modules/embed/account-link.service.ts +76 -0
  383. package/src/modules/embed/embed-link.ts +180 -0
  384. package/src/modules/embed/embed.errors.ts +43 -0
  385. package/src/modules/embed/embed.interface.ts +203 -0
  386. package/src/modules/embed/embed.routes.ts +363 -0
  387. package/src/modules/embed/embed.service.ts +705 -0
  388. package/src/modules/embed/embed.tools.ts +206 -0
  389. package/src/modules/embed/mcp-app.routes.ts +41 -0
  390. package/src/modules/embed/mcp-app.ts +173 -0
  391. package/src/modules/github-app/__tests__/github-app.test.ts +76 -0
  392. package/src/modules/github-app/github-app.connection.ts +38 -4
  393. package/src/modules/kb-fs/__tests__/move-with-edits.test.ts +304 -0
  394. package/src/modules/kb-fs/locking-filesystem.ts +287 -0
  395. package/src/modules/kb-sync/__tests__/kb-sync.service.test.ts +35 -0
  396. package/src/modules/kb-sync/kb-sync.interface.ts +2 -0
  397. package/src/modules/kb-sync/kb-sync.service.ts +6 -0
  398. package/src/modules/mcp/__tests__/bevel-oauth-provider.test.ts +68 -11
  399. package/src/modules/mcp/__tests__/mcp-proxy-helpers.test.ts +37 -2
  400. package/src/modules/mcp/__tests__/mcp.app.e2e.test.ts +200 -0
  401. package/src/modules/mcp/__tests__/mcp.e2e.test.ts +3 -1
  402. package/src/modules/mcp/__tests__/mcp.service.test.ts +23 -13
  403. package/src/modules/mcp/__tests__/tool-call-interface.e2e.test.ts +499 -0
  404. package/src/modules/mcp/mcp-auth.middleware.ts +2 -1
  405. package/src/modules/mcp/mcp.service.ts +81 -12
  406. package/src/modules/mcp/oauth/bevel-oauth-provider.ts +42 -4
  407. package/src/modules/onboarding/__tests__/onboarding.routes.test.ts +163 -0
  408. package/src/modules/onboarding/__tests__/starter-pack.service.test.ts +635 -0
  409. package/src/modules/onboarding/__tests__/starter-packs.test.ts +169 -0
  410. package/src/modules/onboarding/onboarding.contract.ts +85 -0
  411. package/src/modules/onboarding/onboarding.routes.ts +85 -0
  412. package/src/modules/onboarding/starter-pack.service.ts +580 -0
  413. package/src/modules/onboarding/starter-packs.ts +182 -0
  414. package/src/modules/plugins/__tests__/plugins.tools.test.ts +25 -2
  415. package/src/modules/plugins/index.ts +1 -0
  416. package/src/modules/plugins/plugin-provision.service.ts +22 -1
  417. package/src/modules/plugins/plugins.routes.ts +29 -0
  418. package/src/modules/settings/__tests__/deployment-settings.service.test.ts +150 -1
  419. package/src/modules/settings/__tests__/repository-source.test.ts +9 -0
  420. package/src/modules/settings/deployment-settings.service.ts +131 -1
  421. package/src/modules/settings/repository-source.ts +4 -4
  422. package/src/modules/skills/__tests__/skills.tools.description.test.ts +5 -1
  423. package/src/modules/skills/skills.tools.ts +55 -35
  424. package/src/modules/tool-auth/__tests__/connection-key-rejection.test.ts +32 -0
  425. package/src/modules/tool-auth/__tests__/external-api-key.service.test.ts +65 -0
  426. package/src/modules/tool-auth/connection-key-rejection.ts +13 -3
  427. package/src/modules/tool-auth/external-api-key.interface.ts +9 -0
  428. package/src/modules/tool-auth/external-api-key.service.ts +61 -4
  429. package/src/modules/tool-auth/tool-auth.middleware.ts +13 -4
  430. package/src/modules/tool-helpers/__tests__/branch-declaration.test.ts +502 -0
  431. package/src/modules/tool-helpers/__tests__/route-argument-check.test.ts +337 -0
  432. package/src/modules/tool-helpers/index.ts +34 -1
  433. package/src/modules/tool-helpers/route-argument-check.ts +149 -0
  434. package/src/modules/tool-helpers/route-tool-schemas.ts +171 -0
  435. package/src/modules/tool-helpers/tool-def.ts +132 -7
  436. package/src/modules/tool-helpers/tool-handler.ts +196 -8
  437. package/src/modules/tool-helpers/tool.contract.ts +9 -0
  438. package/src/modules/tool-manuals/tool-manuals.tools.ts +15 -5
  439. package/src/modules/tool-registry/__tests__/own-tool-schemas.test.ts +14 -1
  440. package/src/modules/tool-registry/__tests__/tool-description-length.test.ts +23 -10
  441. package/src/modules/tool-registry/description-length.ts +34 -7
  442. package/src/modules/tool-registry/guide-first.ts +8 -1
  443. package/src/modules/workflow/__tests__/file-lock.service.deletion-gate.test.ts +104 -0
  444. package/src/modules/workflow/__tests__/pending-commits.repository-replaced.test.ts +66 -0
  445. package/src/modules/workflow/__tests__/pending-commits.worker.test.ts +31 -2
  446. package/src/modules/workflow/__tests__/preserve-roles-yaml.test.ts +110 -6
  447. package/src/modules/workflow/__tests__/sanitize-error.test.ts +89 -1
  448. package/src/modules/workflow/__tests__/workflow.routes.push-refused.test.ts +202 -0
  449. package/src/modules/workflow/__tests__/workflow.service.branch-in-use.test.ts +6 -6
  450. package/src/modules/workflow/__tests__/workflow.service.delete-branch.test.ts +1026 -0
  451. package/src/modules/workflow/__tests__/workflow.service.facade.test.ts +468 -10
  452. package/src/modules/workflow/__tests__/workflow.service.folder-proposals.test.ts +4 -0
  453. package/src/modules/workflow/__tests__/workflow.service.releaseLock.test.ts +5 -4
  454. package/src/modules/workflow/__tests__/workflow.service.update-from-target.test.ts +54 -2
  455. package/src/modules/workflow/agent-tools/__tests__/change-request-read.tools.test.ts +41 -5
  456. package/src/modules/workflow/agent-tools/__tests__/workflow.tools.test.ts +127 -2
  457. package/src/modules/workflow/agent-tools/change-request-read.tools.ts +157 -122
  458. package/src/modules/workflow/agent-tools/workflow.tools.ts +129 -35
  459. package/src/modules/workflow/file-lock.service.ts +67 -5
  460. package/src/modules/workflow/git/__tests__/git.service.deleteBranch.test.ts +164 -0
  461. package/src/modules/workflow/git/__tests__/git.service.pull.test.ts +48 -1
  462. package/src/modules/workflow/git/__tests__/node-git-runner.test.ts +231 -2
  463. package/src/modules/workflow/git/git.service.ts +176 -38
  464. package/src/modules/workflow/git/node-git-runner.ts +82 -7
  465. package/src/modules/workflow/pending-commits.service.ts +29 -1
  466. package/src/modules/workflow/pending-commits.worker.ts +24 -6
  467. package/src/modules/workflow/recovery-bot.ts +1 -1
  468. package/src/modules/workflow/review-workflow/review-workflow.service.ts +2 -1
  469. package/src/modules/workflow/sanitize-error.ts +50 -0
  470. package/src/modules/workflow/workflow.service.ts +879 -112
  471. package/src/modules/workspace/__tests__/agent-downloads.test.ts +823 -0
  472. package/src/modules/workspace/__tests__/first-run.test.ts +234 -0
  473. package/src/modules/workspace/__tests__/git-internals.security.test.ts +5 -2
  474. package/src/modules/workspace/__tests__/md-links.test.ts +353 -0
  475. package/src/modules/workspace/__tests__/move-links.test.ts +261 -0
  476. package/src/modules/workspace/__tests__/rest-tool-arguments.test.ts +219 -0
  477. package/src/modules/workspace/__tests__/workspace-paths-inside-the-repo.test.ts +3 -0
  478. package/src/modules/workspace/__tests__/workspace.routes.delete.test.ts +102 -0
  479. package/src/modules/workspace/__tests__/workspace.routes.download.test.ts +52 -5
  480. package/src/modules/workspace/__tests__/workspace.routes.folder-zip-access.test.ts +190 -0
  481. package/src/modules/workspace/__tests__/workspace.service.forget-clone-races.test.ts +8 -4
  482. package/src/modules/workspace/__tests__/workspace.service.test.ts +50 -8
  483. package/src/modules/workspace/__tests__/workspace.tools.branch-errors.test.ts +44 -1
  484. package/src/modules/workspace/__tests__/workspace.tools.test.ts +409 -12
  485. package/src/modules/workspace/agent-download.builder.ts +308 -0
  486. package/src/modules/workspace/agent-download.routes.ts +183 -0
  487. package/src/modules/workspace/agent-download.store.ts +533 -0
  488. package/src/modules/workspace/agent-upload.store.ts +23 -7
  489. package/src/modules/workspace/file-readers/raw-mime.ts +40 -0
  490. package/src/modules/workspace/file-readers/text-reader.ts +5 -8
  491. package/src/modules/workspace/first-run.ts +222 -0
  492. package/src/modules/workspace/move-links.ts +237 -0
  493. package/src/modules/workspace/startup/steps/seed-tree.ts +3 -12
  494. package/src/modules/workspace/workspace.routes.ts +64 -22
  495. package/src/modules/workspace/workspace.service.ts +202 -25
  496. package/src/modules/workspace/workspace.tools.ts +492 -63
  497. package/src/modules/write-access/__tests__/write-access.test.ts +13 -0
  498. package/src/modules/write-access/write-access.ts +9 -0
  499. package/src/shared/domain-errors.ts +108 -11
  500. package/src/shared/git.contract.ts +8 -1
  501. package/src/shared/utf8-text.ts +21 -0
  502. package/src/tenancy/__tests__/static-tenant-source.test.ts +1 -0
  503. package/src/tenancy/static-tenant-source.ts +10 -2
  504. package/starter-packs/README.md +103 -0
  505. package/starter-packs/engineering/KnowledgeBase/About us.md +9 -0
  506. package/starter-packs/engineering/KnowledgeBase/Architecture.md +9 -0
  507. package/starter-packs/engineering/KnowledgeBase/Glossary.md +9 -0
  508. package/starter-packs/engineering/KnowledgeBase/How we ship.md +9 -0
  509. package/starter-packs/engineering/Plugins/engineering-starter/LICENSE +21 -0
  510. package/starter-packs/engineering/Plugins/engineering-starter/SOURCE.md +20 -0
  511. package/starter-packs/engineering/Plugins/engineering-starter/access.md +19 -0
  512. package/starter-packs/engineering/Plugins/engineering-starter/plugin.json +10 -0
  513. package/starter-packs/engineering/Plugins/engineering-starter/skills/office-hours/SKILL.md +171 -0
  514. package/starter-packs/engineering/Plugins/engineering-starter/skills/office-hours/sections/phase-2a-startup-diagnostic.md +157 -0
  515. package/starter-packs/engineering/Plugins/engineering-starter/skills/office-hours/sections/phase-2b-builder-brainstorm.md +39 -0
  516. package/starter-packs/engineering/Plugins/engineering-starter/skills/plan-ceo-review/SKILL.md +144 -0
  517. package/starter-packs/engineering/Plugins/engineering-starter/skills/plan-eng-review/SKILL.md +144 -0
  518. package/starter-packs/engineering/Plugins/engineering-starter/skills/review/SKILL.md +80 -0
  519. package/starter-packs/engineering/Plugins/engineering-starter/skills/review/checklist.md +184 -0
  520. package/starter-packs/engineering/pack.yaml +11 -0
  521. package/starter-packs/general/KnowledgeBase/About us.md +9 -0
  522. package/starter-packs/general/KnowledgeBase/Glossary.md +9 -0
  523. package/starter-packs/general/KnowledgeBase/How we work.md +9 -0
  524. package/starter-packs/general/Plugins/general-starter/LICENSE +202 -0
  525. package/starter-packs/general/Plugins/general-starter/SOURCE.md +10 -0
  526. package/starter-packs/general/Plugins/general-starter/access.md +19 -0
  527. package/starter-packs/general/Plugins/general-starter/plugin.json +10 -0
  528. package/starter-packs/general/Plugins/general-starter/skills/memory-management/SKILL.md +332 -0
  529. package/starter-packs/general/Plugins/general-starter/skills/productivity-start/SKILL.md +163 -0
  530. package/starter-packs/general/Plugins/general-starter/skills/productivity-update/SKILL.md +167 -0
  531. package/starter-packs/general/Plugins/general-starter/skills/task-management/SKILL.md +83 -0
  532. package/starter-packs/general/pack.yaml +10 -0
  533. package/starter-packs/operations/KnowledgeBase/Glossary.md +9 -0
  534. package/starter-packs/operations/KnowledgeBase/How we work.md +9 -0
  535. package/starter-packs/operations/KnowledgeBase/Processes.md +9 -0
  536. package/starter-packs/operations/KnowledgeBase/Tools we use.md +9 -0
  537. package/starter-packs/operations/KnowledgeBase/Vendors.md +9 -0
  538. package/starter-packs/operations/Plugins/operations-starter/LICENSE +202 -0
  539. package/starter-packs/operations/Plugins/operations-starter/SOURCE.md +10 -0
  540. package/starter-packs/operations/Plugins/operations-starter/access.md +19 -0
  541. package/starter-packs/operations/Plugins/operations-starter/plugin.json +10 -0
  542. package/starter-packs/operations/Plugins/operations-starter/skills/capacity-plan/SKILL.md +111 -0
  543. package/starter-packs/operations/Plugins/operations-starter/skills/change-request/SKILL.md +119 -0
  544. package/starter-packs/operations/Plugins/operations-starter/skills/compliance-tracking/SKILL.md +44 -0
  545. package/starter-packs/operations/Plugins/operations-starter/skills/process-doc/SKILL.md +80 -0
  546. package/starter-packs/operations/Plugins/operations-starter/skills/process-optimization/SKILL.md +39 -0
  547. package/starter-packs/operations/Plugins/operations-starter/skills/risk-assessment/SKILL.md +40 -0
  548. package/starter-packs/operations/Plugins/operations-starter/skills/runbook/SKILL.md +85 -0
  549. package/starter-packs/operations/Plugins/operations-starter/skills/status-report/SKILL.md +75 -0
  550. package/starter-packs/operations/Plugins/operations-starter/skills/vendor-review/SKILL.md +102 -0
  551. package/starter-packs/operations/pack.yaml +12 -0
  552. package/starter-packs/sales/KnowledgeBase/About us.md +9 -0
  553. package/starter-packs/sales/KnowledgeBase/Customers.md +9 -0
  554. package/starter-packs/sales/KnowledgeBase/Glossary.md +9 -0
  555. package/starter-packs/sales/KnowledgeBase/How we sell.md +9 -0
  556. package/starter-packs/sales/KnowledgeBase/Objections.md +9 -0
  557. package/starter-packs/sales/KnowledgeBase/Pricing.md +9 -0
  558. package/starter-packs/sales/Plugins/sales-starter/LICENSE +202 -0
  559. package/starter-packs/sales/Plugins/sales-starter/SOURCE.md +10 -0
  560. package/starter-packs/sales/Plugins/sales-starter/access.md +19 -0
  561. package/starter-packs/sales/Plugins/sales-starter/plugin.json +10 -0
  562. package/starter-packs/sales/Plugins/sales-starter/skills/account-context/SKILL.md +94 -0
  563. package/starter-packs/sales/Plugins/sales-starter/skills/account-plan/SKILL.md +95 -0
  564. package/starter-packs/sales/Plugins/sales-starter/skills/account-research/SKILL.md +99 -0
  565. package/starter-packs/sales/Plugins/sales-starter/skills/account-tiering/SKILL.md +101 -0
  566. package/starter-packs/sales/Plugins/sales-starter/skills/call-prep/SKILL.md +111 -0
  567. package/starter-packs/sales/Plugins/sales-starter/skills/call-summary/SKILL.md +111 -0
  568. package/starter-packs/sales/Plugins/sales-starter/skills/close-plan/SKILL.md +106 -0
  569. package/starter-packs/sales/Plugins/sales-starter/skills/competitive-intelligence/SKILL.md +102 -0
  570. package/starter-packs/sales/Plugins/sales-starter/skills/create-an-asset/SKILL.md +105 -0
  571. package/starter-packs/sales/Plugins/sales-starter/skills/crm-hygiene-check/SKILL.md +103 -0
  572. package/starter-packs/sales/Plugins/sales-starter/skills/customer-health/SKILL.md +108 -0
  573. package/starter-packs/sales/Plugins/sales-starter/skills/customer-voice/SKILL.md +94 -0
  574. package/starter-packs/sales/Plugins/sales-starter/skills/daily-briefing/SKILL.md +61 -0
  575. package/starter-packs/sales/Plugins/sales-starter/skills/deal-advance-gap/SKILL.md +102 -0
  576. package/starter-packs/sales/Plugins/sales-starter/skills/deal-review/SKILL.md +105 -0
  577. package/starter-packs/sales/Plugins/sales-starter/skills/deal-signals/SKILL.md +96 -0
  578. package/starter-packs/sales/Plugins/sales-starter/skills/deal-slip-scenario/SKILL.md +104 -0
  579. package/starter-packs/sales/Plugins/sales-starter/skills/draft-outreach/SKILL.md +116 -0
  580. package/starter-packs/sales/Plugins/sales-starter/skills/end-of-day/SKILL.md +114 -0
  581. package/starter-packs/sales/Plugins/sales-starter/skills/expansion-whitespace/SKILL.md +97 -0
  582. package/starter-packs/sales/Plugins/sales-starter/skills/forecast/SKILL.md +100 -0
  583. package/starter-packs/sales/Plugins/sales-starter/skills/handle-objection/SKILL.md +93 -0
  584. package/starter-packs/sales/Plugins/sales-starter/skills/inbox-sweep/SKILL.md +114 -0
  585. package/starter-packs/sales/Plugins/sales-starter/skills/lead-triage/SKILL.md +106 -0
  586. package/starter-packs/sales/Plugins/sales-starter/skills/log-activity/SKILL.md +111 -0
  587. package/starter-packs/sales/Plugins/sales-starter/skills/pipeline-review/SKILL.md +97 -0
  588. package/starter-packs/sales/Plugins/sales-starter/skills/renewal-radar/SKILL.md +95 -0
  589. package/starter-packs/sales/Plugins/sales-starter/skills/rep-context/SKILL.md +90 -0
  590. package/starter-packs/sales/Plugins/sales-starter/skills/route-lead/SKILL.md +111 -0
  591. package/starter-packs/sales/Plugins/sales-starter/skills/sales-setup/SKILL.md +200 -0
  592. package/starter-packs/sales/Plugins/sales-starter/skills/schedule-meeting/SKILL.md +99 -0
  593. package/starter-packs/sales/Plugins/sales-starter/skills/stakeholder-map/SKILL.md +107 -0
  594. package/starter-packs/sales/Plugins/sales-starter/skills/team-pipeline/SKILL.md +105 -0
  595. package/starter-packs/sales/Plugins/sales-starter/skills/update-opportunity/SKILL.md +112 -0
  596. package/starter-packs/sales/Plugins/sales-starter/skills/weekly-wrap/SKILL.md +90 -0
  597. package/starter-packs/sales/Plugins/sales-starter/skills/win-loss-review/SKILL.md +88 -0
  598. package/starter-packs/sales/pack.yaml +13 -0
  599. package/starter-packs/support/KnowledgeBase/Escalations.md +9 -0
  600. package/starter-packs/support/KnowledgeBase/Glossary.md +9 -0
  601. package/starter-packs/support/KnowledgeBase/Known issues.md +9 -0
  602. package/starter-packs/support/KnowledgeBase/Products.md +9 -0
  603. package/starter-packs/support/KnowledgeBase/Tone of voice.md +9 -0
  604. package/starter-packs/support/Plugins/support-starter/LICENSE +202 -0
  605. package/starter-packs/support/Plugins/support-starter/SOURCE.md +10 -0
  606. package/starter-packs/support/Plugins/support-starter/access.md +19 -0
  607. package/starter-packs/support/Plugins/support-starter/plugin.json +10 -0
  608. package/starter-packs/support/Plugins/support-starter/skills/customer-escalation/SKILL.md +246 -0
  609. package/starter-packs/support/Plugins/support-starter/skills/customer-research/SKILL.md +250 -0
  610. package/starter-packs/support/Plugins/support-starter/skills/draft-response/SKILL.md +416 -0
  611. package/starter-packs/support/Plugins/support-starter/skills/kb-article/SKILL.md +350 -0
  612. package/starter-packs/support/Plugins/support-starter/skills/ticket-triage/SKILL.md +273 -0
  613. package/starter-packs/support/pack.yaml +12 -0
@@ -27,6 +27,9 @@ const syncLog = logger('sync');
27
27
  const lockLog = logger('lock');
28
28
  const crLog = logger('cr');
29
29
  const mergeLog = logger('merge');
30
+
31
+ /** Who the leftover cleanup deletes as. Its deletions skip the authorship check, and the log names them `system`. */
32
+ const SYSTEM_ACTOR: AuthUser = { id: 'system', email: 'system', name: 'system' };
30
33
  import { promises as fs } from 'node:fs';
31
34
  import { execFile } from 'node:child_process';
32
35
  import { promisify } from 'node:util';
@@ -46,6 +49,8 @@ import type {
46
49
  ChangeRequestUpdateResult,
47
50
  ChangeRequestState,
48
51
  ChangedFile,
52
+ DeleteBranchPreview,
53
+ DeleteBranchResult,
49
54
  FileApproval,
50
55
  FileLock,
51
56
  FolderChangeRequest,
@@ -77,15 +82,20 @@ import { FileLockService } from './file-lock.service.js';
77
82
  import { canonicalFileIdentity } from '../../shared/canonical-file-identity.js';
78
83
  import { PendingCommitsService } from './pending-commits.service.js';
79
84
  import type { WorkflowEventBus } from './event-bus.js';
80
- import { sanitizeError } from './sanitize-error.js';
85
+ import { describeSyncFailure, sanitizeError } from './sanitize-error.js';
81
86
  import type { FileChangeNotifier } from '../kb-fs/file-change-notifier.js';
82
87
  import { WorkflowHooks } from './workflow-hooks.js';
83
88
  import { WorkspaceMutex } from '../kb-fs/mutex.js';
89
+ import { assertValidBranchName } from '../kb-fs/branch-name.js';
84
90
  import { canonicalEmail, hashEmail } from '../../shared/email-identity.js';
85
91
  import {
92
+ BranchAuthorshipError,
93
+ BranchDeleteBlockedError,
94
+ BranchNotFoundError,
86
95
  ChangeRequestConflictsError,
87
96
  DuplicateChangeRequestError,
88
97
  OpenChangeRequestBlocksMergeError,
98
+ ProtectedBranchError,
89
99
  RolesYamlPreservationError,
90
100
  PullRebaseConflictError,
91
101
  PushNeedsAgentResolutionError,
@@ -484,9 +494,19 @@ export class WorkflowService implements IWorkflowService {
484
494
  // request has to be withdrawn or declined first. `systemCleanup` does
485
495
  // its own open-request check under this same lock, and the legacy
486
496
  // `onlyIfNoRemote` prune only fires when origin no longer has the ref.
497
+ // A request that proposes nothing any more is closed first, and then
498
+ // blocks nothing. Only for a caller the deletion would go ahead for: a
499
+ // refused deletion changes nothing, a closed request included — so one
500
+ // that fails after the close reopens what it closed.
501
+ let closed: number[] = [];
487
502
  if (!opts?.systemCleanup && !opts?.onlyIfNoRemote) {
488
- const open = await this.openChangeRequestOn(name);
503
+ let open = await this.openChangeRequestOn(name);
504
+ if (open !== null && !this.kb.isProtectedBranch(name) && (await this.mayDelete(workspaceId, name, user))) {
505
+ closed = await this.closeEmptyRequestsOn(name, user.id, { workspaceId, fresh: false });
506
+ open = await this.openChangeRequestOn(name);
507
+ }
489
508
  if (open !== null) {
509
+ await this.reopenAfterFailedDelete(closed, name, user.id);
490
510
  // Two different situations, two different actors. A request FROM
491
511
  // this branch is the deleter's own to withdraw; a request INTO it
492
512
  // belongs to someone else, and telling the branch owner to
@@ -501,7 +521,12 @@ export class WorkflowService implements IWorkflowService {
501
521
  );
502
522
  }
503
523
  }
504
- await this.deleteBranchUnlocked(workspaceId, name, user, opts);
524
+ try {
525
+ await this.deleteBranchUnlocked(workspaceId, name, user, opts);
526
+ } catch (err) {
527
+ await this.reopenAfterFailedDelete(closed, name, user.id);
528
+ throw err;
529
+ }
505
530
  });
506
531
  }
507
532
 
@@ -510,9 +535,15 @@ export class WorkflowService implements IWorkflowService {
510
535
  workspaceId: string,
511
536
  name: string,
512
537
  user: AuthUser,
513
- opts?: { onlyIfNoRemote?: boolean; systemCleanup?: boolean },
514
- ): Promise<void> {
515
- await this.git.deleteBranch(workspaceId, name, user, opts);
538
+ opts?: { onlyIfNoRemote?: boolean; systemCleanup?: boolean; expectTip?: string },
539
+ ): Promise<{ lastCommit: string | null }> {
540
+ const { lastCommit } = await this.git.deleteBranch(workspaceId, name, user, opts);
541
+ // One line per deletion, whoever asked: the commit is what a restore
542
+ // starts from, and for a deletion made in the app or by the cleanup this
543
+ // line is the only trace there is.
544
+ // By id, never by address: log lines carry no email (the release's own promise).
545
+ const actor = opts?.systemCleanup ? 'system' : user.id;
546
+ log.info(`branch deleted by ${actor}: "${name}" at ${lastCommit ?? '(no commit)'}`);
516
547
  // Retire the deleted branch's own workspace clone, best-effort. A stale
517
548
  // clone left on disk would be silently REUSED if the branch name is ever
518
549
  // recreated (the workspace bootstrap short-circuits on an existing
@@ -525,6 +556,360 @@ export class WorkflowService implements IWorkflowService {
525
556
  } catch (err) {
526
557
  log.warn(`could not retire workspace clone of deleted branch "${name}":`, { err });
527
558
  }
559
+ return { lastCommit };
560
+ }
561
+
562
+ /**
563
+ * Every open change request naming `branch`, at either end — the preview's
564
+ * list. `openChangeRequestOn` answers the first one, which is all a refusal
565
+ * needs.
566
+ */
567
+ private async openChangeRequestsOn(
568
+ branch: string,
569
+ ): Promise<{ number: number; end: 'source' | 'target' }[]> {
570
+ const rows = await this.db
571
+ .select({ number: changeRequests.number, sourceBranch: changeRequests.sourceBranch })
572
+ .from(changeRequests)
573
+ .where(
574
+ and(
575
+ or(
576
+ eq(changeRequests.sourceBranch, branch),
577
+ eq(changeRequests.targetBranch, branch),
578
+ ),
579
+ eq(changeRequests.state, 'open'),
580
+ ),
581
+ );
582
+ return rows.map((row) => ({
583
+ number: row.number,
584
+ end: row.sourceBranch === branch ? ('source' as const) : ('target' as const),
585
+ }));
586
+ }
587
+
588
+ /**
589
+ * Whether open change request `summary` proposes nothing at this moment:
590
+ * its changes, recomputed now, are empty, and no save to its source branch
591
+ * is still landing (a save under a held lock or queued for the commit
592
+ * worker is on disk but not yet in the diff). Anything that cannot be
593
+ * determined is a no — a request is never closed on a guess.
594
+ *
595
+ * `workspaceId` is the clone to compute in (any clone will do: the diff is
596
+ * between origin's refs); absent, the source branch's own, as the app's
597
+ * lazy close always did. `fresh` says that clone was just fetched, so the
598
+ * refs are read as they are instead of fetched again per request.
599
+ */
600
+ private async proposesNothing(
601
+ summary: { number: number; branch: string; base: string },
602
+ opts: { workspaceId?: string; fresh?: boolean } = {},
603
+ ): Promise<boolean> {
604
+ try {
605
+ const wsId = opts.workspaceId ?? (await this.workspaceService.getOrCreateForBranch(summary.branch)).id;
606
+ const paths = await this.git.changedPathsForPr(
607
+ wsId,
608
+ summary.base,
609
+ summary.branch,
610
+ opts.fresh ? { fetch: false } : {},
611
+ );
612
+ if (paths.length > 0) return false;
613
+ } catch (err) {
614
+ crLog.warn(`empty-check for change request #${summary.number} failed — leaving it open:`, { err });
615
+ return false;
616
+ }
617
+ return !(await this.savesInFlight(workspaceIdForBranch(summary.branch)));
618
+ }
619
+
620
+ /**
621
+ * Close open change request `number` if it proposes nothing right now
622
+ * ({@link proposesNothing}), recorded as today's empty-close: closed state
623
+ * and closing time, guarded on `state = 'open'` so a concurrent merge or
624
+ * withdrawal wins. Writes the log line every such close owes. Does NOT
625
+ * retire the source branch — the caller decides that, and a caller holding
626
+ * that branch's lifecycle lock must not. Answers the request's target when
627
+ * this call closed it, else null.
628
+ */
629
+ private async closeIfEmpty(
630
+ number: number,
631
+ opts: { reason: string; actor: string; workspaceId?: string; fresh?: boolean },
632
+ ): Promise<{ base: string } | null> {
633
+ const summary = await this.prs.getPr(number);
634
+ if (!summary || summary.state !== 'open') return null;
635
+ if (!(await this.proposesNothing(summary, opts))) return null;
636
+ const now = new Date();
637
+ const updated = await this.db
638
+ .update(changeRequests)
639
+ .set({ state: 'closed', closedAt: now, updatedAt: now })
640
+ .where(and(eq(changeRequests.number, number), eq(changeRequests.state, 'open')))
641
+ .returning({ id: changeRequests.id });
642
+ if (updated.length === 0) return null;
643
+ this.prs.invalidateDetailCache(number);
644
+ this.events?.emit({ kind: 'change-request-rejected', number });
645
+ crLog.info(
646
+ `closed change request #${number} ("${summary.branch}" into "${summary.base}") by ${opts.actor}: ` +
647
+ `it proposes nothing (${opts.reason})`,
648
+ );
649
+ return { base: summary.base };
650
+ }
651
+
652
+ /**
653
+ * The deletion's close-empty move: every open request from or into
654
+ * `branch` that proposes nothing is closed. Best effort per request — one
655
+ * that cannot be judged or closed stays open, and the open-request check
656
+ * after this refuses on it. Never retires a branch: the caller holds
657
+ * `branch`'s lifecycle lock, and the deletion itself removes it. Answers
658
+ * the numbers it closed, so a deletion that then fails can reopen them
659
+ * ({@link reopenAfterFailedDelete}).
660
+ */
661
+ private async closeEmptyRequestsOn(
662
+ branch: string,
663
+ actor: string,
664
+ opts: { workspaceId?: string; fresh?: boolean },
665
+ ): Promise<number[]> {
666
+ const closed: number[] = [];
667
+ for (const cr of await this.openChangeRequestsOn(branch)) {
668
+ try {
669
+ if (await this.closeIfEmpty(cr.number, { ...opts, actor, reason: `empty when "${branch}" was deleted` })) {
670
+ closed.push(cr.number);
671
+ }
672
+ } catch (err) {
673
+ crLog.warn(`could not close empty change request #${cr.number} before deleting "${branch}":`, { err });
674
+ }
675
+ }
676
+ return closed;
677
+ }
678
+
679
+ /**
680
+ * Undo {@link closeEmptyRequestsOn} for a deletion that failed after it: a
681
+ * refused deletion changes nothing, and the requests it closed are open
682
+ * again. Still under the branch's lifecycle lock, so nothing can have
683
+ * merged, withdrawn or declined them in between; guarded on `closed` all
684
+ * the same. Best effort: a request that cannot be reopened is logged.
685
+ */
686
+ private async reopenAfterFailedDelete(numbers: number[], branch: string, actor: string): Promise<void> {
687
+ if (numbers.length === 0) return;
688
+ try {
689
+ const reopened = await this.db
690
+ .update(changeRequests)
691
+ .set({ state: 'open', closedAt: null, updatedAt: new Date() })
692
+ .where(and(inArray(changeRequests.number, numbers), eq(changeRequests.state, 'closed')))
693
+ .returning({ number: changeRequests.number });
694
+ for (const { number } of reopened) {
695
+ this.prs.invalidateDetailCache(number);
696
+ crLog.info(`reopened change request #${number} for ${actor}: deleting "${branch}" failed after it was closed`);
697
+ // The close told every tab the request was gone; announce it back,
698
+ // as an open does, so none keeps leaving it out.
699
+ const summary = await this.prs.getPr(number).catch(() => null);
700
+ if (summary) {
701
+ this.events?.emit({
702
+ kind: 'change-request-opened',
703
+ number,
704
+ source: summary.branch,
705
+ target: summary.base,
706
+ authorIdHash: summary.authorId ?? null,
707
+ title: summary.title,
708
+ });
709
+ }
710
+ }
711
+ } catch (err) {
712
+ crLog.warn(`could not reopen change requests ${numbers.map((n) => `#${n}`).join(', ')} after deleting "${branch}" failed:`, { err });
713
+ }
714
+ }
715
+
716
+ /** The author-or-Admin rule, as a yes/no; a rule that cannot be read is a no. */
717
+ private async mayDelete(workspaceId: string, name: string, user: AuthUser): Promise<boolean> {
718
+ try {
719
+ return await this.git.mayDeleteBranch(workspaceId, name, user);
720
+ } catch {
721
+ return false;
722
+ }
723
+ }
724
+
725
+ /**
726
+ * The refusal for an open request that still proposes something: names it,
727
+ * links to it, and says who can act — its author withdraws it, an Admin can
728
+ * decline it.
729
+ */
730
+ private openRequestRefusal(
731
+ branch: string,
732
+ cr: { number: number; end: 'source' | 'target'; url: string },
733
+ visible = true,
734
+ ): BranchDeleteBlockedError {
735
+ // One the caller may not see is not named, linked or placed at an end:
736
+ // `get_change_request` answers it as not found, and so does this.
737
+ if (!visible) {
738
+ return new BranchDeleteBlockedError(
739
+ 'open-change-request',
740
+ branch,
741
+ `An open change request you cannot see still proposes changes from or into "${branch}". ` +
742
+ `An Admin can decline it in the app; then the branch can be deleted.`,
743
+ );
744
+ }
745
+ return new BranchDeleteBlockedError(
746
+ 'open-change-request',
747
+ branch,
748
+ `Change request #${cr.number} (${cr.url}) is open ${cr.end === 'source' ? 'from' : 'into'} "${branch}" and still ` +
749
+ `proposes changes. Its author can withdraw it, or an Admin can decline it, in the app; then the branch can be deleted.`,
750
+ { number: cr.number, url: cr.url },
751
+ );
752
+ }
753
+
754
+ /**
755
+ * The default branch's workspace, freshly fetched — where an agent's
756
+ * deletion and the leftover cleanup both decide and act. Never the
757
+ * branch's own checkout (which git refuses to delete from), and always
758
+ * after a strict, forced fetch: the refs are about to authorize a
759
+ * deletion, and a fetch that failed proves nothing about them.
760
+ */
761
+ private async freshDefaultWorkspace(): Promise<string> {
762
+ const ws = await this.workspaceService.getOrCreateForBranch(this.kb.defaultBranch);
763
+ await this.workspaceService.ensureRemotesFetched(ws.id, { strict: true, force: true });
764
+ return ws.id;
765
+ }
766
+
767
+ async deleteBranchChecked(
768
+ user: AuthUser,
769
+ name: string,
770
+ opts: { dryRun?: boolean; discardUnmerged?: boolean; maySee?: (number: number) => Promise<boolean> } = {},
771
+ ): Promise<DeleteBranchPreview | DeleteBranchResult> {
772
+ assertValidBranchName(name);
773
+ // The caller's view of a request, as `get_change_request` gives it: one
774
+ // they may not see is never named, linked or judged in an answer. Absent,
775
+ // every request is visible. A verdict that fails is a no.
776
+ const maySee = async (number: number): Promise<boolean> =>
777
+ opts.maySee ? opts.maySee(number).catch(() => false) : true;
778
+ // Under the lock `deleteBranch`, `createBranch` and `openChangeRequest`
779
+ // take, so nothing this answer depends on — a request being opened, the
780
+ // branch being recreated — can change between the checks and the delete.
781
+ // A preview takes it too: it is short, and it then answers a settled state.
782
+ return this.branchLifecycle.run(`branch:${name}`, async () => {
783
+ const isProtected = this.kb.isProtectedBranch(name);
784
+ if (isProtected && !opts.dryRun) throw new ProtectedBranchError(name, 'deleting a protected branch');
785
+
786
+ let wsId: string;
787
+ try {
788
+ wsId = await this.freshDefaultWorkspace();
789
+ } catch (err) {
790
+ log.warn(`delete_branch "${name}": could not fetch the shared repository — deleting nothing:`, { err });
791
+ throw new BranchDeleteBlockedError(
792
+ 'state-unconfirmed',
793
+ name,
794
+ `Could not reach the shared repository to confirm the current state of "${name}", so nothing was deleted. Try again shortly.`,
795
+ );
796
+ }
797
+
798
+ const state = await this.git.branchState(wsId, name, this.kb.defaultBranch);
799
+ if (!state.exists) {
800
+ if (!opts.dryRun) throw new BranchNotFoundError(name);
801
+ return {
802
+ kind: 'preview',
803
+ branch: name,
804
+ exists: false,
805
+ canDelete: false,
806
+ refusals: [new BranchNotFoundError(name).message],
807
+ unmergedCommits: 0,
808
+ openChangeRequests: [],
809
+ lastCommit: null,
810
+ };
811
+ }
812
+
813
+ // Every refusal, in the order a deletion meets them. The preview lists
814
+ // them all; a deletion throws the first.
815
+ const refusals: Error[] = [];
816
+ if (isProtected) refusals.push(new ProtectedBranchError(name, 'deleting a protected branch'));
817
+ if (!(await this.git.mayDeleteBranch(wsId, name, user))) refusals.push(new BranchAuthorshipError(name));
818
+ // Every open request at either end, each judged now: one that proposes
819
+ // nothing is closed by the deletion and blocks nothing; one that still
820
+ // proposes something — or whose changes cannot be determined — blocks.
821
+ // A request the caller may not see is not part of a preview at all —
822
+ // not listed, not judged, not weighed in `canDelete` — so the preview
823
+ // reads the same whether one exists, and whether it is empty. A
824
+ // deletion still closes it or is refused on it like any other, without
825
+ // naming it: the rules above are the deletion's, not the caller's view.
826
+ const open: (DeleteBranchPreview['openChangeRequests'][number] & { visible: boolean })[] = [];
827
+ for (const cr of await this.openChangeRequestsOn(name)) {
828
+ const visible = await maySee(cr.number);
829
+ if (!visible && opts.dryRun) continue;
830
+ const summary = await this.prs.getPr(cr.number).catch(() => null);
831
+ const empty = summary ? await this.proposesNothing(summary, { workspaceId: wsId, fresh: true }) : false;
832
+ open.push({
833
+ ...cr,
834
+ url: summary?.url ?? `/change-requests/${cr.number}`,
835
+ proposesNothing: empty,
836
+ visible,
837
+ });
838
+ }
839
+ const blocking = open.find((cr) => !cr.proposesNothing);
840
+ if (blocking) refusals.push(this.openRequestRefusal(name, blocking, blocking.visible));
841
+ // Not coverable by `discardUnmerged`: these are a person's saves on
842
+ // their way into the branch, not work already on it.
843
+ if (await this.savesInFlight(workspaceIdForBranch(name))) {
844
+ refusals.push(this.savesLandingRefusal(name));
845
+ }
846
+ if (state.unmergedCommits > 0 && !opts.discardUnmerged) {
847
+ const n = state.unmergedCommits;
848
+ refusals.push(
849
+ new BranchDeleteBlockedError(
850
+ 'unmerged-commits',
851
+ name,
852
+ `"${name}" holds ${n} commit${n === 1 ? '' : 's'} that ${n === 1 ? 'is' : 'are'} not on ${this.kb.defaultBranch}; ` +
853
+ `deleting it would lose ${n === 1 ? 'it' : 'them'}. Pass discardUnmerged: true to delete it anyway.`,
854
+ { unmergedCommits: n },
855
+ ),
856
+ );
857
+ }
858
+
859
+ if (opts.dryRun) {
860
+ return {
861
+ kind: 'preview',
862
+ branch: name,
863
+ exists: true,
864
+ canDelete: refusals.length === 0,
865
+ refusals: refusals.map((r) => r.message),
866
+ unmergedCommits: state.unmergedCommits,
867
+ openChangeRequests: open.map(({ number, end, url, proposesNothing }) => ({ number, end, url, proposesNothing })),
868
+ lastCommit: state.lastCommit,
869
+ };
870
+ }
871
+ // A refused deletion changes nothing: no request is closed either.
872
+ if (refusals[0]) throw refusals[0];
873
+
874
+ // The saves check above is a snapshot; a save could take its file lock
875
+ // since. With no lock grantable on the branch, it is made again and
876
+ // nothing can start landing between it and the deletion.
877
+ const { lastCommit } = await this.fileLocks.whileNoneAcquired(name, async () => {
878
+ if (await this.savesInFlight(workspaceIdForBranch(name))) throw this.savesLandingRefusal(name);
879
+ // Every open request proposes nothing: close them, each re-judged at
880
+ // the moment of closing — the last step before the deletion, so no
881
+ // later check can refuse after it. Nothing here takes this branch's
882
+ // lifecycle lock, so a request whose source IS this branch cannot make
883
+ // the deletion wait on itself. Should the deletion still fail (the
884
+ // leased push below), the requests closed here are reopened.
885
+ const closed = await this.closeEmptyRequestsOn(name, user.id, { workspaceId: wsId, fresh: true });
886
+ try {
887
+ const still = (await this.openChangeRequestsOn(name))[0];
888
+ if (still) {
889
+ const summary = await this.prs.getPr(still.number).catch(() => null);
890
+ throw this.openRequestRefusal(
891
+ name,
892
+ { ...still, url: summary?.url ?? `/change-requests/${still.number}` },
893
+ await maySee(still.number),
894
+ );
895
+ }
896
+ // Leased on the tip the checks above were made against, so a commit
897
+ // pushed since is refused by the host instead of deleted unseen.
898
+ return await this.deleteBranchUnlocked(wsId, name, user, {
899
+ ...(state.lastCommit ? { expectTip: state.lastCommit } : {}),
900
+ });
901
+ } catch (err) {
902
+ await this.reopenAfterFailedDelete(closed, name, user.id);
903
+ throw err;
904
+ }
905
+ });
906
+ return {
907
+ kind: 'deleted',
908
+ branch: name,
909
+ lastCommit: lastCommit ?? state.lastCommit ?? '',
910
+ discardedCommits: state.unmergedCommits,
911
+ };
912
+ });
528
913
  }
529
914
 
530
915
  // No `switchBranch` here on purpose. Under the per-branch workspace model,
@@ -545,7 +930,7 @@ export class WorkflowService implements IWorkflowService {
545
930
  // to discard.
546
931
 
547
932
  shareCurrentBranch(workspaceId: string, user: AuthUser): Promise<void> {
548
- return this.trackedPush(workspaceId, user);
933
+ return this.pushWithRecovery(workspaceId, branchForWorkspaceId(workspaceId), '(share)', user);
549
934
  }
550
935
 
551
936
  refreshRemotes(workspaceId: string): Promise<void> {
@@ -695,7 +1080,7 @@ export class WorkflowService implements IWorkflowService {
695
1080
  }
696
1081
  const message = sanitizeError(err);
697
1082
  syncLog.warn(`pull failed for branch "${branch}": ${message}`);
698
- this.noteGitSyncFailed(gitId, branch, err);
1083
+ this.noteGitSyncFailed(gitId, branch, err, undefined, 'pull');
699
1084
  return { branch, outcome: 'error', error: message };
700
1085
  }
701
1086
  // A clean pull is proof origin is reachable and this clone rebases onto
@@ -1097,7 +1482,8 @@ export class WorkflowService implements IWorkflowService {
1097
1482
  });
1098
1483
  } else {
1099
1484
  lockLog.info(
1100
- `ACQUIRE ws=${workspaceId} branch=${branch} path=${targetPath} user=${user.id} → contended, held by ${result.lock.holderName} (${result.lock.holderUserId})`,
1485
+ // The holder by id only: log lines carry no names.
1486
+ `ACQUIRE ws=${workspaceId} branch=${branch} path=${targetPath} user=${user.id} → contended, held by ${result.lock.holderUserId}`,
1101
1487
  );
1102
1488
  }
1103
1489
  return result;
@@ -1183,7 +1569,8 @@ export class WorkflowService implements IWorkflowService {
1183
1569
  let recoveryError: unknown = null;
1184
1570
  if (looksLikeNonFastForward) {
1185
1571
  try {
1186
- await this.pullWorkspace(workspaceId);
1572
+ // Same as `pushWithRecovery`: keep a stranded merge a merge.
1573
+ await this.pullWorkspace(workspaceId, { preserveMerges: true });
1187
1574
  await this.git.push(workspaceId, user);
1188
1575
  recovered = true;
1189
1576
  this.noteGitSyncOk(workspaceId, branch);
@@ -1272,7 +1659,7 @@ export class WorkflowService implements IWorkflowService {
1272
1659
  const lock = await this.fileLocks.get(workspaceId, branch, targetPath);
1273
1660
  if (!lock || lock.holderUserId !== user.id) {
1274
1661
  lockLog.warn(
1275
- `RELEASE refused ws=${workspaceId} branch=${branch} path=${targetPath} user=${user.id} → ${lock ? `held by ${lock.holderName} (${lock.holderUserId})` : 'no lock row'}`,
1662
+ `RELEASE refused ws=${workspaceId} branch=${branch} path=${targetPath} user=${user.id} → ${lock ? `held by ${lock.holderUserId}` : 'no lock row'}`,
1276
1663
  );
1277
1664
  throw new WorkflowValidationError(
1278
1665
  `Cannot release lock on "${targetPath}": not held by you (or no longer exists).`,
@@ -1444,6 +1831,12 @@ export class WorkflowService implements IWorkflowService {
1444
1831
  * hold the sentence pass it; otherwise it is derived below.
1445
1832
  */
1446
1833
  explicitConflict?: { paths: string[]; message: string },
1834
+ /**
1835
+ * Which side of the sync failed. A 403 or "Repository not found" on a
1836
+ * pull means the credentials cannot READ the repository, and telling the
1837
+ * operator to grant push access would send them to the wrong setting.
1838
+ */
1839
+ operation: 'push' | 'pull' = 'push',
1447
1840
  ): void {
1448
1841
  // A rebase conflict is a conflict whichever path ran into it. The remote
1449
1842
  // sync names its files on purpose; the push-recovery paths (autosave, the
@@ -1466,49 +1859,28 @@ export class WorkflowService implements IWorkflowService {
1466
1859
  kind: 'git-sync-failed',
1467
1860
  workspaceId: id,
1468
1861
  branch,
1469
- // Git stderr can quote a credentialed URL; the banner is user-facing and
1470
- // the string also lands in client logs, so sanitize before it leaves.
1471
- reason: conflict ? conflict.message : sanitizeError(err),
1862
+ // Never the git output itself — not even sanitised: stderr quotes the
1863
+ // host's own error text and URLs, and the banner is user-facing. A
1864
+ // fixed sentence says what kind of failure it was; the raw text is in
1865
+ // the server log, where the banner points whoever can act on it.
1866
+ reason: conflict ? conflict.message : describeSyncFailure(err, operation),
1472
1867
  ...(conflict ? { conflictedPaths: conflict.paths } : {}),
1473
1868
  });
1474
1869
  }
1475
1870
 
1476
- /**
1477
- * A bare push wrapped in the sync tracker: a failure raises the banner, a
1478
- * success clears it. For the workflow paths that push directly — sharing a
1479
- * branch, publishing a CR's source, update-from-base, the decline revert,
1480
- * the roles.yaml restore — rather than through `pushWithRecovery`'s
1481
- * cooperative ladder. Behaviour is otherwise unchanged: the error still
1482
- * propagates to the caller exactly as the bare push's did. Without this,
1483
- * those pushes could fail invisibly (no banner) and, worse, a successful
1484
- * share could not CLEAR a banner an earlier save had raised.
1485
- *
1486
- * The branch is derived from the workspace id (they are the same string,
1487
- * URL-encoding aside) so call sites cannot pass a mismatched pair.
1488
- */
1489
- private async trackedPush(
1490
- workspaceId: string,
1491
- user: AuthUser,
1492
- opts?: { systemAuthorized?: boolean },
1493
- ): Promise<void> {
1494
- const branch = branchForWorkspaceId(workspaceId);
1495
- try {
1496
- // Preserve the exact call shape of the bare pushes this replaces — an
1497
- // explicit `undefined` third argument is a different call signature to
1498
- // every spy that asserts on it.
1499
- await (opts ? this.git.push(workspaceId, user, opts) : this.git.push(workspaceId, user));
1500
- this.noteGitSyncOk(workspaceId, branch);
1501
- } catch (err) {
1502
- this.noteGitSyncFailed(workspaceId, branch, err);
1503
- throw err;
1504
- }
1505
- }
1506
-
1507
1871
  /**
1508
1872
  * Shared implementation of "push, and on non-fast-forward try a
1509
1873
  * cooperative pull-rebase + retry, then hand off to the agent if that
1510
1874
  * still fails." The full rationale lives at the call site in
1511
1875
  * `releaseLock`; this method is the de-duplicated body.
1876
+ *
1877
+ * EVERY workflow push goes through here — saves, sharing a branch, opening
1878
+ * a request, update-from-target, the decline revert, the roles.yaml
1879
+ * restore — so a push the host refuses answers one way everywhere: the
1880
+ * commit stays local, the sync banner goes up, and the caller gets the
1881
+ * 409 saved-locally sentence instead of a raw git error (which a route
1882
+ * would turn into a 500). A later successful push of the branch carries
1883
+ * the commits and clears the banner.
1512
1884
  */
1513
1885
  private async pushWithRecovery(
1514
1886
  workspaceId: string,
@@ -1517,8 +1889,12 @@ export class WorkflowService implements IWorkflowService {
1517
1889
  user: AuthUser,
1518
1890
  opts?: { systemAuthorized?: boolean },
1519
1891
  ): Promise<void> {
1892
+ // No explicit `undefined` third argument when there are no options: the
1893
+ // call shape stays the bare `push(workspaceId, user)` every caller made.
1894
+ const push = () =>
1895
+ opts ? this.git.push(workspaceId, user, opts) : this.git.push(workspaceId, user);
1520
1896
  try {
1521
- await this.git.push(workspaceId, user, opts);
1897
+ await push();
1522
1898
  this.noteGitSyncOk(workspaceId, branch);
1523
1899
  } catch (firstPushErr) {
1524
1900
  const firstDetail = firstPushErr instanceof Error ? firstPushErr.message : String(firstPushErr);
@@ -1526,10 +1902,24 @@ export class WorkflowService implements IWorkflowService {
1526
1902
  let recovered = false;
1527
1903
  let recoveryDetail = '(cooperative path not attempted)';
1528
1904
  let recoveryError: unknown = null;
1905
+ // The retry push's own rejection, when the pull got that far: the
1906
+ // divergence is cured by then, so it — not the first rejection — says
1907
+ // whether the host is refusing.
1908
+ let retryDetail: string | null = null;
1529
1909
  if (looksLikeNonFastForward) {
1530
1910
  try {
1531
- await this.pullWorkspace(workspaceId);
1532
- await this.git.push(workspaceId, user, opts);
1911
+ // `preserveMerges` on every push, not only the ones that make a
1912
+ // merge: a merge stranded by a refused open or update rides along
1913
+ // with whatever push of the branch comes next — a save, a share —
1914
+ // and a plain rebase would flatten it into cherry-picks. With no
1915
+ // merge among the local commits the two spellings replay the same.
1916
+ await this.pullWorkspace(workspaceId, { preserveMerges: true });
1917
+ try {
1918
+ await push();
1919
+ } catch (retryErr) {
1920
+ retryDetail = retryErr instanceof Error ? retryErr.message : String(retryErr);
1921
+ throw retryErr;
1922
+ }
1533
1923
  recovered = true;
1534
1924
  this.noteGitSyncOk(workspaceId, branch);
1535
1925
  log.info(
@@ -1552,12 +1942,31 @@ export class WorkflowService implements IWorkflowService {
1552
1942
  // When recovery RAN, its error is the current state of the world (the
1553
1943
  // first rejection may be a stale non-fast-forward the pull already
1554
1944
  // cured); when it was skipped, the first error is all there is.
1555
- this.noteGitSyncFailed(workspaceId, branch, recoveryError ?? firstPushErr);
1945
+ // A recovery that failed before its retry push failed in the PULL.
1946
+ const failedInPull = recoveryError !== null && retryDetail === null;
1947
+ this.noteGitSyncFailed(
1948
+ workspaceId,
1949
+ branch,
1950
+ recoveryError ?? firstPushErr,
1951
+ undefined,
1952
+ failedInPull ? 'pull' : 'push',
1953
+ );
1556
1954
  log.warn(
1557
1955
  `push failed for workspace=${workspaceId} user=${user.id}; throwing PushNeedsAgentResolutionError so the frontend can hand off to the agent:`,
1558
1956
  { detail: firstDetail },
1559
1957
  );
1560
- throw new PushNeedsAgentResolutionError(branch, targetPath, firstDetail, recoveryDetail);
1958
+ throw new PushNeedsAgentResolutionError(
1959
+ branch,
1960
+ targetPath,
1961
+ firstDetail,
1962
+ recoveryDetail,
1963
+ // `rejected` above also matches the host's own `[remote rejected]`
1964
+ // (an outage, a hook): worth the cooperative try, but only a real
1965
+ // divergence is described as one.
1966
+ /non-fast-forward|fetch first|updates were rejected|! \[rejected\]/i.test(retryDetail ?? firstDetail)
1967
+ ? 'diverged'
1968
+ : 'refused',
1969
+ );
1561
1970
  }
1562
1971
  }
1563
1972
  }
@@ -1877,10 +2286,24 @@ export class WorkflowService implements IWorkflowService {
1877
2286
  );
1878
2287
  }
1879
2288
 
1880
- // Push the source — `gh pr create` against an unpushed branch returns
1881
- // "head branch does not exist on remote". Push *after* the auto-merge
1882
- // so the remote sees the merge commit too.
1883
- await this.trackedPush(workspaceId, user);
2289
+ // Push the source *after* the auto-merge so the remote sees the merge
2290
+ // commit too. A push the host refuses does not undo the open: the merge
2291
+ // is committed locally, the request is a DB row, and the next push of
2292
+ // the branch carries the commits — so the row is still created below and
2293
+ // the refusal (409, the saved-locally sentence, the sync banner) is
2294
+ // answered once it exists.
2295
+ let pushRefused: PushNeedsAgentResolutionError | null = null;
2296
+ try {
2297
+ await this.pushWithRecovery(
2298
+ workspaceId,
2299
+ branchForWorkspaceId(workspaceId),
2300
+ '(opening a change request)',
2301
+ user,
2302
+ );
2303
+ } catch (err) {
2304
+ if (!(err instanceof PushNeedsAgentResolutionError)) throw err;
2305
+ pushRefused = err;
2306
+ }
1884
2307
 
1885
2308
  const workspacePath = await this.workspaceService.getWorkspacePath(workspaceId);
1886
2309
  const cwd = path.join(workspacePath, this.kbDirName);
@@ -1969,6 +2392,21 @@ export class WorkflowService implements IWorkflowService {
1969
2392
  );
1970
2393
  }
1971
2394
  this.prs.invalidateDetailCache(prNumber);
2395
+ const opened = {
2396
+ kind: 'change-request-opened',
2397
+ number: prNumber,
2398
+ source: input.sourceBranch,
2399
+ target: input.targetBranch,
2400
+ authorIdHash: hashEmail(user.email),
2401
+ title: input.title,
2402
+ } as const;
2403
+ if (pushRefused) {
2404
+ // The request exists; its detail reads the published refs, which the
2405
+ // refused push never moved — answering the refusal is what the caller
2406
+ // needs, not a detail read that may fail on a branch the host lacks.
2407
+ this.events?.emit(opened);
2408
+ throw pushRefused;
2409
+ }
1972
2410
 
1973
2411
  const detail = await this.prs.getPrDetail(prNumber, {
1974
2412
  fresh: true,
@@ -1980,14 +2418,7 @@ export class WorkflowService implements IWorkflowService {
1980
2418
  `Created change request #${prNumber} but could not fetch its detail`,
1981
2419
  );
1982
2420
  }
1983
- this.events?.emit({
1984
- kind: 'change-request-opened',
1985
- number: prNumber,
1986
- source: input.sourceBranch,
1987
- target: input.targetBranch,
1988
- authorIdHash: hashEmail(user.email),
1989
- title: input.title,
1990
- });
2421
+ this.events?.emit(opened);
1991
2422
  return detail;
1992
2423
  });
1993
2424
  }
@@ -2119,7 +2550,7 @@ export class WorkflowService implements IWorkflowService {
2119
2550
  // do. Asking git what is unpushed retries it instead.
2120
2551
  //
2121
2552
  // A failed probe falls back to the old gate rather than to "push
2122
- // anyway": `trackedPush` on a clone with nothing to push is a wasted
2553
+ // anyway": a push on a clone with nothing to push is a wasted
2123
2554
  // round trip on every single update.
2124
2555
  const hasUnpushed = await this.git
2125
2556
  .hasUnpushedCommits(workspaceId)
@@ -2131,7 +2562,15 @@ export class WorkflowService implements IWorkflowService {
2131
2562
  return !outcome.alreadyUpToDate;
2132
2563
  });
2133
2564
  if (hasUnpushed) {
2134
- await this.trackedPush(workspaceId, user);
2565
+ // A refusal answers 409 with the saved-locally sentence and leaves the
2566
+ // merge applied in the clone; the probe above makes the next update
2567
+ // (or any save on the branch) push it.
2568
+ await this.pushWithRecovery(
2569
+ workspaceId,
2570
+ branchForWorkspaceId(workspaceId),
2571
+ `(update from ${detail.base})`,
2572
+ user,
2573
+ );
2135
2574
  }
2136
2575
  // Where the branch ended up, as PUBLISHED — two rev-parses, not a second
2137
2576
  // detail read. Everything below needs only the sha, and the detail that
@@ -2382,8 +2821,10 @@ export class WorkflowService implements IWorkflowService {
2382
2821
  // Best-effort freshen of the source checkout: the diff below reads origin
2383
2822
  // refs, but the restore commits from the working tree — a stale tree
2384
2823
  // would push non-fast-forward and fail loudly anyway; this just makes
2385
- // that rare.
2386
- await this.pullWorkspace(ws.id).catch(() => undefined);
2824
+ // that rare. `preserveMerges`: the branch may carry a merge a refused open
2825
+ // or update stranded locally, and a plain rebase would flatten it before
2826
+ // the revert's push publishes the branch.
2827
+ await this.pullWorkspace(ws.id, { preserveMerges: true }).catch(() => undefined);
2387
2828
 
2388
2829
  // The verb acts on the request as it is NOW — never a cached file list.
2389
2830
  const paths = await this.git.changedPathsForPr(ws.id, baseBranch, headBranch);
@@ -2416,6 +2857,10 @@ export class WorkflowService implements IWorkflowService {
2416
2857
  // save must not race the restore between write and commit.
2417
2858
  const held: string[] = [];
2418
2859
  let revertError: { reason: unknown } | null = null;
2860
+ // A push the host refuses leaves the revert committed on the branch
2861
+ // locally; it is answered (409, the saved-locally sentence) only after
2862
+ // the locks are released and the request's caches reflect the new head.
2863
+ let pushRefused: PushNeedsAgentResolutionError | null = null;
2419
2864
  try {
2420
2865
  for (const p of reverted) {
2421
2866
  const lockPath = `${this.kbDirName}/${p}`;
@@ -2440,7 +2885,12 @@ export class WorkflowService implements IWorkflowService {
2440
2885
  true, // skipValidator — this restores an already-validated base version
2441
2886
  );
2442
2887
  }
2443
- await this.trackedPush(ws.id, user);
2888
+ try {
2889
+ await this.pushWithRecovery(ws.id, headBranch, repoRelPath, user);
2890
+ } catch (err) {
2891
+ if (!(err instanceof PushNeedsAgentResolutionError)) throw err;
2892
+ pushRefused = err;
2893
+ }
2444
2894
  } catch (err) {
2445
2895
  revertError = { reason: err };
2446
2896
  }
@@ -2455,9 +2905,14 @@ export class WorkflowService implements IWorkflowService {
2455
2905
  if (revertError) throw revertError.reason;
2456
2906
  const failedRelease = released.find((r): r is PromiseRejectedResult => r.status === 'rejected');
2457
2907
  if (failedRelease) throw failedRelease.reason;
2908
+ this.prs.invalidateDetailCache(number);
2909
+ // A refused push moved nothing the request is judged on. A recorded
2910
+ // apply failure describes the published head, which is still where it
2911
+ // was, so it stays; and the file list reads the published refs, so
2912
+ // closing an "empty" request is decided once the push lands.
2913
+ if (pushRefused) throw pushRefused;
2458
2914
  // The source head moved: the refusal described a revision that is gone.
2459
2915
  await this.clearApplyFailure(number, { recordedBefore: headMovedAfter });
2460
- this.prs.invalidateDetailCache(number);
2461
2916
 
2462
2917
  const remaining = await this.git.changedPathsForPr(ws.id, baseBranch, headBranch);
2463
2918
  if (remaining.length > 0) {
@@ -2598,7 +3053,9 @@ export class WorkflowService implements IWorkflowService {
2598
3053
  if (!summary || summary.state !== 'open') continue;
2599
3054
  const ws = await this.workspaceService.getOrCreateForBranch(summary.branch);
2600
3055
  try {
2601
- await this.pullWorkspace(ws.id);
3056
+ // `preserveMerges`: a merge a refused open or update stranded on the
3057
+ // request's branch must survive until the branch's next push.
3058
+ await this.pullWorkspace(ws.id, { preserveMerges: true });
2602
3059
  } catch (err) {
2603
3060
  log.warn(
2604
3061
  `pull failed for #${summary.number} before removing folder ${printable(folder)}: ${printable(sanitizeError(err))}`,
@@ -2902,33 +3359,9 @@ export class WorkflowService implements IWorkflowService {
2902
3359
  * Returns true when THIS call closed it.
2903
3360
  */
2904
3361
  async closeEmptyChangeRequest(number: number, user: AuthUser): Promise<boolean> {
2905
- const summary = await this.prs.getPr(number);
2906
- if (!summary || summary.state !== 'open') return false;
2907
- let paths: string[];
2908
- let wsId: string;
2909
- try {
2910
- const ws = await this.workspaceService.getOrCreateForBranch(summary.branch);
2911
- wsId = ws.id;
2912
- paths = await this.git.changedPathsForPr(ws.id, summary.base, summary.branch);
2913
- } catch (err) {
2914
- crLog.warn(`empty-check for change request #${number} failed — leaving it open:`, { err });
2915
- return false;
2916
- }
2917
- if (paths.length > 0) return false;
2918
- if (await this.savesInFlight(wsId)) return false;
2919
-
2920
- // Guard on `state = 'open'` so a concurrent merge or withdraw wins the
2921
- // race and this becomes a no-op.
2922
- const now = new Date();
2923
- const updated = await this.db
2924
- .update(changeRequests)
2925
- .set({ state: 'closed', closedAt: now, updatedAt: now })
2926
- .where(and(eq(changeRequests.number, number), eq(changeRequests.state, 'open')))
2927
- .returning({ id: changeRequests.id });
2928
- if (updated.length === 0) return false;
2929
- this.prs.invalidateDetailCache(number);
2930
- this.events?.emit({ kind: 'change-request-rejected', number });
2931
- await this.retireMergedSourceBranch(number, summary.base, user);
3362
+ const closed = await this.closeIfEmpty(number, { reason: 'found empty', actor: user.email });
3363
+ if (!closed) return false;
3364
+ await this.retireMergedSourceBranch(number, closed.base, user);
2932
3365
  return true;
2933
3366
  }
2934
3367
 
@@ -2938,6 +3371,14 @@ export class WorkflowService implements IWorkflowService {
2938
3371
  * (their file is still only on disk). An answer that cannot be read is a
2939
3372
  * yes — the caller is about to delete the checkout.
2940
3373
  */
3374
+ private savesLandingRefusal(name: string): BranchDeleteBlockedError {
3375
+ return new BranchDeleteBlockedError(
3376
+ 'saves-landing',
3377
+ name,
3378
+ `"${name}" still has saves waiting to be committed or a file held for editing. Try again once they have landed.`,
3379
+ );
3380
+ }
3381
+
2941
3382
  private async savesInFlight(wsId: string): Promise<boolean> {
2942
3383
  try {
2943
3384
  return (await this.fileLocks.hasAnyActive(wsId)) || (await this.pendingCommits.hasAnyForWorkspace(wsId));
@@ -3173,11 +3614,233 @@ export class WorkflowService implements IWorkflowService {
3173
3614
  }
3174
3615
  })
3175
3616
  .catch((err) => crLog.warn('on-demand deleted-branch sweep failed:', { err }))
3617
+ // Every sweep is followed by the tidy-up, which never throws.
3618
+ .then(() => this.tidyAfterSweep())
3619
+ .then(() => undefined)
3176
3620
  .finally(() => {
3177
3621
  this.sweepKick = null;
3178
3622
  });
3179
3623
  }
3180
3624
 
3625
+ private tidyRound: Promise<{ closedEmpty: number; removedLeftovers: number }> | null = null;
3626
+ private tidyStopped = false;
3627
+
3628
+ /**
3629
+ * Stop the tidy-up when the graph stops: no round starts after this, and a
3630
+ * round under way stops at its next request or branch. Then
3631
+ * {@link drainTidy} waits for it, so it cannot fetch or delete once the
3632
+ * pool is ended or a replacement graph owns the same checkout.
3633
+ */
3634
+ stopTidying(): void {
3635
+ this.tidyStopped = true;
3636
+ }
3637
+
3638
+ /** Settles once no tidy-up (nor the sweep that leads into one) is running. */
3639
+ async drainTidy(): Promise<void> {
3640
+ await Promise.allSettled([this.sweepKick, this.tidyRound]);
3641
+ }
3642
+
3643
+ /**
3644
+ * What follows every sweep for deleted branches — at startup, on a remote
3645
+ * sync, after a merge and on demand: first the open requests that propose
3646
+ * nothing are closed and their source branch removed
3647
+ * ({@link closeEmptyOpenChangeRequests}), then the branches merged requests
3648
+ * left behind ({@link retireLeftoverMergedBranches}, behind its own
3649
+ * setting). In that order, because closing an empty request is what can
3650
+ * free a branch for the second. Never throws; coalesced.
3651
+ */
3652
+ tidyAfterSweep(): Promise<{ closedEmpty: number; removedLeftovers: number }> {
3653
+ if (this.tidyRound) return this.tidyRound;
3654
+ if (this.tidyStopped) return Promise.resolve({ closedEmpty: 0, removedLeftovers: 0 });
3655
+ this.tidyRound = (async () => {
3656
+ const closedEmpty = await this.closeEmptyOpenChangeRequests().catch((err: unknown) => {
3657
+ crLog.warn('background close of empty change requests failed:', { err });
3658
+ return 0;
3659
+ });
3660
+ const removedLeftovers = await this.retireLeftoverMergedBranches();
3661
+ return { closedEmpty, removedLeftovers };
3662
+ })().finally(() => {
3663
+ this.tidyRound = null;
3664
+ });
3665
+ return this.tidyRound;
3666
+ }
3667
+
3668
+ /**
3669
+ * Close every open change request that proposes nothing, and remove its
3670
+ * source branch — what opening such a request's page in the app does
3671
+ * (`closeEmptyChangeRequest`), done without anyone opening it. Each is
3672
+ * judged from the default branch's workspace against origin's refs, after
3673
+ * ONE strict fetch, so no request's branch is cloned for the question; a
3674
+ * round whose fetch fails closes nothing. A request whose changes cannot be
3675
+ * determined, or with a save still landing on its branch, stays open.
3676
+ * Returns how many it closed.
3677
+ *
3678
+ * The source branch is removed under the same guards as any other
3679
+ * deletion: under its lifecycle lock, only with no request open from or
3680
+ * into it, with no save landing and no lock grantable on it at that moment,
3681
+ * and leased on the tip the request was judged empty at — a commit pushed
3682
+ * since is refused by the host instead of deleted unseen.
3683
+ */
3684
+ async closeEmptyOpenChangeRequests(): Promise<number> {
3685
+ const open = await this.db
3686
+ .select({ number: changeRequests.number, sourceBranch: changeRequests.sourceBranch })
3687
+ .from(changeRequests)
3688
+ .where(eq(changeRequests.state, 'open'));
3689
+ if (open.length === 0) return 0;
3690
+ let wsId: string;
3691
+ try {
3692
+ wsId = await this.freshDefaultWorkspace();
3693
+ } catch (err) {
3694
+ crLog.warn('background close of empty change requests skipped — could not fetch the shared repository:', { err });
3695
+ return 0;
3696
+ }
3697
+ let closed = 0;
3698
+ for (const { number, sourceBranch } of open) {
3699
+ if (this.tidyStopped) break;
3700
+ try {
3701
+ // Read before the request is judged, so the lease below covers
3702
+ // anything that reached the branch after the judgement.
3703
+ const tip = this.kb.isProtectedBranch(sourceBranch)
3704
+ ? null
3705
+ : (await this.git.branchState(wsId, sourceBranch, this.kb.defaultBranch)).lastCommit;
3706
+ const done = await this.closeIfEmpty(number, {
3707
+ workspaceId: wsId,
3708
+ fresh: true,
3709
+ actor: 'system',
3710
+ reason: 'empty in the background sweep',
3711
+ });
3712
+ if (!done) continue;
3713
+ closed++;
3714
+ if (tip) await this.retireEmptySourceBranch(wsId, sourceBranch, tip);
3715
+ } catch (err) {
3716
+ crLog.warn(`background close of change request #${number} failed — leaving it open:`, { err });
3717
+ }
3718
+ }
3719
+ return closed;
3720
+ }
3721
+
3722
+ /**
3723
+ * Remove the source branch of a request the background sweep just closed
3724
+ * as empty, from the default branch's freshly fetched workspace `wsId`.
3725
+ * Skips quietly when another request is open from or into it or a save is
3726
+ * landing on it; the delete is leased on `tip`. Never throws.
3727
+ */
3728
+ private async retireEmptySourceBranch(wsId: string, branch: string, tip: string): Promise<void> {
3729
+ try {
3730
+ await this.branchLifecycle.run(`branch:${branch}`, async () => {
3731
+ if ((await this.openChangeRequestOn(branch)) !== null) return;
3732
+ await this.fileLocks.whileNoneAcquired(branch, async () => {
3733
+ if (await this.savesInFlight(workspaceIdForBranch(branch))) {
3734
+ crLog.info(`kept "${branch}" after closing its empty change request: a save is still landing on it`);
3735
+ return;
3736
+ }
3737
+ await this.deleteBranchUnlocked(wsId, branch, SYSTEM_ACTOR, { systemCleanup: true, expectTip: tip });
3738
+ });
3739
+ });
3740
+ } catch (err) {
3741
+ crLog.warn(`could not remove "${branch}" after closing its empty change request (non-fatal):`, { err });
3742
+ }
3743
+ }
3744
+
3745
+ /**
3746
+ * Whether the leftover cleanup below runs — the `retireMergedBranches`
3747
+ * deployment setting, read at every round so the Deployment page applies
3748
+ * without a restart. Set by the composition root; on by default.
3749
+ */
3750
+ leftoverCleanupEnabled: () => boolean = () => true;
3751
+
3752
+ private leftoverRound: Promise<number> | null = null;
3753
+
3754
+ /**
3755
+ * Remove the branches merged change requests left behind: sources of a
3756
+ * merge from before the post-merge retirement existed (core-backend 0.5.0),
3757
+ * and ones whose retirement failed. What `retireMergedSourceBranch` does
3758
+ * after a merge, applied to every merge on record.
3759
+ *
3760
+ * A branch goes only when ALL hold: it is not protected; it was the source
3761
+ * of a merged request; it has no commit that is not on the default branch;
3762
+ * no request is open from or into it; its tip is contained in the merge
3763
+ * commit recorded for one of those requests — a branch recreated under the
3764
+ * same name after the merge is somebody's new draft, and a request with no
3765
+ * recorded merge commit proves nothing; and its checkout has no saves
3766
+ * landing and no file held. Each is decided and deleted under the branch's
3767
+ * lifecycle lock, like the post-merge retirement.
3768
+ *
3769
+ * Fails SAFE, like the deleted-branch sweep it runs beside: a round whose
3770
+ * fetch fails removes nothing, and a branch whose state cannot be read is
3771
+ * left. The switch covers this round only; the post-merge retirement is not
3772
+ * asked. Never throws. Coalesced, because boot, the remote sync and the
3773
+ * on-demand sweep can all start one. Returns how many it removed.
3774
+ */
3775
+ retireLeftoverMergedBranches(): Promise<number> {
3776
+ if (this.leftoverRound) return this.leftoverRound;
3777
+ this.leftoverRound = this.retireLeftoverMergedBranchesOnce()
3778
+ .catch((err) => {
3779
+ log.warn('leftover branch cleanup failed:', { err });
3780
+ return 0;
3781
+ })
3782
+ .finally(() => {
3783
+ this.leftoverRound = null;
3784
+ });
3785
+ return this.leftoverRound;
3786
+ }
3787
+
3788
+ private async retireLeftoverMergedBranchesOnce(): Promise<number> {
3789
+ if (!this.leftoverCleanupEnabled()) return 0;
3790
+ const merged = await this.db
3791
+ .select({ sourceBranch: changeRequests.sourceBranch, mergedSha: changeRequests.mergedSha })
3792
+ .from(changeRequests)
3793
+ .where(eq(changeRequests.state, 'merged'));
3794
+ const mergeCommits = new Map<string, string[]>();
3795
+ for (const row of merged) {
3796
+ if (this.kb.isProtectedBranch(row.sourceBranch)) continue;
3797
+ const shas = mergeCommits.get(row.sourceBranch) ?? [];
3798
+ if (row.mergedSha) shas.push(row.mergedSha);
3799
+ mergeCommits.set(row.sourceBranch, shas);
3800
+ }
3801
+ if (mergeCommits.size === 0) return 0;
3802
+
3803
+ let wsId: string;
3804
+ try {
3805
+ wsId = await this.freshDefaultWorkspace();
3806
+ } catch (err) {
3807
+ log.warn('leftover branch cleanup skipped — could not fetch the shared repository:', { err });
3808
+ return 0;
3809
+ }
3810
+
3811
+ let removed = 0;
3812
+ for (const [branch, shas] of mergeCommits) {
3813
+ if (this.tidyStopped) break;
3814
+ if (shas.length === 0) continue;
3815
+ try {
3816
+ const done = await this.branchLifecycle.run(`branch:${branch}`, async () => {
3817
+ const state = await this.git.branchState(wsId, branch, this.kb.defaultBranch);
3818
+ if (!state.exists || state.lastCommit === null || state.unmergedCommits > 0) return false;
3819
+ if ((await this.openChangeRequestOn(branch)) !== null) return false;
3820
+ let contained = false;
3821
+ for (const sha of shas) {
3822
+ if (await this.git.isAncestor(wsId, state.lastCommit, sha).catch(() => false)) {
3823
+ contained = true;
3824
+ break;
3825
+ }
3826
+ }
3827
+ if (!contained) return false;
3828
+ const tip = state.lastCommit;
3829
+ return this.fileLocks.whileNoneAcquired(branch, async () => {
3830
+ if (await this.savesInFlight(workspaceIdForBranch(branch))) return false;
3831
+ await this.deleteBranchUnlocked(wsId, branch, SYSTEM_ACTOR, { systemCleanup: true, expectTip: tip });
3832
+ return true;
3833
+ });
3834
+ });
3835
+ if (done) removed++;
3836
+ } catch (err) {
3837
+ log.warn(`leftover branch cleanup could not remove "${branch}":`, { err });
3838
+ }
3839
+ }
3840
+ if (removed > 0) log.info(`removed ${removed} branch${removed === 1 ? '' : 'es'} left over from merged change requests`);
3841
+ return removed;
3842
+ }
3843
+
3181
3844
 
3182
3845
  /**
3183
3846
  * Reject (close-without-merging) a change request. Per PLAN.md spec, the
@@ -3353,6 +4016,9 @@ export class WorkflowService implements IWorkflowService {
3353
4016
  // AFTER the event: the applying UI is waiting on `change-request-merged`,
3354
4017
  // and branch retirement is git IO it must never wait behind.
3355
4018
  await this.retireMergedSourceBranch(number, baseBranch, user);
4019
+ // A merge can empty OTHER open requests into the same target; the sweep's
4020
+ // tidy-up closes those. Detached and coalesced, like every kick.
4021
+ this.kickDeletedBranchSweep();
3356
4022
  return { kind: 'merged', result };
3357
4023
  }
3358
4024
 
@@ -3421,11 +4087,92 @@ export class WorkflowService implements IWorkflowService {
3421
4087
  }
3422
4088
  }
3423
4089
 
4090
+ /**
4091
+ * How long `mergeBranch` waits for the source's queued commits, and how
4092
+ * often it asks. The worker polls every half second and a commit takes a few
4093
+ * seconds; twenty seconds of waiting is an outage, not latency.
4094
+ *
4095
+ * Twenty, not thirty, because of who is waiting on THIS call: an agent over
4096
+ * `/api/mcp` reaches the tool through `@utcp/http`, whose request timeout is
4097
+ * a fixed 30 seconds (its call-template schema drops any `timeout` field).
4098
+ * The wait plus the merge after it (fetch, merge, push) must fit inside
4099
+ * that, or the agent hears "timeout of 30000ms exceeded" instead of the
4100
+ * `pending-commits` answer this wait exists to give. Mutable for tests only.
4101
+ */
4102
+ mergeWaitForPendingCommits = { timeoutMs: 20_000, pollMs: 250 };
4103
+
4104
+ /**
4105
+ * Wait until no commit is queued on `branch`, or the bound runs out. A
4106
+ * commit escalated to a person ends the wait at once: nothing will land it.
4107
+ *
4108
+ * Polls the queue rather than draining it: the worker's own per-workspace
4109
+ * serialization stays the only writer to the clone, and the row is deleted
4110
+ * only after its push, so "no row" means the remote holds the commit.
4111
+ */
4112
+ private async awaitPendingCommits(
4113
+ branch: string,
4114
+ ): Promise<{ ok: true } | { ok: false; pending: number; needsAttention?: string }> {
4115
+ const { timeoutMs, pollMs } = this.mergeWaitForPendingCommits;
4116
+ const deadline = Date.now() + timeoutMs;
4117
+ for (;;) {
4118
+ const { queued, stuck, needsAttention } = await this.pendingCommits.queuedOnBranch(branch);
4119
+ if (needsAttention !== null) return { ok: false, pending: queued + stuck, needsAttention };
4120
+ if (queued === 0) return { ok: true };
4121
+ if (Date.now() >= deadline) return { ok: false, pending: queued };
4122
+ await new Promise((resolve) => setTimeout(resolve, Math.min(pollMs, Math.max(0, deadline - Date.now()))));
4123
+ }
4124
+ }
4125
+
4126
+ /** The one question `mergeBranch` refuses on: is a request from `source` into `target` open? */
4127
+ private async openRequestBlockingMerge(sourceBranch: string, targetBranch: string): Promise<number | null> {
4128
+ const [open] = await this.db
4129
+ .select({ number: changeRequests.number })
4130
+ .from(changeRequests)
4131
+ .where(
4132
+ and(
4133
+ eq(changeRequests.sourceBranch, sourceBranch),
4134
+ eq(changeRequests.targetBranch, targetBranch),
4135
+ eq(changeRequests.state, 'open'),
4136
+ ),
4137
+ )
4138
+ .limit(1);
4139
+ return open ? open.number : null;
4140
+ }
4141
+
3424
4142
  async mergeBranch(user: AuthUser, sourceBranch: string, targetBranch: string): Promise<MergeBranchOutcome> {
3425
4143
  if (sourceBranch === targetBranch) {
3426
4144
  throw new WorkflowValidationError(`\`source\` and \`target\` are both "${sourceBranch}" — name two different branches.`);
3427
4145
  }
3428
4146
 
4147
+ // Asked once BEFORE waiting, so a merge the open request forbids is refused
4148
+ // at once rather than after the source's commits have landed. Not the
4149
+ // answer that counts — that one is asked again under the locks below.
4150
+ const openBefore = await this.openRequestBlockingMerge(sourceBranch, targetBranch);
4151
+ if (openBefore !== null) throw new OpenChangeRequestBlocksMergeError(sourceBranch, targetBranch, openBefore);
4152
+
4153
+ // Writes are committed asynchronously: a write tool answers once the bytes
4154
+ // are on disk and the pending-commits worker commits and pushes them a few
4155
+ // seconds later. The merge below merges what the REMOTE holds of the
4156
+ // source, so issued in those seconds it would find nothing new and land
4157
+ // nothing. Wait for them first — OUTSIDE the lifecycle locks, which guard
4158
+ // creating, deleting and opening requests on these branches, and must not
4159
+ // be held for seconds of waiting on a queue.
4160
+ const settled = await this.awaitPendingCommits(sourceBranch);
4161
+ if (!settled.ok) {
4162
+ const message = settled.needsAttention
4163
+ ? `A commit queued on "${sourceBranch}" failed and needs a person: ${settled.needsAttention} ` +
4164
+ `Nothing was merged. Tell the user; merge again once it has been resolved.`
4165
+ : `${settled.pending} write(s) on "${sourceBranch}" are still being committed. ` +
4166
+ `Nothing was merged. Retry the merge shortly.`;
4167
+ return {
4168
+ kind: 'pending-commits',
4169
+ branch: sourceBranch,
4170
+ pending: settled.pending,
4171
+ ...(settled.needsAttention ? { needsAttention: settled.needsAttention } : {}),
4172
+ message,
4173
+ };
4174
+ }
4175
+
3429
4176
  // Under the lifecycle lock of BOTH branches, the same protocol
3430
4177
  // `openChangeRequest` follows — and for the same window. That method holds
3431
4178
  // these keys across its whole check-then-insert (an auto-merge and a push,
@@ -3439,18 +4186,8 @@ export class WorkflowService implements IWorkflowService {
3439
4186
  // A person merges a change request. Only the request's OWN direction is
3440
4187
  // blocked: the target merged into the source is how a draft under review
3441
4188
  // stays current, and that must keep working while the request is open.
3442
- const [open] = await this.db
3443
- .select({ number: changeRequests.number })
3444
- .from(changeRequests)
3445
- .where(
3446
- and(
3447
- eq(changeRequests.sourceBranch, sourceBranch),
3448
- eq(changeRequests.targetBranch, targetBranch),
3449
- eq(changeRequests.state, 'open'),
3450
- ),
3451
- )
3452
- .limit(1);
3453
- if (open) throw new OpenChangeRequestBlocksMergeError(sourceBranch, targetBranch, open.number);
4189
+ const open = await this.openRequestBlockingMerge(sourceBranch, targetBranch);
4190
+ if (open !== null) throw new OpenChangeRequestBlocksMergeError(sourceBranch, targetBranch, open);
3454
4191
 
3455
4192
  // The merge runs in the target's own workspace, like a change request's.
3456
4193
  const targetWorkspaceId = (await this.workspaceService.getOrCreateForBranch(targetBranch)).id;
@@ -3530,6 +4267,12 @@ export class WorkflowService implements IWorkflowService {
3530
4267
  return { kind: 'conflicts-need-resolution', conflictedPaths: result.paths };
3531
4268
  }
3532
4269
  await this.pullMergeTarget(targetBranch, user);
4270
+ // No merge commit: the target already held everything on the source, and
4271
+ // `sha` is its unchanged tip. Reported as such — a `merged` that applied
4272
+ // nothing is what sent agents on as if their write had landed.
4273
+ if (result.mergeCommit === null) return { kind: 'nothing-to-merge', sha: result.sha };
4274
+ // What landed on the target may have emptied open requests into it.
4275
+ this.kickDeletedBranchSweep();
3533
4276
  return { kind: 'merged', sha: result.sha };
3534
4277
  });
3535
4278
  }
@@ -3812,8 +4555,9 @@ export class WorkflowService implements IWorkflowService {
3812
4555
  // sweep those unrelated edits into our "preserve roles.yaml" commit under the
3813
4556
  // wrong author/message. Feature branch → the protected-branch gate doesn't
3814
4557
  // fire, so this commits cleanly. Then publish so the merge sees the
3815
- // neutralised source. A non-fast-forward push (the source advanced under us)
3816
- // throws → RolesYamlPreservationError → the merge aborts, fail-closed.
4558
+ // neutralised source. A push that still fails after the cooperative
4559
+ // pull-rebase throws PushNeedsAgentResolutionError → the merge aborts,
4560
+ // fail-closed, with the restore kept locally for the next push.
3817
4561
  const committed = await this.git.commitFile(
3818
4562
  ws.id,
3819
4563
  user,
@@ -3829,12 +4573,29 @@ export class WorkflowService implements IWorkflowService {
3829
4573
  // with origin/<head>), then origin/<head> STILL carries the divergent
3830
4574
  // roles.yaml and the merge would land it. Treat that as a hard failure —
3831
4575
  // returning false here would fail OPEN. Fail closed instead.
3832
- if (!committed) {
4576
+ //
4577
+ // One shape of "nothing to commit" is not out of sync: a restore an
4578
+ // earlier merge attempt committed, whose push the host refused. The
4579
+ // clone's HEAD already carries the base version — that is why there
4580
+ // was nothing new to commit — and only the push is owed. Without this,
4581
+ // the retry the refusal promises could never succeed: every attempt
4582
+ // would find the file already restored and stop here, and the merge
4583
+ // would stay refused until some unrelated save pushed the branch.
4584
+ //
4585
+ // The question is NOT "does the clone hold unpushed commits" — any
4586
+ // queued save answers yes. It is whether HEAD already holds all of
4587
+ // origin/<head>, so that the push fast-forwards origin to a head whose
4588
+ // roles.yaml is the base version. A clone BEHIND origin would have
4589
+ // origin's divergent copy rebased into HEAD by the cooperative pull on
4590
+ // the way to the push, and the merge would land it: that clone is the
4591
+ // out-of-sync one this guard refuses. A probe that cannot answer
4592
+ // throws, and the guard fails closed with it.
4593
+ if (!committed && !(await this.git.headContainsOrigin(ws.id))) {
3833
4594
  throw new Error(
3834
4595
  'roles.yaml restore produced no commit while origin still diverges from base — source workspace out of sync; refusing to merge',
3835
4596
  );
3836
4597
  }
3837
- await this.trackedPush(ws.id, user);
4598
+ await this.pushWithRecovery(ws.id, headBranch, ROLES_YAML, user);
3838
4599
  this.accessControl.invalidate(ws.id);
3839
4600
  return true;
3840
4601
  } finally {
@@ -3843,6 +4604,12 @@ export class WorkflowService implements IWorkflowService {
3843
4604
  await this.fileLocks.release(ws.id, headBranch, rolesLockPath, user);
3844
4605
  }
3845
4606
  } catch (err) {
4607
+ // A refused push: the restore is committed on the source locally and the
4608
+ // merge does not run (origin still carries the divergent roles.yaml).
4609
+ // Answer it like every other refused push — 409, the saved-locally
4610
+ // sentence, the banner already raised — so the merge can be retried
4611
+ // once the host accepts the push.
4612
+ if (err instanceof PushNeedsAgentResolutionError) throw err;
3846
4613
  const detail = err instanceof Error ? err.message : String(err);
3847
4614
  // Log the raw git/push detail server-side; the thrown error keeps it OFF
3848
4615
  // the client-facing 502 message (see RolesYamlPreservationError).