@uniqbit/mate-core 0.20.0 → 0.21.1

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 (287) hide show
  1. package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +1 -1
  2. package/claude-capability-plugins/companion-mentions/hooks/register.ts +1 -1
  3. package/claude-plugin/hooks/hooks.json +10 -1
  4. package/claude-plugin/hooks/rtk-worktree-git.mjs +58 -0
  5. package/opencode-plugin/src/server.ts +9 -2
  6. package/package.json +2 -1
  7. package/src/cli/commands/artifact/delivery/environment.ts +28 -8
  8. package/src/cli/commands/artifact/delivery/link.ts +28 -9
  9. package/src/cli/commands/artifact/delivery/output.ts +7 -0
  10. package/src/cli/commands/companion/update.ts +2 -19
  11. package/src/cli/commands/factory/factory.ts +11 -1
  12. package/src/cli/commands/install.ts +47 -36
  13. package/src/cli/commands/launch/claude.ts +2 -0
  14. package/src/cli/commands/launch/shared.ts +33 -6
  15. package/src/cli/commands/plugin/install.ts +27 -11
  16. package/src/cli/commands/report/index.ts +180 -184
  17. package/src/cli/commands/report/markdown.ts +67 -72
  18. package/src/cli/commands/shared/companion-selection.ts +3 -1
  19. package/src/cli/commands/studio/access.ts +6 -14
  20. package/src/cli/commands/studio/areas.ts +112 -33
  21. package/src/cli/commands/studio/companion-add.ts +87 -0
  22. package/src/cli/commands/studio/companion-removal.ts +15 -8
  23. package/src/cli/commands/studio/factory-credential.ts +1 -15
  24. package/src/cli/commands/studio/factory-git-tokens.ts +40 -0
  25. package/src/cli/commands/studio/factory-relay.ts +18 -0
  26. package/src/cli/commands/studio/graph-model.ts +61 -0
  27. package/src/cli/commands/studio/graph.ts +336 -0
  28. package/src/cli/commands/studio/index.ts +4 -4
  29. package/src/cli/commands/studio/payload.ts +42 -15
  30. package/src/cli/commands/studio/repository-add.ts +116 -0
  31. package/src/cli/commands/studio/routes.ts +6 -0
  32. package/src/cli/commands/studio/selection.ts +12 -3
  33. package/src/cli/commands/studio/server.ts +127 -5
  34. package/src/cli/commands/studio/services.ts +40 -0
  35. package/src/cli/commands/studio/terminal.ts +45 -3
  36. package/src/cli/commands/studio/views/vault/markdown-tree.ts +84 -3
  37. package/src/cli/commands/studio/workset-session.ts +47 -14
  38. package/src/cli/commands/unwrap.ts +3 -0
  39. package/src/cli/commands/update.ts +2 -0
  40. package/src/cli/commands/vscode/release-vsix.json +4 -0
  41. package/src/cli/commands/vscode/setup.ts +71 -13
  42. package/src/cli/commands/vscode/vsix.ts +48 -7
  43. package/src/cli/commands/working/cleanup.ts +40 -8
  44. package/src/cli/commands/working/worktree.ts +176 -35
  45. package/src/cli/main.ts +17 -2
  46. package/src/cli/usage.ts +1 -1
  47. package/src/hooks/rtk-worktree-git.ts +48 -0
  48. package/src/hooks/validate-artifact-path.ts +38 -7
  49. package/src/lib/delivery/branch-template.ts +122 -0
  50. package/src/lib/delivery/branches.ts +21 -16
  51. package/src/lib/delivery/checkout.ts +102 -0
  52. package/src/lib/delivery/environment.ts +2 -0
  53. package/src/lib/delivery/merge-git.ts +13 -1
  54. package/src/lib/delivery/record-delivery.ts +83 -29
  55. package/src/lib/delivery/record.ts +15 -3
  56. package/src/lib/delivery/resolve-branch.ts +157 -110
  57. package/src/lib/factory/attach-client.ts +11 -1
  58. package/src/lib/factory/broker.ts +37 -40
  59. package/src/lib/factory/client.ts +22 -1
  60. package/src/lib/factory/clone-url.ts +39 -0
  61. package/src/lib/factory/command.ts +21 -5
  62. package/src/lib/factory/git-auth.ts +61 -0
  63. package/src/lib/factory/git-credential-store.ts +181 -0
  64. package/src/lib/factory/ids.ts +12 -2
  65. package/src/lib/factory/outcomes/actions.ts +20 -4
  66. package/src/lib/factory/outcomes/index.ts +77 -11
  67. package/src/lib/factory/outcomes/lifecycle.ts +9 -2
  68. package/src/lib/factory/outcomes/sessions.ts +23 -1
  69. package/src/lib/factory/prepare.ts +9 -3
  70. package/src/lib/factory/runner/scheduler.ts +96 -14
  71. package/src/lib/factory/runner/workflow.ts +5 -1
  72. package/src/lib/factory/runtime.ts +143 -43
  73. package/src/lib/orchestrator/companion-hub.ts +6 -1
  74. package/src/lib/orchestrator/engine-floor.ts +48 -0
  75. package/src/lib/orchestrator/launcher.ts +34 -1
  76. package/src/lib/orchestrator/projection-claude-commands.ts +2 -2
  77. package/src/lib/orchestrator/projection-claude-entry.ts +42 -21
  78. package/src/lib/orchestrator/projection-claude-links.ts +32 -8
  79. package/src/lib/orchestrator/projection-claude-skills.ts +2 -2
  80. package/src/lib/orchestrator/projection-entries.ts +22 -18
  81. package/src/lib/orchestrator/projection-opencode-copies.ts +65 -21
  82. package/src/lib/orchestrator/projection-runtime-documents.ts +66 -43
  83. package/src/lib/orchestrator/projection-types.ts +28 -1
  84. package/src/lib/orchestrator/refresh-working-claude-links.ts +3 -1
  85. package/src/lib/orchestrator/session-prepare.ts +6 -1
  86. package/src/lib/orchestrator/setup-compatibilities.ts +1 -1
  87. package/src/lib/orchestrator/types.ts +4 -0
  88. package/src/lib/orchestrator/umbrella-checkouts.ts +102 -0
  89. package/src/lib/orchestrator/working-repo-projection.ts +24 -4
  90. package/src/lib/orchestrator/wrap-pass.ts +1 -0
  91. package/src/lib/public-npm.ts +95 -50
  92. package/src/lib/session-state.ts +72 -2
  93. package/src/lib/update-checker.ts +7 -1
  94. package/src/lib/usage/aggregate.ts +202 -0
  95. package/src/lib/usage/cache.ts +87 -0
  96. package/src/lib/usage/claude-pricing.ts +71 -0
  97. package/src/lib/usage/claude.ts +189 -0
  98. package/src/lib/usage/collect.ts +56 -0
  99. package/src/lib/usage/opencode.ts +188 -0
  100. package/src/lib/usage/records.ts +80 -0
  101. package/src/lib/usage/rtk-database.ts +72 -0
  102. package/src/lib/usage/savings.ts +209 -0
  103. package/src/lib/usage/scope.ts +182 -0
  104. package/src/lib/usage/source.ts +102 -0
  105. package/src/lib/usage/types.ts +143 -0
  106. package/src/lib/usage/window.ts +37 -0
  107. package/src/lib/workset/factory-local.ts +157 -0
  108. package/src/lib/workset/record.ts +25 -11
  109. package/src/lib/workset/repositories.ts +118 -25
  110. package/src/lib/workset/worktree-include.ts +161 -0
  111. package/src/lib/workset/worktree-index.ts +6 -2
  112. package/src/lib/workset/worktree.ts +591 -101
  113. package/src/opencode/companion-hooks.ts +46 -8
  114. package/src/opencode/companion-policy.ts +18 -5
  115. package/src/opencode/enter-worktree.ts +254 -6
  116. package/src/opencode/session-register.ts +2 -2
  117. package/src/runtime/claude-bg-isolation.ts +138 -0
  118. package/src/runtime/companion-git.ts +10 -2
  119. package/src/runtime/companion-guidance.ts +17 -4
  120. package/src/runtime/current-branch.ts +16 -2
  121. package/src/runtime/entered-worktree.ts +24 -0
  122. package/src/runtime/git-tracked.ts +60 -0
  123. package/src/runtime/repo-destination.ts +72 -0
  124. package/src/runtime/repo-local.ts +25 -3
  125. package/src/runtime/rtk-git-guard.ts +66 -0
  126. package/src/runtime/runtime-document-manifest.ts +229 -19
  127. package/src/runtime/runtime-document-manifest.typecheck.ts +10 -0
  128. package/src/runtime/secret-guard.ts +9 -2
  129. package/src/runtime/secret-policy-weakening.ts +122 -0
  130. package/src/runtime/serving-claude-wrap.ts +15 -2
  131. package/src/runtime/umbrella-folder.ts +56 -0
  132. package/src/runtime/wrap-state.ts +5 -13
  133. package/src/studio.ts +37 -0
  134. package/src/templates/mate-skills/agents/mate-apply-change/SKILL.md +61 -6
  135. package/src/templates/mate-skills/agents/mate-explore-change/SKILL.md +8 -4
  136. package/src/templates/mate-skills/agents/mate-propose-change/SKILL.md +9 -5
  137. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +5 -4
  138. package/src/templates/mate-skills/agents/mate-show-me/SKILL.md +10 -4
  139. package/src/templates/mate-skills/agents/mate-simplify-code/SKILL.md +5 -1
  140. package/src/templates/mate-skills/claude/mate-apply-change/SKILL.md +61 -6
  141. package/src/templates/mate-skills/claude/mate-explore-change/SKILL.md +8 -4
  142. package/src/templates/mate-skills/claude/mate-propose-change/SKILL.md +9 -5
  143. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +5 -4
  144. package/src/templates/mate-skills/claude/mate-show-me/SKILL.md +10 -4
  145. package/src/templates/mate-skills/claude/mate-simplify-code/SKILL.md +5 -1
  146. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +307 -42
  147. package/src/tools/setup/capabilities/rtk.ts +93 -1
  148. package/src/tools/setup/dynamic-plugins/audiences.ts +65 -21
  149. package/src/tools/setup/dynamic-plugins/frozen.ts +32 -13
  150. package/src/tools/setup/dynamic-plugins/hydrate.ts +4 -4
  151. package/src/tools/setup/dynamic-plugins/install.ts +24 -22
  152. package/src/tools/setup/dynamic-plugins/loader.ts +11 -7
  153. package/src/tools/setup/dynamic-plugins/paths.ts +30 -10
  154. package/src/tools/setup/dynamic-plugins/verify.ts +10 -7
  155. package/src/tools/setup/dynamic-plugins/workspaces.ts +153 -0
  156. package/src/tools/setup/mate.ts +3 -3
  157. package/src/tools/setup/plugins/gitignore.ts +15 -9
  158. package/src/tools/setup/providers/claude-plugin-hooks.ts +12 -0
  159. package/src/tools/setup/providers/claude.ts +25 -3
  160. package/src/tools/setup/utils.ts +4 -2
  161. package/src/tools/setup/working-repo-cleanup.ts +2 -2
  162. package/src/tools/setup/working-repo-local-state.ts +2 -0
  163. package/src/tools/setup.ts +25 -14
  164. package/studio-dist/client/assets/app-D9cw6szy.css +2 -0
  165. package/studio-dist/client/assets/artifacts-WD2ZXYrx.js +1 -0
  166. package/studio-dist/client/assets/button-Br0O1sXw.js +1 -0
  167. package/studio-dist/client/assets/combobox-DA7RAUUZ.js +1 -0
  168. package/studio-dist/client/assets/companion-view-CrabvxS8.js +1 -0
  169. package/studio-dist/client/assets/factory-DGS0E16C.js +6 -0
  170. package/studio-dist/client/assets/fields-6aXBpFhJ.js +1 -0
  171. package/studio-dist/client/assets/getting-started-Clde4w6P.js +1 -0
  172. package/studio-dist/client/assets/getting-started-D6kgWwWZ.js +1 -0
  173. package/studio-dist/client/assets/getting-started._topic-BiunccbT.js +1 -0
  174. package/studio-dist/client/assets/getting-started.index-DpiNoGw8.js +1 -0
  175. package/studio-dist/client/assets/graph-B_TCBVbu.js +2 -0
  176. package/studio-dist/client/assets/graph-canvas-Ba37Y5AE.js +3242 -0
  177. package/studio-dist/client/assets/guides-Du_RtJxP.js +1 -0
  178. package/studio-dist/client/assets/index-Df8L1LQa.js +40 -0
  179. package/studio-dist/client/assets/jsx-runtime-MZURdZre.js +1 -0
  180. package/studio-dist/client/assets/markdown-view-BOX6x0rL.js +1 -0
  181. package/studio-dist/client/assets/panel-dbmCx7Mx.js +1 -0
  182. package/studio-dist/client/assets/queries-RvHeXY12.js +1 -0
  183. package/studio-dist/client/assets/react-3QStrcDO.js +27 -0
  184. package/studio-dist/client/assets/report-url-XRL0x1SY.js +1 -0
  185. package/studio-dist/client/assets/reports-r3IK7Doz.js +1 -0
  186. package/studio-dist/client/assets/routes-C0A5LTFc.js +1 -0
  187. package/studio-dist/client/assets/select-CnaMd617.js +1 -0
  188. package/studio-dist/client/assets/skills-CzjzHpBT.js +1 -0
  189. package/studio-dist/client/assets/specs-B0ldF_6J.js +1 -0
  190. package/studio-dist/client/assets/specs-view-BnCLA0gW.js +1 -0
  191. package/studio-dist/client/assets/spinner-Dcm3fqK1.js +1 -0
  192. package/studio-dist/client/assets/steps-C0p2N1Pb.js +1 -0
  193. package/studio-dist/client/assets/store-Dw34catY.js +1 -0
  194. package/studio-dist/client/assets/studio-Cpz_HRHp.js +100 -0
  195. package/studio-dist/client/assets/studio-queries-ibmpFo6R.js +2 -0
  196. package/studio-dist/client/assets/usage-C2QJ_0IZ.js +55 -0
  197. package/studio-dist/client/assets/useAnchoredPopupScrollLock-Bj-FWb8z.js +1 -0
  198. package/studio-dist/client/assets/useMutation-aAr2uiay.js +1 -0
  199. package/studio-dist/client/assets/useSelector-AYcH7lB0.js +2 -0
  200. package/studio-dist/client/assets/vault-BGcxkSIY.js +1 -0
  201. package/studio-dist/client/assets/warnings-R1cE1rLf.js +1 -0
  202. package/studio-dist/client/assets/workflow-C2qTrMDH.js +1 -0
  203. package/studio-dist/server/assets/__23tanstack-start-server-fn-resolver-Bn896ZYj.js +122 -0
  204. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +102 -35
  205. package/studio-dist/server/assets/{actions-Bvgj9eb8.js → actions-DYSv-9VV.js} +10 -4
  206. package/studio-dist/server/assets/artifacts-DnF9L3dZ.js +216 -0
  207. package/studio-dist/server/assets/{button-CIJqAhni.js → button-CgOIVdmD.js} +13 -1702
  208. package/studio-dist/server/assets/combobox-DV_s9W0s.js +483 -0
  209. package/studio-dist/server/assets/{companion-view-DISASvdJ.js → companion-view-BKVXD3TO.js} +3 -3
  210. package/studio-dist/server/assets/companions-C7fctnU9.js +31 -0
  211. package/studio-dist/server/assets/{createServerRpc-tK2lE9R2.js → createServerRpc-bFKFpGFG.js} +1 -1
  212. package/studio-dist/server/assets/{factory-DUTa0eDs.js → factory-C7Ybg0xG.js} +1256 -353
  213. package/studio-dist/server/assets/{factory-DGPmNGbo.js → factory-Df5uAHjb.js} +53 -6
  214. package/studio-dist/server/assets/fields-BbieQTD0.js +1190 -0
  215. package/studio-dist/server/assets/getting-started-B136TP57.js +4 -0
  216. package/studio-dist/server/assets/getting-started-CRxMWorQ.js +67 -0
  217. package/studio-dist/server/assets/getting-started._topic-DJKQAzYl.js +13 -0
  218. package/studio-dist/server/assets/getting-started.index-D84gec1t.js +13 -0
  219. package/studio-dist/server/assets/graph-CSje3029.js +801 -0
  220. package/studio-dist/server/assets/graph-DDZzXM1L.js +16 -0
  221. package/studio-dist/server/assets/graph-canvas-22bWB5-2.js +21066 -0
  222. package/studio-dist/server/assets/graph-wire-BdSUx0G5.js +58 -0
  223. package/studio-dist/server/assets/guides-D9dk1Frq.js +13 -0
  224. package/studio-dist/server/assets/guides-IE-19POz.js +5 -0
  225. package/studio-dist/server/assets/guides.server-vcYRY5wx.js +66 -0
  226. package/studio-dist/server/assets/jsx-runtime-Bt0s0YKS.js +451 -0
  227. package/studio-dist/server/assets/{markdown-view-Bn7xPdks.js → markdown-view-BR8dJ7aR.js} +28 -9
  228. package/studio-dist/server/assets/{panel-3Jmn4awF.js → panel-BR_t9iMM.js} +4 -4
  229. package/studio-dist/server/assets/queries-DWoTin-q.js +32 -0
  230. package/studio-dist/server/assets/react-CdqSUhaL.js +89 -0
  231. package/studio-dist/server/assets/redirect-BaZ_QyqF.js +39 -0
  232. package/studio-dist/server/assets/report-url-BUXPcE_8.js +9 -0
  233. package/studio-dist/server/assets/{reports-D6YMqhnO.js → reports-CQ9qQ1-n.js} +9 -10
  234. package/studio-dist/server/assets/{reports-C06RXVE2.js → reports-dYDEoBeq.js} +3 -3
  235. package/studio-dist/server/assets/{router-C8MGqlAY.js → router-DkRHNTpE.js} +787 -2862
  236. package/studio-dist/server/assets/{routes-BcFgvqf7.js → routes-B6GfOew4.js} +22 -171
  237. package/studio-dist/server/assets/{search-JAKurDNh.js → search-BJnWLfkG.js} +21 -2
  238. package/studio-dist/server/assets/select-Af7Wibii.js +1609 -0
  239. package/studio-dist/server/assets/{shell-DS3wUexh.js → shell-Hq-hXgnT.js} +6 -5
  240. package/studio-dist/server/assets/{skills-BEnOxiDl.js → skills-B7nEuVbx.js} +9 -8
  241. package/studio-dist/server/assets/{skills-CtrBAtX3.js → skills-B_YYL7q8.js} +3 -3
  242. package/studio-dist/server/assets/specs-BpLUFntA.js +51 -0
  243. package/studio-dist/server/assets/specs-view-0peMVd22.js +426 -0
  244. package/studio-dist/server/assets/spinner-CdwJW4VB.js +20 -0
  245. package/studio-dist/server/assets/{steps-Dq_CwY_s.js → steps-D56DApvK.js} +1 -1
  246. package/studio-dist/server/assets/store-Cs17okNG.js +280 -0
  247. package/studio-dist/server/assets/studio-CAcKp3bM.js +10340 -0
  248. package/studio-dist/server/assets/studio-queries-BtRGzDdh.js +1451 -0
  249. package/studio-dist/server/assets/usage-COdjd1gD.js +25570 -0
  250. package/studio-dist/server/assets/usage-f6pqE1tm.js +24 -0
  251. package/studio-dist/server/assets/useAnchoredPopupScrollLock-DlBKHRw7.js +756 -0
  252. package/studio-dist/server/assets/useMutation-DzTZGenE.js +690 -0
  253. package/studio-dist/server/assets/{__23tanstack-start-server-fn-resolver-M2GBs8s3.js → useSelector-DUmCUXAs.js} +4 -668
  254. package/studio-dist/server/assets/{vault-Fvxt2Tzl.js → vault-BDuIUq0F.js} +8 -5
  255. package/studio-dist/server/assets/{vault-BmWnryh3.js → vault-BVLp6zu3.js} +3 -3
  256. package/studio-dist/server/assets/{views-BgYa-za2.js → views-flRUr21z.js} +4 -4
  257. package/studio-dist/server/assets/{warnings-DzR6fyZh.js → warnings-CDy9pdgL.js} +3 -2
  258. package/studio-dist/server/assets/{delivery-path-C29fBynY.js → workflow-D9GKI2EV.js} +132 -106
  259. package/studio-dist/server/server.js +582 -8
  260. package/src/cli/commands/report/collector.ts +0 -288
  261. package/studio-dist/client/assets/app-CdPiFv59.css +0 -2
  262. package/studio-dist/client/assets/button-BIIHE0EQ.js +0 -3
  263. package/studio-dist/client/assets/companion-view-DM6YyXaR.js +0 -1
  264. package/studio-dist/client/assets/delivery-path-DELxj0Av.js +0 -1
  265. package/studio-dist/client/assets/factory-BZy0E8ty.js +0 -4
  266. package/studio-dist/client/assets/index-B3wkMzjA.js +0 -40
  267. package/studio-dist/client/assets/markdown-view-pQ2Qp_i5.js +0 -1
  268. package/studio-dist/client/assets/panel-CbajlC3p.js +0 -1
  269. package/studio-dist/client/assets/prepaint-CwSrpdFA.js +0 -27
  270. package/studio-dist/client/assets/react-CN2GSx7x.js +0 -1
  271. package/studio-dist/client/assets/reports-DllhYQ5_.js +0 -1
  272. package/studio-dist/client/assets/rolldown-runtime-WkwZ5CU-.js +0 -1
  273. package/studio-dist/client/assets/routes-COm-G3mK.js +0 -1
  274. package/studio-dist/client/assets/skills-DmWAy-jZ.js +0 -1
  275. package/studio-dist/client/assets/specs-BG3Wi3ln.js +0 -1
  276. package/studio-dist/client/assets/steps-DFsH3Neu.js +0 -1
  277. package/studio-dist/client/assets/vault-B2q1nBY5.js +0 -1
  278. package/studio-dist/client/assets/warnings-BSXIyuSQ.js +0 -1
  279. package/studio-dist/client/assets/workflow-DlsQD6Hc.js +0 -1
  280. package/studio-dist/server/assets/companions-BYbHWKOZ.js +0 -15
  281. package/studio-dist/server/assets/createServerFn-F5sAOF8V.js +0 -459
  282. package/studio-dist/server/assets/prepaint-DJfTQ_VH.js +0 -45
  283. package/studio-dist/server/assets/react-Ce6dj15C.js +0 -46
  284. package/studio-dist/server/assets/rolldown-runtime-DYf_mQCB.js +0 -34
  285. package/studio-dist/server/assets/specs-C8rv34-5.js +0 -211
  286. package/studio-dist/server/assets/studio-BeltxxKt.js +0 -216
  287. package/studio-dist/server/assets/workflow-liRYecHk.js +0 -73
@@ -9,7 +9,8 @@ import {
9
9
  TICKETS_OFF,
10
10
  type TicketFormat,
11
11
  } from "../../../lib/delivery/branches";
12
- import { recordDelivery } from "../../../lib/delivery/record-delivery";
12
+ import type { DeliveryEnvironment } from "../../../lib/delivery/environment";
13
+ import { recordDelivery, type DeliveryRefusal } from "../../../lib/delivery/record-delivery";
13
14
  import { isJiraKey, normalizeJiraKey, sameRepository } from "../../../lib/delivery/record";
14
15
  import { resolveForCapability } from "../../../lib/orchestrator/framework-context";
15
16
  import {
@@ -22,10 +23,12 @@ import {
22
23
  NOT_CREATED,
23
24
  pruneWorksetWorktrees,
24
25
  type PruneResult,
26
+ type UmbrellaWorktreeResult,
25
27
  type WorktreeResult,
26
28
  } from "../../../lib/workset/worktree";
27
29
  import { attributeCurrentSession } from "../../../lib/session-attribution";
28
30
  import { errorMessage } from "../../../runtime/error-message";
31
+ import { companionPolicySelectsRtk } from "../../../runtime/rtk-git-guard";
29
32
  import { gitEnvironment } from "../../../runtime/companion-git";
30
33
  import { resolveDeliveryEnvironment } from "../artifact/delivery/environment";
31
34
  import { sharedRefusalMessage } from "../artifact/delivery/output";
@@ -37,7 +40,7 @@ const execFileAsync = promisify(execFile);
37
40
  const n = FRAMEWORK_NAME;
38
41
  const USAGE = [
39
42
  `${n} working worktree: usage: ${n} working worktree <workset-id> [--ticket <KEY>] [--companion <path>] [--no-install] [--json]`,
40
- `${n} working worktree: usage: ${n} working worktree --change <change> [--enter] [--ticket <KEY>] [--companion <path>] [--no-install] [--json]`,
43
+ `${n} working worktree: usage: ${n} working worktree --change <change> [--enter] [--take-branch] [--ticket <KEY>] [--companion <path>] [--no-install] [--json]`,
41
44
  `${n} working worktree: usage: ${n} working worktree prune [--companion <path>] [--json]`,
42
45
  ].join("\n");
43
46
 
@@ -48,12 +51,25 @@ export interface EnterInstruction {
48
51
  tool?: "EnterWorktree" | "mate_enter_worktree";
49
52
  /** The current Working Repository's worktree; absent when it has none or it is unknown. */
50
53
  path?: string;
54
+ /** Why a handoff; on Claude's `tool` with RTK selected, how git runs after the move. */
51
55
  reason?: string;
52
56
  }
53
57
 
54
58
  /** The current Working Repository's worktree, its branch recorded; or why nothing was recorded. */
55
59
  export type RecordedBranch =
56
60
  | { repository: string; branch: string; path: string }
61
+ /**
62
+ * An Umbrella Repository's mirrored worktree on the Workset `branch`: `repositories` were
63
+ * recorded, `failed` names the rest. OpenCode moves the session into `path`; any other
64
+ * runtime hands off to a new session there, for the reason `handoff`.
65
+ */
66
+ | {
67
+ handoff: string;
68
+ path: string;
69
+ branch?: string;
70
+ repositories: string[];
71
+ failed?: string[];
72
+ }
57
73
  | { skipped: string }
58
74
  | { failed: string[] };
59
75
 
@@ -78,6 +94,8 @@ export interface WorkingWorktreeDeps {
78
94
  ticketFormat?: (companion: string) => Promise<TicketFormat>;
79
95
  /** Records the change, and the worktree it moves to, on the agent session this runs in. */
80
96
  attribute?: typeof attributeCurrentSession;
97
+ /** Whether the companion selects RTK, whose git rewrite Claude refuses in an entered worktree. */
98
+ rtkSelected?: (companion: string) => boolean;
81
99
  }
82
100
 
83
101
  async function canonicalPath(candidate: string): Promise<string> {
@@ -109,7 +127,7 @@ type Parsed = {
109
127
  install: boolean;
110
128
  json: boolean;
111
129
  ticket?: string;
112
- } & ({ target: string } | { change: string; enter: boolean });
130
+ } & ({ target: string } | { change: string; enter: boolean; takeBranch: boolean });
113
131
 
114
132
  function parse(argv: string[]): Parsed | null {
115
133
  const positional: string[] = [];
@@ -119,6 +137,7 @@ function parse(argv: string[]): Parsed | null {
119
137
  let install = true;
120
138
  let json = false;
121
139
  let enter = false;
140
+ let takeBranch = false;
122
141
  for (let index = 0; index < argv.length; index += 1) {
123
142
  const arg = argv[index]!;
124
143
  if (arg === "--companion") {
@@ -132,6 +151,7 @@ function parse(argv: string[]): Parsed | null {
132
151
  if (!ticket) return null;
133
152
  } else if (arg === "--no-install") install = false;
134
153
  else if (arg === "--enter") enter = true;
154
+ else if (arg === "--take-branch") takeBranch = true;
135
155
  else if (arg === "--json") json = true;
136
156
  else if (arg.startsWith("-")) return null;
137
157
  else positional.push(arg);
@@ -142,9 +162,9 @@ function parse(argv: string[]): Parsed | null {
142
162
  install,
143
163
  json,
144
164
  };
145
- if (change) return positional.length === 0 ? { change, enter, ...rest } : null;
165
+ if (change) return positional.length === 0 ? { change, enter, takeBranch, ...rest } : null;
146
166
  const [target] = positional;
147
- if (positional.length !== 1 || !target || enter) return null;
167
+ if (positional.length !== 1 || !target || enter || takeBranch) return null;
148
168
  if (target === "prune" && (!install || ticket)) return null;
149
169
  return { target, ...rest };
150
170
  }
@@ -164,29 +184,38 @@ async function resolveCompanion(
164
184
  }
165
185
  }
166
186
  const cwd = deps.cwd ?? process.cwd();
187
+ // Outside Git, as in an Umbrella Repository, the folder itself pairs.
167
188
  const roots = await (deps.checkoutRoots ?? checkoutRoots)(cwd);
168
- if (!roots) return { error: `${cwd} is not inside a Git working tree; pass --companion <path>` };
169
- const inventory = await (deps.collectInventory ?? collectWorkspaceInventory)();
170
- const paired = await Promise.all(
171
- inventory.pairings.map(async (pairing) =>
172
- roots.includes(await canonicalPath(pairing.repository.path)) ? pairing.companionPath : null,
173
- ),
174
- );
175
- const pairedCompanions = [...new Set(paired.filter((entry): entry is string => entry !== null))];
189
+ const pairedCompanions = await pairedWith(roots ?? [await canonicalPath(cwd)], deps);
176
190
  // A registry entry naming a removed folder pairs with nothing; the repo-local link still holds.
177
191
  const companions =
178
192
  pairedCompanions.length > 0
179
193
  ? pairedCompanions
180
194
  : (await launchAmbiguityDeps.resolveLinkedCompanions(cwd)).map((m) => m.companionPath);
195
+ const folder = roots?.[0] ?? cwd;
181
196
  if (companions.length === 1) return { companion: companions[0]! };
182
197
  if (companions.length === 0) {
183
- return { error: `${roots[0]} is not linked to a companion; pass --companion <path>` };
198
+ const where = roots
199
+ ? "is not linked to a companion"
200
+ : "is neither inside a Git working tree nor linked to a companion";
201
+ return { error: `${folder} ${where}; pass --companion <path>` };
184
202
  }
185
203
  return {
186
- error: `${roots[0]} is paired with several companions (${companions.join(", ")}); pass --companion <path>`,
204
+ error: `${folder} is paired with several companions (${companions.join(", ")}); pass --companion <path>`,
187
205
  };
188
206
  }
189
207
 
208
+ /** The companions whose registry pairs with one of the checkout's roots. */
209
+ async function pairedWith(roots: string[], deps: WorkingWorktreeDeps): Promise<string[]> {
210
+ const inventory = await (deps.collectInventory ?? collectWorkspaceInventory)();
211
+ const paired = await Promise.all(
212
+ inventory.pairings.map(async (pairing) =>
213
+ roots.includes(await canonicalPath(pairing.repository.path)) ? pairing.companionPath : null,
214
+ ),
215
+ );
216
+ return [...new Set(paired.filter((entry): entry is string => entry !== null))];
217
+ }
218
+
190
219
  /** As `mate artifact link <change> --branch <branch>` records it, for the current Working Repository. */
191
220
  async function recordBranch(
192
221
  companion: string,
@@ -202,6 +231,17 @@ async function recordBranch(
202
231
  return { failed: [environment.error ?? `cannot resolve the companion ${companion}`] };
203
232
  }
204
233
  const slug = environment.workingRepo?.slug;
234
+ if (!slug && environment.workingRepo?.umbrellaChildren) {
235
+ if (
236
+ !result.umbrella ||
237
+ !(await isSessionUmbrella(environment.workingRepo.path, result.umbrella))
238
+ ) {
239
+ return {
240
+ skipped: `no child of the Umbrella Repository ${environment.workingRepo.path} got a worktree for ${result.workset}`,
241
+ };
242
+ }
243
+ return recordUmbrella(environment, change, result, result.umbrella);
244
+ }
205
245
  if (!slug) return { failed: ["the Working Repository has no origin remote to identify it"] };
206
246
  const entry = result.repositories.find((candidate) => sameRepository(candidate.repository, slug));
207
247
  if (!entry) return { skipped: `${slug} got no worktree for ${result.workset}` };
@@ -210,26 +250,84 @@ async function recordBranch(
210
250
  repository: slug,
211
251
  edit: { delivery: { branch: entry.branch, direct: false } },
212
252
  });
213
- if ("refusal" in outcome) {
214
- const { refusal } = outcome;
215
- return {
216
- failed: [
217
- refusal.reason === "unknown-change"
218
- ? `no active change ${refusal.change}`
219
- : sharedRefusalMessage(refusal),
220
- ],
221
- };
222
- }
253
+ if ("refusal" in outcome) return { failed: [refusalText(outcome.refusal)] };
223
254
  return { repository: entry.repository, branch: entry.branch, path: entry.path };
224
255
  }
225
256
 
257
+ /** The session's folder is the umbrella the mirrored worktree serves, or that worktree. */
258
+ async function isSessionUmbrella(
259
+ folder: string,
260
+ umbrella: UmbrellaWorktreeResult,
261
+ ): Promise<boolean> {
262
+ const [session, ...served] = await Promise.all(
263
+ [folder, umbrella.path, umbrella.worktree].map(canonicalPath),
264
+ );
265
+ return served.includes(session!);
266
+ }
267
+
268
+ /**
269
+ * In an Umbrella Repository session: the branch of every child worktree in the mirrored
270
+ * worktree, recorded per child.
271
+ */
272
+ async function recordUmbrella(
273
+ environment: DeliveryEnvironment,
274
+ change: string,
275
+ result: WorktreeResult,
276
+ umbrella: UmbrellaWorktreeResult,
277
+ ): Promise<RecordedBranch> {
278
+ const children = result.repositories.filter((entry) =>
279
+ umbrella.repositories.includes(entry.repository),
280
+ );
281
+ const recorded: string[] = [];
282
+ const failed: string[] = [];
283
+ for (const entry of children) {
284
+ // oxlint-disable-next-line no-await-in-loop -- one Delivery Record, written in order
285
+ const outcome = await recordDelivery(environment, {
286
+ changes: [change],
287
+ repository: entry.repository,
288
+ edit: { delivery: { branch: entry.branch, direct: false } },
289
+ });
290
+ if ("refusal" in outcome) failed.push(`${entry.repository}: ${refusalText(outcome.refusal)}`);
291
+ else recorded.push(entry.repository);
292
+ }
293
+ // The first child folder's in name order, as `currentBranch` reads the session's later.
294
+ const branch = children.toSorted((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))[0]
295
+ ?.branch;
296
+ return {
297
+ handoff: `${umbrella.worktree} is a mirrored umbrella worktree, not a Git worktree`,
298
+ path: umbrella.worktree,
299
+ ...(branch ? { branch } : {}),
300
+ repositories: recorded,
301
+ ...(failed.length > 0 ? { failed } : {}),
302
+ };
303
+ }
304
+
305
+ function refusalText(refusal: DeliveryRefusal): string {
306
+ return refusal.reason === "unknown-change"
307
+ ? `no active change ${refusal.change}`
308
+ : sharedRefusalMessage(refusal);
309
+ }
310
+
311
+ /** Claude Code's worktree guard refuses RTK's `rtk git` rewrite once the session moved. */
312
+ const RTK_GIT_NOTE =
313
+ "then run git as RTK_DISABLED=1 git ...: Claude Code refuses git run through RTK in the entered worktree";
314
+
226
315
  /** Detected by the markers each runtime sets for the commands its agent runs. */
227
316
  function enterInstruction(
228
317
  env: Record<string, string | undefined>,
229
318
  recorded: RecordedBranch,
319
+ rtkSelected: () => boolean = () => false,
230
320
  ): EnterInstruction {
231
321
  const runtime = runtimeOf(env);
232
322
  if ("skipped" in recorded) return { runtime, action: "handoff", reason: recorded.skipped };
323
+ // Before `failed`: a mirrored worktree stays the place to work on when a record failed.
324
+ if ("handoff" in recorded) {
325
+ // Claude's `EnterWorktree` takes only Git worktrees; `mate_enter_worktree` takes this folder.
326
+ if (runtime === "opencode") {
327
+ return { runtime, action: "tool", tool: ENTER_TOOLS.opencode, path: recorded.path };
328
+ }
329
+ return { runtime, action: "handoff", path: recorded.path, reason: recorded.handoff };
330
+ }
233
331
  if ("failed" in recorded) {
234
332
  const reason = `recording the delivery branch failed: ${recorded.failed.join("; ")}`;
235
333
  return { runtime, action: "handoff", reason };
@@ -239,7 +337,8 @@ function enterInstruction(
239
337
  const reason = "this Agent Runtime cannot move a running session";
240
338
  return { runtime, action: "handoff", path: target, reason };
241
339
  }
242
- return { runtime, action: "tool", tool: ENTER_TOOLS[runtime], path: target };
340
+ const note = runtime === "claude" && rtkSelected() ? { reason: RTK_GIT_NOTE } : {};
341
+ return { runtime, action: "tool", tool: ENTER_TOOLS[runtime], path: target, ...note };
243
342
  }
244
343
 
245
344
  const ENTER_TOOLS = {
@@ -254,7 +353,10 @@ function runtimeOf(env: Record<string, string | undefined>): EnterInstruction["r
254
353
  }
255
354
 
256
355
  function enterLine(enter: EnterInstruction): string {
257
- if (enter.action === "tool") return `${n}: enter: call ${enter.tool} with ${enter.path}`;
356
+ if (enter.action === "tool") {
357
+ const note = enter.reason ? `; ${enter.reason}` : "";
358
+ return `${n}: enter: call ${enter.tool} with ${enter.path}${note}`;
359
+ }
258
360
  if (enter.path) return `${n}: enter: start a new session in ${enter.path} (${enter.reason})`;
259
361
  return `${n}: enter: not entering (${enter.reason})`;
260
362
  }
@@ -282,6 +384,14 @@ function printCreated(result: WorktreeResult): void {
282
384
  } else if (wrap.outcome === "skipped") {
283
385
  process.stdout.write(`${prefix} wrap skipped (${wrap.reason})\n`);
284
386
  }
387
+ const { include } = entry;
388
+ if (include.sources.length > 0) {
389
+ const copied = include.copied.length > 0 ? include.copied.join(", ") : "nothing new";
390
+ process.stdout.write(`${prefix} copied from ${include.sources.join(", ")}: ${copied}\n`);
391
+ }
392
+ for (const failed of include.failed) {
393
+ process.stdout.write(`${prefix} copying ${failed.path} failed (${failed.reason})\n`);
394
+ }
285
395
  const { command, outcome, reason } = entry.install;
286
396
  process.stdout.write(
287
397
  outcome === "skipped"
@@ -300,6 +410,21 @@ function printCreated(result: WorktreeResult): void {
300
410
  }
301
411
  if (entry.error) console.error(`${n} working worktree: ${entry.repository}: ${entry.error}`);
302
412
  }
413
+ const { umbrella } = result;
414
+ if (!umbrella) return;
415
+ const prefix = `${n}: ${umbrella.path}:`;
416
+ process.stdout.write(`${prefix} ${umbrella.action} mirrored worktree ${umbrella.worktree}\n`);
417
+ const { wrap } = umbrella;
418
+ if (wrap.outcome === "ok") {
419
+ process.stdout.write(`${prefix} wrapped for ${wrap.runtimes.join(", ")}\n`);
420
+ } else if (wrap.outcome === "skipped") {
421
+ process.stdout.write(`${prefix} wrap skipped (${wrap.reason})\n`);
422
+ }
423
+ const { index } = umbrella;
424
+ process.stdout.write(
425
+ `${prefix} tokensave index ${index.outcome}${index.reason ? ` (${index.reason})` : ""}\n`,
426
+ );
427
+ if (umbrella.error) console.error(`${n} working worktree: ${umbrella.path}: ${umbrella.error}`);
303
428
  }
304
429
 
305
430
  function printPruned(result: PruneResult): void {
@@ -311,7 +436,15 @@ function printPruned(result: PruneResult): void {
311
436
  `${n}: kept ${entry.path} (${entry.workset}, ${entry.repository}): ${entry.reason}\n`,
312
437
  );
313
438
  }
314
- if (result.removed.length === 0 && result.kept.length === 0) {
439
+ for (const entry of result.umbrellas?.removed ?? []) {
440
+ process.stdout.write(`${n}: removed mirrored worktree ${entry.path} (${entry.workset})\n`);
441
+ }
442
+ for (const entry of result.umbrellas?.kept ?? []) {
443
+ process.stdout.write(
444
+ `${n}: kept mirrored worktree ${entry.path} (${entry.workset}): ${entry.reason}\n`,
445
+ );
446
+ }
447
+ if (result.removed.length === 0 && result.kept.length === 0 && !result.umbrellas) {
315
448
  process.stdout.write(`${n}: no worktree of a Done Workset to prune\n`);
316
449
  }
317
450
  }
@@ -320,7 +453,9 @@ function printPruned(result: PruneResult): void {
320
453
  * `mate working worktree <workset-id>` creates or reuses the Workset's worktree in each
321
454
  * Working Repository; `--change <change>` does so for the Workset the change resolves to,
322
455
  * and with `--enter` also records the current repository's branch as the change's delivery
323
- * and reports how the Agent Runtime enters the worktree; `mate working worktree prune`
456
+ * and reports how the Agent Runtime enters the worktree; with `--take-branch` a branch
457
+ * checked out in a main checkout without tracked changes, inherited ones included, moves to the worktree, leaving
458
+ * that checkout on a detached HEAD; `mate working worktree prune`
324
459
  * removes those of Done Worksets.
325
460
  */
326
461
  export async function runWorkingWorktreeCommand(
@@ -370,6 +505,7 @@ export async function runWorkingWorktreeCommand(
370
505
  install: parsed.install,
371
506
  streamInstall: !parsed.json,
372
507
  ...(ticket ? { ticket } : {}),
508
+ ...("change" in parsed && parsed.takeBranch ? { takeBranch: true } : {}),
373
509
  };
374
510
  const result =
375
511
  "change" in parsed
@@ -381,13 +517,18 @@ export async function runWorkingWorktreeCommand(
381
517
  if ("change" in parsed && parsed.enter && result.ok) {
382
518
  const record = deps.recordBranch ?? recordBranch;
383
519
  const recorded = await record(companion, parsed.change, result, deps.cwd ?? process.cwd());
384
- if ("failed" in recorded) result.warnings.push(...recorded.failed);
385
- enter = enterInstruction(deps.env ?? process.env, recorded);
520
+ if ("failed" in recorded) result.warnings.push(...(recorded.failed ?? []));
521
+ // Read only for a Claude move, the one the note serves.
522
+ const rtkSelected = () => (deps.rtkSelected ?? companionPolicySelectsRtk)(companion);
523
+ enter = enterInstruction(deps.env ?? process.env, recorded, rtkSelected);
524
+ // A handed-off umbrella session stays where it is; its successor registers the branch.
525
+ const handedOff = "handoff" in recorded && enter.action !== "tool";
526
+ const move =
527
+ "branch" in recorded && recorded.branch && !handedOff
528
+ ? { cwd: recorded.path, branch: recorded.branch }
529
+ : undefined;
386
530
  await (deps.attribute ?? attributeCurrentSession)(
387
- {
388
- change: parsed.change,
389
- ...("path" in recorded ? { move: { cwd: recorded.path, branch: recorded.branch } } : {}),
390
- },
531
+ { change: parsed.change, ...(move ? { move } : {}) },
391
532
  deps.env ?? process.env,
392
533
  );
393
534
  }
package/src/cli/main.ts CHANGED
@@ -122,6 +122,9 @@ export async function main(argv = process.argv, deps: MainDeps = mainDeps): Prom
122
122
  // scheduleBackgroundCheck() has been observed to race a large final stdout
123
123
  // write against process exit, truncating it.
124
124
  const ownsStdout = isPluginCommand;
125
+ // `report` prints one large JSON contract, so it skips the background check
126
+ // too but keeps update enforcement and its stderr banner.
127
+ const skipsBackgroundCheck = ownsStdout || command === "report";
125
128
 
126
129
  // Every dispatch case opens with a gate() call declaring what the command
127
130
  // needs before it may run. Declared gates run in fixed order — update
@@ -131,7 +134,7 @@ export async function main(argv = process.argv, deps: MainDeps = mainDeps): Prom
131
134
  const gate = async (needs: GateNeeds): Promise<boolean> => {
132
135
  if (!ownsStdout) {
133
136
  const updateStore = new UpdateStateStore();
134
- scheduleBackgroundCheck(updateStore);
137
+ if (!skipsBackgroundCheck) scheduleBackgroundCheck(updateStore);
135
138
  if (needs.updateGuard && (await enforceUpdateIfRequired(updateStore))) {
136
139
  process.exitCode = 1;
137
140
  return false;
@@ -272,7 +275,19 @@ export async function main(argv = process.argv, deps: MainDeps = mainDeps): Prom
272
275
  await runLaunchOpenCodeCommand(argv.slice(3), { directPassthrough: true });
273
276
  return;
274
277
  case "report":
275
- if (!(await gate({ updateGuard: true, install: true }))) return;
278
+ if (!(await gate({ updateGuard: true, install: true }))) {
279
+ console.log(
280
+ JSON.stringify({
281
+ kind: "error",
282
+ version: 1,
283
+ error: {
284
+ code: "PREFLIGHT_FAILED",
285
+ message: "Mate must be updated or installed before reporting; see stderr",
286
+ },
287
+ }),
288
+ );
289
+ return;
290
+ }
276
291
  await runReportCommand(argv.slice(3));
277
292
  return;
278
293
  case "studio":
package/src/cli/usage.ts CHANGED
@@ -23,7 +23,7 @@ export function usage(): string {
23
23
  ` ${n} working cleanup`,
24
24
  ` ${n} working link --companion <path> --yes`,
25
25
  ` ${n} working worktree <workset-id> [--companion <path>] [--no-install] [--json]`,
26
- ` ${n} working worktree --change <change> [--enter] [--companion <path>] [--no-install] [--json]`,
26
+ ` ${n} working worktree --change <change> [--enter] [--take-branch] [--companion <path>] [--no-install] [--json]`,
27
27
  ` ${n} working worktree prune [--companion <path>] [--json]`,
28
28
  ` ${n} wrap [--companion PATH]`,
29
29
  ` ${n} unwrap`,
@@ -0,0 +1,48 @@
1
+ // Deny a git call RTK would wrap in a Claude session moved into a linked worktree.
2
+ import { movedIntoLinkedWorktree } from "../runtime/entered-worktree";
3
+ import {
4
+ companionSelectsRtk,
5
+ runnableGitCommand,
6
+ type RewriteRunner,
7
+ } from "../runtime/rtk-git-guard";
8
+ import { hookOutcome, type HookEnv, type HookOutcome } from "./hook-io";
9
+
10
+ interface BashHookInput {
11
+ cwd?: unknown;
12
+ tool_input?: unknown;
13
+ }
14
+
15
+ export interface RtkWorktreeGitDeps {
16
+ rtkSelected?: (cwd: string, env: HookEnv) => boolean;
17
+ rewrite?: RewriteRunner;
18
+ }
19
+
20
+ /**
21
+ * A deny naming the runnable command, else no output. Never `updatedInput`: two
22
+ * rewriting hooks race and the slower one wins, so a rewrite could lose to RTK's.
23
+ * Cheapest checks first; `rtk rewrite` runs only for a moved session with RTK selected.
24
+ */
25
+ export function buildRtkWorktreeGit(
26
+ input: unknown,
27
+ env: HookEnv = process.env,
28
+ deps: RtkWorktreeGitDeps = {},
29
+ ): HookOutcome {
30
+ try {
31
+ const { cwd, tool_input: toolInput } = (input ?? {}) as BashHookInput;
32
+ const command = (toolInput as { command?: unknown } | null | undefined)?.command;
33
+ if (typeof cwd !== "string" || typeof command !== "string") return hookOutcome(null);
34
+ if (!movedIntoLinkedWorktree(cwd, env.CLAUDE_PROJECT_DIR)) return hookOutcome(null);
35
+ if (!(deps.rtkSelected ?? companionSelectsRtk)(cwd, env)) return hookOutcome(null);
36
+ const runnable = runnableGitCommand(command, deps.rewrite);
37
+ if (!runnable) return hookOutcome(null);
38
+ return hookOutcome({
39
+ hookSpecificOutput: {
40
+ hookEventName: "PreToolUse",
41
+ permissionDecision: "deny",
42
+ permissionDecisionReason: `This session moved into a linked worktree, where Claude Code refuses git run through RTK (rtk git). Run instead: ${runnable}`,
43
+ },
44
+ });
45
+ } catch {
46
+ return hookOutcome(null);
47
+ }
48
+ }
@@ -251,6 +251,16 @@ export function commandMatches(command: string): string[] {
251
251
  return targets;
252
252
  }
253
253
 
254
+ const stringOrEmpty = (value: unknown) => (typeof value === "string" ? value : "");
255
+
256
+ function replacement(edit: Record<string, unknown>) {
257
+ return {
258
+ oldText: stringOrEmpty(edit.old_string),
259
+ newText: stringOrEmpty(edit.new_string),
260
+ all: edit.replace_all === true,
261
+ };
262
+ }
263
+
254
264
  /** Claude tool payloads in the shape the shared secret guard reads. */
255
265
  function secretToolCall(
256
266
  toolName: string,
@@ -271,19 +281,40 @@ function secretToolCall(
271
281
  case "Edit":
272
282
  return {
273
283
  kind: "write",
274
- writes: [{ path: target(toolInput.file_path), content: text(toolInput.new_string) }],
284
+ writes: [
285
+ {
286
+ path: target(toolInput.file_path),
287
+ content: text(toolInput.new_string),
288
+ result: { kind: "replace", edits: [replacement(toolInput)] },
289
+ },
290
+ ],
275
291
  };
276
292
  case "MultiEdit": {
277
- const edits = Array.isArray(toolInput.edits) ? toolInput.edits : [];
278
- const content = edits
279
- .map((edit) => (edit && typeof edit === "object" ? text(edit.new_string) : ""))
280
- .join("\n");
281
- return { kind: "write", writes: [{ path: target(toolInput.file_path), content }] };
293
+ const edits = (Array.isArray(toolInput.edits) ? toolInput.edits : []).map((edit) =>
294
+ edit && typeof edit === "object" ? (edit as Record<string, unknown>) : {},
295
+ );
296
+ const content = edits.map((edit) => text(edit.new_string)).join("\n");
297
+ return {
298
+ kind: "write",
299
+ writes: [
300
+ {
301
+ path: target(toolInput.file_path),
302
+ content,
303
+ result: { kind: "replace", edits: edits.map(replacement) },
304
+ },
305
+ ],
306
+ };
282
307
  }
283
308
  case "NotebookEdit":
284
309
  return {
285
310
  kind: "write",
286
- writes: [{ path: target(toolInput.notebook_path), content: text(toolInput.new_source) }],
311
+ writes: [
312
+ {
313
+ path: target(toolInput.notebook_path),
314
+ content: text(toolInput.new_source),
315
+ result: { kind: "unknown" },
316
+ },
317
+ ],
287
318
  };
288
319
  case "Bash":
289
320
  return { kind: "shell", command: text(toolInput.command) };
@@ -0,0 +1,122 @@
1
+ /** A Delivery Branch template: a fixed prefix ending in `/`, `{workset}`, and optional `{ticket}`. */
2
+ export type BranchTemplate = string;
3
+
4
+ export const DEFAULT_BRANCH_TEMPLATE: BranchTemplate = "workset/{ticket}-{workset}";
5
+
6
+ const PLACEHOLDER = /\{([^{}]*)\}/g;
7
+ const SEPARATORS = new Set(["-", "_", "/"]);
8
+ // Any case, as `isJiraKey` accepts it; see `matchBranchTemplate` for an all-lowercase one.
9
+ const TICKET_KEY = "[A-Za-z][A-Za-z0-9]+-\\d+";
10
+
11
+ export interface BranchTemplateSetting {
12
+ template: BranchTemplate;
13
+ /** Set for an invalid value, which counts as the default. */
14
+ diagnostic: string | null;
15
+ }
16
+
17
+ /** True when `name` passes `git check-ref-format --branch`, checked without Git. */
18
+ function isBranchName(name: string): boolean {
19
+ if (!name || name === "@" || name.startsWith("-") || name.endsWith("/") || name.endsWith(".")) {
20
+ return false;
21
+ }
22
+ // oxlint-disable-next-line no-control-regex -- control characters are invalid in refs
23
+ if (/[\u0000- \u007f~^:?*[\\]|\.\.|@\{|\/\//.test(name)) return false;
24
+ return name
25
+ .split("/")
26
+ .every((part) => part !== "" && !part.startsWith(".") && !part.endsWith(".lock"));
27
+ }
28
+
29
+ /** The rule a template breaks, or null when it is valid. */
30
+ function brokenRule(template: string): string | null {
31
+ const names = [...template.matchAll(PLACEHOLDER)].map((match) => match[1]!);
32
+ const unknown = names.find((name) => name !== "workset" && name !== "ticket");
33
+ if (unknown !== undefined) {
34
+ return `unknown placeholder {${unknown}}; only {workset} and {ticket} exist`;
35
+ }
36
+ if (names.filter((name) => name === "workset").length !== 1) {
37
+ return "{workset} must appear exactly once";
38
+ }
39
+ if (names.filter((name) => name === "ticket").length > 1) {
40
+ return "{ticket} may appear at most once";
41
+ }
42
+ if (/[{}]/.test(template.replace(PLACEHOLDER, ""))) return "a brace is not part of a placeholder";
43
+ if (!branchTemplatePrefix(template).endsWith("/")) {
44
+ return "a fixed prefix ending in / must precede the first placeholder";
45
+ }
46
+ const samples = [
47
+ applyBranchTemplate(template, "acme-fix"),
48
+ applyBranchTemplate(template, "acme-fix", "ABC-123"),
49
+ ];
50
+ if (!samples.every(isBranchName)) return "it does not yield a valid Git branch name";
51
+ return null;
52
+ }
53
+
54
+ /** A configured template; absent means the default, invalid the default with a diagnostic. */
55
+ export function parseBranchTemplate(value: unknown): BranchTemplateSetting {
56
+ if (value === undefined) return { template: DEFAULT_BRANCH_TEMPLATE, diagnostic: null };
57
+ const rule = typeof value === "string" ? brokenRule(value) : "it is not a string";
58
+ if (rule === null) return { template: value as string, diagnostic: null };
59
+ return {
60
+ template: DEFAULT_BRANCH_TEMPLATE,
61
+ diagnostic: `Invalid branchTemplate ${JSON.stringify(value)} on the openspec capability: ${rule}; ${DEFAULT_BRANCH_TEMPLATE} applies.`,
62
+ };
63
+ }
64
+
65
+ /**
66
+ * The branch a template names for a Workset. Without a ticket, `{ticket}` and one adjacent
67
+ * separator go, the following one first: `workset/{ticket}-{workset}` → `workset/<id>`.
68
+ */
69
+ export function applyBranchTemplate(
70
+ template: BranchTemplate,
71
+ worksetId: string,
72
+ ticket?: string | null,
73
+ ): string {
74
+ const shaped = ticket ? template.replace("{ticket}", ticket) : withoutTicket(template);
75
+ return shaped.replace("{workset}", worksetId);
76
+ }
77
+
78
+ /** The template without `{ticket}` and one adjacent separator; the prefix's own `/` stays. */
79
+ function withoutTicket(template: BranchTemplate): string {
80
+ const at = template.indexOf("{ticket}");
81
+ if (at < 0) return template;
82
+ const end = at + "{ticket}".length;
83
+ if (SEPARATORS.has(template[end] ?? "")) return template.slice(0, at) + template.slice(end + 1);
84
+ const separatorBefore =
85
+ at > branchTemplatePrefix(template).length && SEPARATORS.has(template[at - 1]!);
86
+ return template.slice(0, separatorBefore ? at - 1 : at) + template.slice(end);
87
+ }
88
+
89
+ /** The fixed text before the first placeholder, e.g. `feature/`; scopes ref listing. */
90
+ export function branchTemplatePrefix(template: BranchTemplate): string {
91
+ const at = template.indexOf("{");
92
+ return at < 0 ? template : template.slice(0, at);
93
+ }
94
+
95
+ function escape(literal: string): string {
96
+ return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
97
+ }
98
+
99
+ /**
100
+ * Whether `branch` is the template's branch for the Workset, and with which ticket: null for
101
+ * the name without one, else the key as written.
102
+ */
103
+ export function matchBranchTemplate(
104
+ template: BranchTemplate,
105
+ branch: string,
106
+ worksetId: string,
107
+ ): { ticket: string | null } | null {
108
+ if (branch === applyBranchTemplate(template, worksetId)) return { ticket: null };
109
+ if (!template.includes("{ticket}")) return null;
110
+ const source = template
111
+ .split(/(\{ticket\}|\{workset\})/)
112
+ .map((part) => {
113
+ if (part === "{ticket}") return `(${TICKET_KEY})`;
114
+ return escape(part === "{workset}" ? worksetId : part);
115
+ })
116
+ .join("");
117
+ const ticket = new RegExp(`^${source}$`).exec(branch)?.[1];
118
+ if (!ticket) return null;
119
+ // After {workset}, an all-lowercase key reads as the tail of a longer Workset id: `fix-login-2`.
120
+ const trailing = template.indexOf("{ticket}") > template.indexOf("{workset}");
121
+ return trailing && ticket === ticket.toLowerCase() ? null : { ticket };
122
+ }