@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
@@ -6,39 +6,48 @@ import { FRAMEWORK_NAME } from "../../framework";
6
6
  import { gitEnvironment, withoutAskPass } from "../../runtime/companion-git";
7
7
  import { withCompanionLock } from "../../runtime/companion-lock";
8
8
  import { errorMessage } from "../../runtime/error-message";
9
+ import { readGitLayout } from "../../runtime/git-layout";
10
+ import { repoLocalRegistryPath } from "../../runtime/repo-local";
9
11
  import type { WrapRuntime } from "../../runtime/runtime-document-manifest";
10
12
  import { readWrapState, WRAP_RUNTIMES } from "../../runtime/wrap-state";
11
13
  import { cleanupWorkingRepository } from "../../tools/setup/working-repo-cleanup";
12
14
  import { locateChange } from "../change-layout";
13
- import { workingRepoGit } from "../delivery/branches";
14
- import { mergeGit } from "../delivery/merge-git";
15
+ import { classifyBranch, configuredProtectedPatterns } from "../delivery/branches";
16
+ import { deliveryCheckout } from "../delivery/checkout";
15
17
  import { type DeliveryRecord, readDeliveryRecord } from "../delivery/record";
16
18
  import {
17
- listRefsWith,
18
- mergeProbeWith,
19
19
  newBranchBase,
20
20
  resolveDeliveryBranch,
21
21
  worktreeAddArgs,
22
22
  type BranchSource,
23
23
  } from "../delivery/resolve-branch";
24
+ import { repositoryPath } from "../delivery/forge";
24
25
  import { scopedRepositories } from "../openspec-scopes";
25
26
  import { attendedLockOptions } from "../orchestrator/companion-git-sync";
27
+ import { readCompanionConfig } from "../orchestrator/config-store";
26
28
  import {
27
29
  findRepoLocalLinkTo,
28
30
  readCompanionRegistry,
29
31
  writeRepoLocalRegistryEntry,
30
32
  } from "../orchestrator/repository-link";
33
+ import { projectionEntries } from "../orchestrator/projection-entries";
31
34
  import type { LinkedRepository } from "../orchestrator/types";
35
+ import { linkedCheckoutsOf, type EntryCheckout } from "../orchestrator/umbrella-checkouts";
32
36
  import { runWrapPass } from "../orchestrator/wrap-pass";
33
- import { identityOf } from "./repositories";
34
- import { indexWorktree, type IndexOutcome, type TokensaveRunner } from "./worktree-index";
37
+ import {
38
+ indexWorktree,
39
+ UMBRELLA_NOT_INDEXED,
40
+ type IndexOutcome,
41
+ type TokensaveRunner,
42
+ } from "./worktree-index";
43
+ import { copyIncludedFiles, selectIncludedFiles, type IncludeOutcome } from "./worktree-include";
35
44
  import { findWorkset, readWorksets, resolveWorksetBranch, resolveWorksetOf } from "./record";
36
45
 
37
46
  /**
38
47
  * Workset worktrees outside the factory: one Git worktree per Working Repository at
39
48
  * `<main checkout>.worktrees/<workset-id>`, on the Workset's Delivery Branch, linked to
40
- * the companion, wrapped like its main checkout and installed. Env files are reported by
41
- * path, never opened.
49
+ * the companion, wrapped like its main checkout and installed. Ignored files named by the
50
+ * main checkout's include files are copied in; other env files are reported by path only.
42
51
  */
43
52
 
44
53
  export interface GitResult {
@@ -51,6 +60,8 @@ export interface GitRunOptions {
51
60
  /** Added to the promptless environment every command gets. */
52
61
  env?: Record<string, string>;
53
62
  timeoutMs?: number;
63
+ /** Written to standard input, which is then closed. */
64
+ input?: string;
54
65
  }
55
66
 
56
67
  export type GitRunner = (
@@ -101,16 +112,36 @@ export interface WorktreeRepositoryResult {
101
112
  wrap: WrapOutcome;
102
113
  /** The worktree's tokensave index; a failure only warns. */
103
114
  index: IndexOutcome;
115
+ /** Ignored files copied from the main checkout by its include files. */
116
+ include: IncludeOutcome;
104
117
  /** Env files of the main checkout the worktree lacks, relative to the repository root. */
105
118
  missingEnv: string[];
106
119
  /** Set when a step for this repository failed. */
107
120
  error?: string;
108
121
  }
109
122
 
123
+ /** An Umbrella Repository's mirrored worktree, linked and wrapped like the umbrella. */
124
+ export interface UmbrellaWorktreeResult {
125
+ /** The Umbrella Repository. */
126
+ path: string;
127
+ /** The mirrored worktree folder holding the children's worktrees. */
128
+ worktree: string;
129
+ action: "created" | "reused";
130
+ /** The children whose worktree the folder holds, as `org/repository`. */
131
+ repositories: string[];
132
+ wrap: WrapOutcome;
133
+ /** The folder's tokensave index, kept when the umbrella has one; a failure only warns. */
134
+ index: IndexOutcome;
135
+ /** Set when linking or wrapping the folder failed; its worktrees stay. */
136
+ error?: string;
137
+ }
138
+
110
139
  export interface WorktreeResult {
111
140
  workset: string;
112
141
  ok: boolean;
113
142
  repositories: WorktreeRepositoryResult[];
143
+ /** Present only when a repository is an Umbrella Repository's child. */
144
+ umbrella?: UmbrellaWorktreeResult;
114
145
  diagnostics: string[];
115
146
  warnings: string[];
116
147
  }
@@ -127,9 +158,21 @@ export interface PruneTarget {
127
158
  changes: readonly string[];
128
159
  }
129
160
 
161
+ /** An Umbrella Repository's mirrored worktree of a Workset. */
162
+ export interface PruneMirrorEntry {
163
+ workset: string;
164
+ umbrella: string;
165
+ path: string;
166
+ }
167
+
130
168
  export interface PruneResult {
131
169
  removed: PruneEntry[];
132
170
  kept: (PruneEntry & { reason: string })[];
171
+ /** Present only when a pruned Workset has a mirrored umbrella worktree. */
172
+ umbrellas?: {
173
+ removed: PruneMirrorEntry[];
174
+ kept: (PruneMirrorEntry & { reason: string })[];
175
+ };
133
176
  warnings: string[];
134
177
  }
135
178
 
@@ -145,16 +188,21 @@ function promptlessEnv(): NodeJS.ProcessEnv {
145
188
  const runGit: GitRunner = (cwd, args, options = {}) =>
146
189
  new Promise<GitResult>((resolve) => {
147
190
  let timer: ReturnType<typeof setTimeout> | undefined;
191
+ // Unbounded: a merge check pipes a whole `git log -p` range into `git patch-id`.
148
192
  const child = execFile(
149
193
  "git",
150
194
  args,
151
- { cwd, env: { ...promptlessEnv(), ...options.env }, maxBuffer: 16 * 1024 * 1024 },
195
+ { cwd, env: { ...promptlessEnv(), ...options.env }, maxBuffer: Infinity },
152
196
  (error, stdout, stderr) => {
153
197
  clearTimeout(timer);
154
198
  const code = error ? (typeof error.code === "number" ? error.code : 1) : 0;
155
199
  resolve({ code, stdout: String(stdout), stderr: String(stderr) });
156
200
  },
157
201
  );
202
+ if (options.input !== undefined) {
203
+ child.stdin?.on("error", () => {});
204
+ child.stdin?.end(options.input);
205
+ }
158
206
  const { timeoutMs } = options;
159
207
  if (timeoutMs !== undefined) {
160
208
  // Resolved without awaiting `close`: an SSH grandchild may hold the pipes open.
@@ -271,23 +319,42 @@ async function listWorktrees(git: GitRunner, repo: string): Promise<WorktreeEntr
271
319
  );
272
320
  }
273
321
 
322
+ /** A linked checkout; `umbrella` is set for an Umbrella Repository's child, whose id is the umbrella's. */
323
+ type LinkedCheckout = LinkedRepository & { umbrella?: string };
324
+
274
325
  interface LinkedLookup {
275
- linked: LinkedRepository | null;
326
+ linked: LinkedCheckout | null;
276
327
  /** Registered paths that no longer exist. */
277
328
  missing: string[];
278
329
  }
279
330
 
331
+ /** Every checkout linked to the companion, in lookup order, with its `org/repository`. */
332
+ interface LinkedIndex {
333
+ checkouts: { linked: LinkedCheckout; identity: string | null }[];
334
+ /** Registered paths that no longer exist. */
335
+ missing: string[];
336
+ }
337
+
338
+ /** The first checkout in the index whose `origin` is the repository. */
339
+ function linkedCheckout(index: LinkedIndex, repository: string): LinkedLookup {
340
+ // The first match in registry order decides, umbrella children in name order.
341
+ const match = index.checkouts.find(
342
+ ({ identity }) => identity?.toLowerCase() === repository.toLowerCase(),
343
+ );
344
+ return { linked: match?.linked ?? null, missing: index.missing };
345
+ }
346
+
280
347
  /**
281
- * The first checkout linked to the companion whose `origin` is the repository: an
282
- * existing registered one, else the checkout holding `cwd` when its repo-local link
283
- * names the companion, so an entry left naming a removed folder does not hide it.
348
+ * The existing registered checkouts, an Umbrella Repository's children included, then
349
+ * the one the repo-local link holding `cwd` names, so an entry left naming a removed
350
+ * folder does not hide it. Read once per run: expanding an umbrella reads every child's
351
+ * `origin`.
284
352
  */
285
- async function linkedCheckout(
353
+ async function linkedIndex(
286
354
  companionPath: string,
287
- repository: string,
288
355
  git: GitRunner,
289
356
  cwd: string,
290
- ): Promise<LinkedLookup> {
357
+ ): Promise<LinkedIndex> {
291
358
  let repos: LinkedRepository[] = [];
292
359
  try {
293
360
  repos = (await readCompanionRegistry(companionPath)).repos;
@@ -296,24 +363,50 @@ async function linkedCheckout(
296
363
  }
297
364
  const present = await Promise.all(repos.map((repo) => exists(repo.path)));
298
365
  const current = await findRepoLocalLinkTo(cwd, companionPath);
299
- const candidates = [...repos.filter((_, index) => present[index]), ...(current ? [current] : [])];
300
- const identities = await Promise.all(
301
- candidates.map(async (repo) => {
302
- // Raw config, not `remote get-url`, so `insteadOf` rewrites do not change the identity.
303
- const remote = await git(repo.path, ["config", "--get", "remote.origin.url"]);
304
- return remote.code === 0 ? identityOf(remote.stdout.trim()) : null;
305
- }),
306
- );
307
- // The first match in registry order decides.
308
- const index = identities.findIndex(
309
- (identity) => identity?.toLowerCase() === repository.toLowerCase(),
366
+ const entries = [...repos.filter((_, index) => present[index]), ...(current ? [current] : [])];
367
+ const readOrigin = async (checkout: string) => {
368
+ // Raw config, not `remote get-url`, so `insteadOf` rewrites do not change the identity.
369
+ const remote = await git(checkout, ["config", "--get", "remote.origin.url"]);
370
+ return remote.code === 0 ? remote.stdout.trim() || null : null;
371
+ };
372
+ const expanded = await Promise.all(
373
+ entries.map(async (entry) =>
374
+ Promise.all(
375
+ (await linkedCheckoutsOf(entry, readOrigin, readOrigin)).map(async (checkout) => ({
376
+ linked: { ...entry, ...(await mainChild(checkout)) },
377
+ identity: checkout.remote ? repositoryPath(checkout.remote) : null,
378
+ })),
379
+ ),
380
+ ),
310
381
  );
311
382
  return {
312
- linked: index === -1 ? null : candidates[index]!,
383
+ checkouts: expanded.flat(),
313
384
  missing: repos.filter((_, at) => !present[at]).map((repo) => repo.path),
314
385
  };
315
386
  }
316
387
 
388
+ /**
389
+ * The checkout and umbrella an entry's checkout stands for. A child of a mirrored worktree
390
+ * `<umbrella>.worktrees/<id>/<name>`, a worktree of `<umbrella>/<name>`, stands for that
391
+ * main checkout, so the real umbrella stays the one mirrored.
392
+ */
393
+ async function mainChild(checkout: EntryCheckout): Promise<{ path: string; umbrella?: string }> {
394
+ const { path: child } = checkout;
395
+ if (!checkout.umbrella) return { path: child };
396
+ // Canonical, so an umbrella reached by a registry path and by Git's paths is one.
397
+ const umbrella = await canonical(checkout.umbrella);
398
+ const layout = readGitLayout(child);
399
+ if (layout?.kind === "linked" && path.basename(layout.commonDir) === ".git") {
400
+ const main = path.dirname(layout.commonDir);
401
+ const real = await canonical(path.dirname(main));
402
+ const mirrored =
403
+ path.basename(main) === path.basename(child) &&
404
+ (await canonical(worktreePathFor(real, path.basename(umbrella)))) === umbrella;
405
+ if (mirrored) return { path: main, umbrella: real };
406
+ }
407
+ return { path: child, umbrella };
408
+ }
409
+
317
410
  interface Plan {
318
411
  repository: string;
319
412
  /** The main checkout's Repository Link id, which the worktree's link repeats. */
@@ -325,6 +418,10 @@ interface Plan {
325
418
  /** Start point when `source` is `new`. */
326
419
  base?: string;
327
420
  reuse: boolean;
421
+ /** `--take-branch`: `branch` is checked out in `checkout`, which is detached first. */
422
+ take?: boolean;
423
+ /** Set for an Umbrella Repository's child: the umbrella, whose mirrored worktree holds `target`. */
424
+ umbrella?: string;
328
425
  }
329
426
 
330
427
  /** A resolved Workset: its id and the repositories that get a worktree. */
@@ -362,25 +459,100 @@ async function changeTarget(companionPath: string, change: string): Promise<Targ
362
459
  return { id: resolution.id, repositories };
363
460
  }
364
461
 
462
+ type ProtectedPatterns = readonly string[];
463
+
464
+ type PlanOptions = Pick<CreateWorktreesOptions, "ticket" | "takeBranch"> & {
465
+ /** The companion's protected patterns, read once for every repository's take. */
466
+ protectedPatterns?: ProtectedPatterns;
467
+ };
468
+
365
469
  /** Phase 1: every check for every repository; any failure means nothing is created. */
366
470
  async function planWorktrees(
367
471
  companionPath: string,
368
472
  target: Target,
369
473
  git: GitRunner,
370
474
  cwd: string,
371
- ticket?: string,
372
- ): Promise<{ plans: Plan[]; diagnostics: string[]; warnings: string[] }> {
475
+ options: Pick<CreateWorktreesOptions, "ticket" | "takeBranch">,
476
+ ): Promise<{ plans: Plan[]; mirror?: Mirror; diagnostics: string[]; warnings: string[] }> {
373
477
  const warnings: string[] = [];
478
+ const index = await linkedIndex(companionPath, git, cwd);
479
+ const planOptions: PlanOptions = options.takeBranch
480
+ ? {
481
+ ...options,
482
+ protectedPatterns: configuredProtectedPatterns(
483
+ (await readCompanionConfig(companionPath)).capabilities ?? [],
484
+ ),
485
+ }
486
+ : options;
374
487
  const checked = await Promise.all(
375
488
  target.repositories.map((repository) =>
376
- planRepository(companionPath, target.id, repository, git, cwd, warnings, ticket),
489
+ planRepository(companionPath, target.id, repository, git, index, warnings, planOptions),
377
490
  ),
378
491
  );
379
- return {
380
- plans: checked.filter((entry): entry is Plan => !Array.isArray(entry)),
381
- diagnostics: checked.flatMap((entry) => (Array.isArray(entry) ? entry : [])),
382
- warnings,
383
- };
492
+ const plans = checked.filter((entry): entry is Plan => !Array.isArray(entry));
493
+ const diagnostics = checked.flatMap((entry) => (Array.isArray(entry) ? entry : []));
494
+ const mirror = await planMirror(companionPath, target.id, plans);
495
+ if (Array.isArray(mirror)) return { plans, diagnostics: [...diagnostics, ...mirror], warnings };
496
+ return { plans, ...(mirror ? { mirror } : {}), diagnostics, warnings };
497
+ }
498
+
499
+ /** The mirrored worktree a Workset's umbrella children get. */
500
+ interface Mirror {
501
+ umbrella: string;
502
+ /** The umbrella's Repository Link id, which the folder's link repeats. */
503
+ repositoryId: string;
504
+ folder: string;
505
+ /** The folder already is this umbrella's mirrored worktree. */
506
+ reuse: boolean;
507
+ }
508
+
509
+ /**
510
+ * The mirrored worktree of the plans' Umbrella Repository, or the diagnostics that stop
511
+ * the run: the folder must be this umbrella's mirrored worktree, or hold nothing but OS
512
+ * metadata, Mate's material, and its children's reused worktrees, as a run interrupted
513
+ * before linking leaves it.
514
+ */
515
+ async function planMirror(
516
+ companionPath: string,
517
+ worksetId: string,
518
+ plans: readonly Plan[],
519
+ ): Promise<Mirror | string[] | undefined> {
520
+ const children = plans.filter((plan) => plan.umbrella);
521
+ const umbrellas = [...new Set(children.map((plan) => plan.umbrella!))];
522
+ if (umbrellas.length === 0) return undefined;
523
+ if (umbrellas.length > 1) {
524
+ return [
525
+ `the Workset spans the Umbrella Repositories ${umbrellas.join(", ")}; a mirrored worktree serves one`,
526
+ ];
527
+ }
528
+ const umbrella = umbrellas[0]!;
529
+ const repositoryId = children[0]!.repositoryId;
530
+ const folder = await canonical(worktreePathFor(umbrella, worksetId));
531
+ if (await isMirrorOf(folder, companionPath, repositoryId)) {
532
+ return { umbrella, repositoryId, folder, reuse: true };
533
+ }
534
+ // A link of its own names another companion or id: someone else's folder.
535
+ if (await exists(repoLocalRegistryPath(folder))) {
536
+ return [`${folder} exists and is not the mirrored worktree of ${umbrella}`];
537
+ }
538
+ const listed = await fs.readdir(folder).catch(() => []);
539
+ const material = mirrorMaterial();
540
+ const reused = new Set(
541
+ children.filter((plan) => plan.reuse).map((plan) => path.basename(plan.target)),
542
+ );
543
+ const foreign = listed.filter((name) => !material.has(name) && !reused.has(name));
544
+ if (foreign.length === 0) return { umbrella, repositoryId, folder, reuse: false };
545
+ return [`${folder} exists and is not the mirrored worktree of ${umbrella}`];
546
+ }
547
+
548
+ /** `folder` carries its own repo-local link to the companion under the umbrella's id. */
549
+ async function isMirrorOf(
550
+ folder: string,
551
+ companionPath: string,
552
+ repositoryId: string,
553
+ ): Promise<boolean> {
554
+ const link = await findRepoLocalLinkTo(folder, companionPath);
555
+ return link !== null && link.id === repositoryId && (await canonical(link.path)) === folder;
384
556
  }
385
557
 
386
558
  /** One repository's plan, or the diagnostics that stop the run. */
@@ -389,11 +561,11 @@ async function planRepository(
389
561
  worksetId: string,
390
562
  repository: string,
391
563
  git: GitRunner,
392
- cwd: string,
564
+ index: LinkedIndex,
393
565
  warnings: string[],
394
- ticket?: string,
566
+ { ticket, takeBranch, protectedPatterns }: PlanOptions,
395
567
  ): Promise<Plan | string[]> {
396
- const { linked, missing } = await linkedCheckout(companionPath, repository, git, cwd);
568
+ const { linked, missing } = linkedCheckout(index, repository);
397
569
  if (!linked) {
398
570
  // An identity problem outranks the missing link.
399
571
  const identity = await resolveWorksetBranch(companionPath, worksetId, repository);
@@ -410,23 +582,24 @@ async function planRepository(
410
582
  `${repository}: fetching origin failed, using local refs: ${fetched.stderr.trim()}`,
411
583
  );
412
584
  }
413
- const hasRef = async (ref: string) =>
414
- (await git(linked.path, ["rev-parse", "--verify", "--quiet", ref])).code === 0;
415
- const resolution = await resolveDeliveryBranch({
416
- companionPath,
417
- repository,
418
- hasRef,
419
- listRefs: listRefsWith(async (args) => {
420
- const listed = await git(linked.path, args);
421
- return listed.code === 0 ? listed.stdout : null;
585
+ // Every probe runs through the same runner; it already adds the promptless environment.
586
+ const checkout = deliveryCheckout(linked.path, (args, { input, timeoutMs }) =>
587
+ git(linked.path, [...args], {
588
+ env: { GIT_NO_LAZY_FETCH: "1" },
589
+ ...(input !== undefined ? { input } : {}),
590
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
422
591
  }),
423
- mergeProbe: mergeProbeWith(
424
- mergeGit(linked.path),
425
- await workingRepoGit(linked.path).defaultBranch(),
426
- ),
427
- worksetId,
428
- ...(ticket ? { ticket } : {}),
429
- });
592
+ );
593
+ const resolution = await resolveDeliveryBranch(
594
+ checkout,
595
+ { companionPath, repository, worksetId },
596
+ ticket ? { ticket } : {},
597
+ );
598
+ // Concerns the companion, not a repository: reported once, first.
599
+ const { templateDiagnostic } = resolution;
600
+ if (templateDiagnostic && !warnings.includes(templateDiagnostic)) {
601
+ warnings.unshift(templateDiagnostic);
602
+ }
430
603
  const { branch, source } = resolution;
431
604
  if (branch === null || source === null) {
432
605
  return resolution.diagnostics.map((line) => `${repository}: ${line}`);
@@ -436,7 +609,11 @@ async function planRepository(
436
609
  const entries = await listWorktrees(git, linked.path);
437
610
  const main = entries?.[0];
438
611
  if (!main) return [`${repository}: cannot list the worktrees of ${linked.path}`];
439
- const target = await canonical(worktreePathFor(main.path, worksetId));
612
+ const target = await canonical(
613
+ linked.umbrella
614
+ ? path.join(worktreePathFor(linked.umbrella, worksetId), path.basename(linked.path))
615
+ : worktreePathFor(main.path, worksetId),
616
+ );
440
617
  const atTarget = entries.find((entry) => entry.path === target);
441
618
  // A stale entry is never reused: wrapping it would only refill a folder without a checkout.
442
619
  const stale = entries.find(
@@ -447,11 +624,20 @@ async function planRepository(
447
624
  `${repository}: ${stale.path} is a stale worktree entry (${stale.stale}); remove any folder left there, run \`git worktree prune\` in ${main.path}, then retry`,
448
625
  ];
449
626
  }
450
- const plan = { repository, repositoryId: linked.id, checkout: main.path, branch, source };
627
+ const plan = {
628
+ repository,
629
+ repositoryId: linked.id,
630
+ checkout: main.path,
631
+ branch,
632
+ source,
633
+ ...(linked.umbrella ? { umbrella: linked.umbrella } : {}),
634
+ };
451
635
  const elsewhere = entries.find((entry) => entry.branch === branch && entry.path !== target);
452
636
  const inherited = resolution.inheritedFrom.join(", ");
637
+ const take = Boolean(takeBranch && elsewhere?.path === main.path);
453
638
  // An inherited branch is the dependency's worktree; one branch has one worktree.
454
- if (elsewhere && inherited && !atTarget) {
639
+ // In the main checkout, only `--take-branch` moves it out.
640
+ if (elsewhere && inherited && !atTarget && !take) {
455
641
  if (elsewhere.path === main.path) {
456
642
  return [
457
643
  `${repository}: ${branch}, inherited from ${inherited}, is checked out in ${main.path}; work there or switch it to another branch`,
@@ -466,20 +652,97 @@ async function planRepository(
466
652
  if (!reuse && (atTarget || (await exists(target)))) {
467
653
  return [`${repository}: ${target} exists and is not a worktree of ${repository} on ${branch}`];
468
654
  }
655
+ if (take) {
656
+ const refusal = await takeRefusal(git, main.path, branch, checkout, protectedPatterns ?? []);
657
+ if (refusal) return [`${repository}: ${refusal}`];
658
+ return { ...plan, target, reuse: false, take: true };
659
+ }
469
660
  if (elsewhere) return [`${repository}: ${branch} is already checked out at ${elsewhere.path}`];
470
661
  return {
471
662
  ...plan,
472
663
  target,
473
- base: source === "new" ? await newBranchBase(hasRef) : undefined,
664
+ base: source === "new" ? await newBranchBase(checkout.hasRef) : undefined,
474
665
  reuse,
475
666
  };
476
667
  }
477
668
 
669
+ /** Why `--take-branch` leaves `branch` in the main checkout `main`, or null to take it. */
670
+ async function takeRefusal(
671
+ git: GitRunner,
672
+ main: string,
673
+ branch: string,
674
+ checkout: { defaultBranch(): Promise<string> },
675
+ patterns: ProtectedPatterns,
676
+ ): Promise<string | null> {
677
+ const protection = classifyBranch(branch, {
678
+ defaultBranch: await checkout.defaultBranch(),
679
+ patterns,
680
+ });
681
+ if (protection.protected) {
682
+ return `--take-branch does not take the protected branch ${branch} out of ${main}`;
683
+ }
684
+ return trackedChangesRefusal(git, main);
685
+ }
686
+
687
+ /** Why `main`'s tracked changes block a take, or null when it has none. */
688
+ async function trackedChangesRefusal(git: GitRunner, main: string): Promise<string | null> {
689
+ const status = await git(main, ["status", "--porcelain", "-z", "--untracked-files=no"]);
690
+ if (status.code !== 0) return `cannot read the status of ${main}: ${status.stderr.trim()}`;
691
+ // `XY path\0`; a rename or copy, in either column, adds its source as the next field,
692
+ // which is skipped.
693
+ const fields = status.stdout.split("\0");
694
+ const changed: string[] = [];
695
+ for (let at = 0; at < fields.length; at++) {
696
+ const field = fields[at]!;
697
+ if (field.length <= 3) continue;
698
+ changed.push(field.slice(3));
699
+ if (/[RC]/.test(field.slice(0, 2))) at++;
700
+ }
701
+ if (changed.length > 0) {
702
+ return `${main} has uncommitted changes to tracked files (${changed.join(", ")}); commit or stash them, then retry --take-branch`;
703
+ }
704
+ return null;
705
+ }
706
+
478
707
  async function addWorktree(git: GitRunner, plan: Plan): Promise<string | null> {
479
708
  const result = await git(plan.checkout, worktreeAddArgs(plan, plan.target, plan.base));
480
709
  return result.code === 0 ? null : `creating the worktree failed: ${result.stderr.trim()}`;
481
710
  }
482
711
 
712
+ /**
713
+ * `--take-branch`: detach the main checkout, add the worktree, and undo both on failure.
714
+ * Earlier repositories' takes stay: their worktrees are made, as for any later failure.
715
+ */
716
+ async function takeIntoWorktree(
717
+ git: GitRunner,
718
+ plan: Plan,
719
+ warnings: string[],
720
+ ): Promise<string | null> {
721
+ // Checked again: earlier repositories' setup may have given the developer time to edit.
722
+ const changed = await trackedChangesRefusal(git, plan.checkout);
723
+ if (changed) return changed;
724
+ const detached = await git(plan.checkout, ["switch", "--detach"]);
725
+ if (detached.code !== 0) return `detaching ${plan.checkout} failed: ${detached.stderr.trim()}`;
726
+ const failure = await addWorktree(git, plan);
727
+ if (!failure) {
728
+ warnings.push(
729
+ `${plan.repository}: ${plan.checkout} is now on a detached HEAD; ${plan.branch} moved to ${plan.target}`,
730
+ );
731
+ return null;
732
+ }
733
+ // Back to the state before the command, so a failed take changes nothing visible. A
734
+ // worktree registered before the add failed still holds the branch; the planned target
735
+ // did not exist, so removing it drops only what the add left. A failed remove matters
736
+ // only when the switch back fails too: an add that registered nothing leaves nothing.
737
+ const removed = await git(plan.checkout, ["worktree", "remove", "--force", plan.target]);
738
+ await git(plan.checkout, ["worktree", "prune"]);
739
+ const restored = await git(plan.checkout, ["switch", plan.branch]);
740
+ if (restored.code === 0) return failure;
741
+ const kept =
742
+ removed.code === 0 ? "" : `; removing ${plan.target} failed: ${removed.stderr.trim()}`;
743
+ return `${failure}${kept}; switching ${plan.checkout} back to ${plan.branch} failed: ${restored.stderr.trim()}`;
744
+ }
745
+
483
746
  /** The runtimes `checkout` is wrapped for, in wrap order. */
484
747
  async function wrappedRuntimes(checkout: string, deps: WorktreeDeps): Promise<WrapRuntime[]> {
485
748
  const state = await (deps.readWrapState ?? readWrapState)(checkout);
@@ -556,10 +819,18 @@ async function missingEnvFiles(
556
819
 
557
820
  export interface CreateWorktreesOptions {
558
821
  install: boolean;
559
- /** Names a new Delivery Branch `workset/<TICKET>-<id>`; an existing or recorded one wins. */
822
+ /**
823
+ * Names a new Delivery Branch by the template (default `workset/<TICKET>-<id>`); an existing
824
+ * or recorded one wins.
825
+ */
560
826
  ticket?: string;
561
827
  /** Pass the installer's output through; false discards it, as `--json` needs. */
562
828
  streamInstall: boolean;
829
+ /**
830
+ * Take a resolved, unprotected branch, inherited ones included, out of a main checkout
831
+ * without tracked changes: detach that checkout, then add the worktree on the branch.
832
+ */
833
+ takeBranch?: boolean;
563
834
  }
564
835
 
565
836
  /**
@@ -605,12 +876,12 @@ async function createTargetWorktrees(
605
876
  const worksetId = target.id;
606
877
  const git = deps.git ?? runGit;
607
878
  const cwd = (deps.cwd ?? process.cwd)();
608
- const { plans, diagnostics, warnings } = await planWorktrees(
879
+ const { plans, mirror, diagnostics, warnings } = await planWorktrees(
609
880
  companionPath,
610
881
  target,
611
882
  git,
612
883
  cwd,
613
- options.ticket,
884
+ options,
614
885
  );
615
886
  if (diagnostics.length > 0) {
616
887
  return { workset: worksetId, ok: false, repositories: [], diagnostics, warnings };
@@ -634,21 +905,118 @@ async function createTargetWorktrees(
634
905
  }),
635
906
  );
636
907
  }
908
+ // After its children exist, so the folder is linked only once it holds a worktree.
909
+ const held = plans.flatMap((plan, at) =>
910
+ plan.umbrella && repositories[at]!.install.reason !== NOT_CREATED ? [plan.repository] : [],
911
+ );
912
+ const umbrella =
913
+ mirror && held.length > 0
914
+ ? await realizeMirror(companionPath, mirror, held, deps, warnings)
915
+ : undefined;
916
+ // An unlinked mirror is reported broken; it gets no index. It holds the children's
917
+ // worktrees, so it is indexed after theirs rather than over them.
918
+ if (umbrella && mirror && !umbrella.error) {
919
+ const children = Promise.all(indexing);
920
+ indexing.push(
921
+ children
922
+ .then(() =>
923
+ indexWorktree(
924
+ mirror.umbrella,
925
+ mirror.folder,
926
+ companionPath,
927
+ deps.tokensave,
928
+ (action) => progress?.(`${mirror.umbrella}: tokensave ${action} of ${mirror.folder}…`),
929
+ UMBRELLA_NOT_INDEXED,
930
+ ),
931
+ )
932
+ .then((index) => {
933
+ umbrella.index = index;
934
+ }),
935
+ );
936
+ }
637
937
  await Promise.all(indexing);
638
938
  for (const result of repositories) {
639
939
  if (result.index.outcome === "failed") {
640
940
  warnings.push(`${result.repository}: tokensave index step failed: ${result.index.reason}`);
641
941
  }
642
942
  }
943
+ if (umbrella?.index.outcome === "failed") {
944
+ warnings.push(`${umbrella.path}: tokensave index step failed: ${umbrella.index.reason}`);
945
+ }
643
946
  return {
644
947
  workset: worksetId,
645
- ok: repositories.every((entry) => !entry.error),
948
+ ok: repositories.every((entry) => !entry.error) && !umbrella?.error,
646
949
  repositories,
950
+ ...(umbrella ? { umbrella } : {}),
647
951
  diagnostics,
648
952
  warnings,
649
953
  };
650
954
  }
651
955
 
956
+ /**
957
+ * Links the mirrored worktree folder under the umbrella's id, without the companion
958
+ * registry, and wraps it for the umbrella's runtimes. Its children get neither: the
959
+ * folder's projection serves them, as the umbrella's serves its own.
960
+ */
961
+ async function realizeMirror(
962
+ companionPath: string,
963
+ mirror: Mirror,
964
+ repositories: string[],
965
+ deps: WorktreeDeps,
966
+ warnings: string[],
967
+ ): Promise<UmbrellaWorktreeResult> {
968
+ const { wrap, error, warning } = await linkAndWrap(
969
+ companionPath,
970
+ { id: mirror.repositoryId, path: mirror.folder },
971
+ mirror.umbrella,
972
+ mirror.reuse,
973
+ deps,
974
+ );
975
+ if (warning) warnings.push(`${mirror.folder}: ${warning}`);
976
+ return {
977
+ path: mirror.umbrella,
978
+ worktree: mirror.folder,
979
+ action: mirror.reuse ? "reused" : "created",
980
+ repositories,
981
+ wrap,
982
+ index: { outcome: "skipped", ...(error ? { reason: "mirrored worktree broken" } : {}) },
983
+ ...(error ? { error } : {}),
984
+ };
985
+ }
986
+
987
+ /**
988
+ * Links `repository.path` to the companion and wraps it like `wrappedFrom`. A reused
989
+ * folder still wrapped from before stays usable, so a failed refresh only warns.
990
+ */
991
+ async function linkAndWrap(
992
+ companionPath: string,
993
+ repository: LinkedRepository,
994
+ wrappedFrom: string,
995
+ reuse: boolean,
996
+ deps: WorktreeDeps,
997
+ ): Promise<{ wrap: WrapOutcome; error?: string; warning?: string }> {
998
+ try {
999
+ await (deps.writeLink ?? writeRepoLocalRegistryEntry)(
1000
+ repository.path,
1001
+ companionPath,
1002
+ repository,
1003
+ "existing",
1004
+ );
1005
+ } catch (error) {
1006
+ return {
1007
+ wrap: { runtimes: [], outcome: "skipped", reason: "worktree not linked" },
1008
+ error: `linking the worktree failed: ${errorMessage(error)}`,
1009
+ };
1010
+ }
1011
+ const wrap = await wrapWorktree(companionPath, wrappedFrom, repository, deps);
1012
+ if (wrap.outcome !== "failed") return { wrap };
1013
+ const message = `wrapping the worktree failed: ${wrap.reason}`;
1014
+ if (reuse && (await stillWrapped(repository.path, wrap.runtimes, deps))) {
1015
+ return { wrap, warning: `${message}; its earlier wrap stays` };
1016
+ }
1017
+ return { wrap, error: message };
1018
+ }
1019
+
652
1020
  async function realize(
653
1021
  companionPath: string,
654
1022
  plan: Plan,
@@ -666,10 +1034,13 @@ async function realize(
666
1034
  install: { command: null, outcome: "skipped" },
667
1035
  wrap: { runtimes: [], outcome: "skipped" },
668
1036
  index: { outcome: "skipped" },
1037
+ include: { sources: [], copied: [], failed: [] },
669
1038
  missingEnv: [],
670
1039
  };
671
1040
  if (!plan.reuse) {
672
- const failure = await addWorktree(git, plan);
1041
+ const failure = plan.take
1042
+ ? await takeIntoWorktree(git, plan, warnings)
1043
+ : await addWorktree(git, plan);
673
1044
  if (failure) {
674
1045
  return {
675
1046
  ...result,
@@ -680,28 +1051,27 @@ async function realize(
680
1051
  };
681
1052
  }
682
1053
  }
683
- // The main checkout's id: a session moved here keeps its `MATE_REPOSITORY_ID`.
684
- const repository = { id: plan.repositoryId, path: plan.target };
685
- try {
686
- await (deps.writeLink ?? writeRepoLocalRegistryEntry)(
687
- plan.target,
1054
+ if (plan.umbrella) {
1055
+ result.wrap.reason = "served by the mirrored worktree";
1056
+ } else {
1057
+ // The main checkout's id: a session moved here keeps its `MATE_REPOSITORY_ID`.
1058
+ const linked = await linkAndWrap(
688
1059
  companionPath,
689
- repository,
690
- "existing",
1060
+ { id: plan.repositoryId, path: plan.target },
1061
+ plan.checkout,
1062
+ plan.reuse,
1063
+ deps,
691
1064
  );
692
- result.wrap = await wrapWorktree(companionPath, plan.checkout, repository, deps);
693
- if (result.wrap.outcome === "failed") {
694
- const message = `wrapping the worktree failed: ${result.wrap.reason}`;
695
- // A reused worktree still wrapped from before stays usable; only refreshing it failed.
696
- if (plan.reuse && (await stillWrapped(plan.target, result.wrap.runtimes, deps))) {
697
- warnings.push(`${plan.repository}: ${message}; its earlier wrap stays`);
698
- } else {
699
- result.error = message;
700
- }
701
- }
702
- } catch (error) {
703
- result.error = `linking the worktree failed: ${errorMessage(error)}`;
704
- result.wrap.reason = "worktree not linked";
1065
+ result.wrap = linked.wrap;
1066
+ if (linked.error) result.error = linked.error;
1067
+ if (linked.warning) warnings.push(`${plan.repository}: ${linked.warning}`);
1068
+ }
1069
+ // Before install: a copied `.npmrc` may be what lets it reach a private registry.
1070
+ const selection = await selectIncludedFiles(git, plan.checkout);
1071
+ for (const warning of selection.warnings) warnings.push(`${plan.repository}: ${warning}`);
1072
+ result.include = await copyIncludedFiles(plan.checkout, plan.target, selection);
1073
+ if (result.include.failed.length > 0) {
1074
+ result.error ??= `copying ${result.include.failed.map((entry) => entry.path).join(", ")} failed`;
705
1075
  }
706
1076
  const command = await installCommand(plan.target);
707
1077
  result.install.command = command ? command.join(" ") : null;
@@ -785,27 +1155,24 @@ async function recordedBranches(
785
1155
  return byRepository;
786
1156
  }
787
1157
 
1158
+ /** Returns the Umbrella Repository whose child the repository is, so its mirror is pruned after. */
788
1159
  async function pruneRepository(
789
1160
  companionPath: string,
790
1161
  worksetId: string,
791
1162
  repository: string,
792
1163
  branches: ReadonlySet<string>,
1164
+ index: LinkedIndex,
793
1165
  git: GitRunner,
794
1166
  deps: WorktreeDeps,
795
1167
  result: PruneResult,
796
- ): Promise<void> {
797
- const { linked } = await linkedCheckout(
798
- companionPath,
799
- repository,
800
- git,
801
- (deps.cwd ?? process.cwd)(),
802
- );
803
- if (!linked) return;
1168
+ ): Promise<LinkedCheckout | undefined> {
1169
+ const { linked } = linkedCheckout(index, repository);
1170
+ if (!linked) return undefined;
804
1171
  const entries = await listWorktrees(git, linked.path);
805
1172
  const main = entries?.[0];
806
1173
  if (!main) {
807
1174
  result.warnings.push(`${repository}: cannot list the worktrees of ${linked.path}`);
808
- return;
1175
+ return linked.umbrella ? linked : undefined;
809
1176
  }
810
1177
  // The first entry is the main checkout; a detached HEAD has no branch and never matches.
811
1178
  const candidates = entries
@@ -821,6 +1188,7 @@ async function pruneRepository(
821
1188
  result,
822
1189
  );
823
1190
  }
1191
+ return linked.umbrella ? linked : undefined;
824
1192
  }
825
1193
 
826
1194
  interface PruneCandidate {
@@ -828,7 +1196,7 @@ interface PruneCandidate {
828
1196
  repository: string;
829
1197
  /** The main checkout's path. */
830
1198
  main: string;
831
- linked: LinkedRepository;
1199
+ linked: LinkedCheckout;
832
1200
  listed: WorktreeEntry;
833
1201
  }
834
1202
 
@@ -848,12 +1216,18 @@ async function pruneWorktree(
848
1216
  result.kept.push({ ...entry, reason });
849
1217
  return;
850
1218
  }
851
- // Unwrap first: machine-local state keyed by its path (Claude local-scope MCP) must not outlive it.
852
- try {
853
- await (deps.unwrap ?? cleanupWorkingRepository)(target, [companionPath]);
854
- } catch (error) {
855
- result.kept.push({ ...entry, reason: `removing its wrap failed: ${errorMessage(error)}` });
856
- return;
1219
+ // A worktree in the mirrored folder carries no wrap; the folder is unwrapped after.
1220
+ const inMirror =
1221
+ linked.umbrella !== undefined &&
1222
+ path.dirname(target) === (await canonical(worktreePathFor(linked.umbrella, worksetId)));
1223
+ if (!inMirror) {
1224
+ // Unwrap first: machine-local state keyed by its path (Claude local-scope MCP) must not outlive it.
1225
+ try {
1226
+ await (deps.unwrap ?? cleanupWorkingRepository)(target, [companionPath]);
1227
+ } catch (error) {
1228
+ result.kept.push({ ...entry, reason: `removing its wrap failed: ${errorMessage(error)}` });
1229
+ return;
1230
+ }
857
1231
  }
858
1232
  const removed = await git(main, ["worktree", "remove", target]);
859
1233
  if (removed.code === 0) {
@@ -861,6 +1235,18 @@ async function pruneWorktree(
861
1235
  return;
862
1236
  }
863
1237
  const refused = removed.stderr.trim() || "git refused";
1238
+ if (inMirror) {
1239
+ result.kept.push({ ...entry, reason: refused });
1240
+ return;
1241
+ }
1242
+ // The umbrella's id is no link for a child's own worktree, so Mate cannot re-wrap it.
1243
+ if (linked.umbrella) {
1244
+ result.kept.push({
1245
+ ...entry,
1246
+ reason: `${refused}; its wrap was removed, run \`${FRAMEWORK_NAME} wrap\` there`,
1247
+ });
1248
+ return;
1249
+ }
864
1250
  // Kept, so it gets its guardrails back.
865
1251
  const rewrap = await wrapWorktree(companionPath, main, { id: linked.id, path: target }, deps);
866
1252
  result.kept.push({
@@ -886,13 +1272,117 @@ export async function pruneWorksetWorktrees(
886
1272
  ): Promise<PruneResult> {
887
1273
  const git = deps.git ?? runGit;
888
1274
  const result: PruneResult = { removed: [], kept: [], warnings: [] };
1275
+ let index: LinkedIndex | undefined;
889
1276
  for (const workset of done) {
890
1277
  // oxlint-disable-next-line no-await-in-loop -- Worksets one at a time
891
1278
  const branches = await recordedBranches(companionPath, workset.changes, result.warnings);
1279
+ if (branches.size === 0) continue;
1280
+ // oxlint-disable-next-line no-await-in-loop -- read once, on first need
1281
+ index ??= await linkedIndex(companionPath, git, (deps.cwd ?? process.cwd)());
1282
+ // Umbrella path to its Repository Link id.
1283
+ const umbrellas = new Map<string, string>();
892
1284
  for (const [repository, names] of branches) {
893
1285
  // oxlint-disable-next-line no-await-in-loop -- Git operations on shared checkouts, one at a time
894
- await pruneRepository(companionPath, workset.id, repository, names, git, deps, result);
1286
+ const child = await pruneRepository(
1287
+ companionPath,
1288
+ workset.id,
1289
+ repository,
1290
+ names,
1291
+ index,
1292
+ git,
1293
+ deps,
1294
+ result,
1295
+ );
1296
+ if (child?.umbrella) umbrellas.set(child.umbrella, child.id);
1297
+ }
1298
+ for (const [umbrella, repositoryId] of umbrellas) {
1299
+ // oxlint-disable-next-line no-await-in-loop -- after its children, one at a time
1300
+ await pruneMirror(
1301
+ companionPath,
1302
+ { worksetId: workset.id, umbrella, repositoryId },
1303
+ deps,
1304
+ result,
1305
+ );
895
1306
  }
896
1307
  }
897
1308
  return result;
898
1309
  }
1310
+
1311
+ /** Files the OS writes into any folder it shows, e.g. Finder's; never anyone's work. */
1312
+ const OS_METADATA = new Set([".DS_Store", "Thumbs.db", "desktop.ini"]);
1313
+
1314
+ /**
1315
+ * Top-level names a wrap, a link, or the OS may write; everything else in a mirrored
1316
+ * worktree is someone's work.
1317
+ */
1318
+ function mirrorMaterial(): Set<string> {
1319
+ return new Set([
1320
+ ...projectionEntries()
1321
+ .map((entry) => entry.path.split(/[\\/]/)[0]!)
1322
+ .filter((name) => name !== ".git" && name !== "~"),
1323
+ ...OS_METADATA,
1324
+ ]);
1325
+ }
1326
+
1327
+ /**
1328
+ * Best effort: unwraps and removes the Workset's mirrored worktree, then an empty
1329
+ * `<umbrella>.worktrees`, only when nothing but Mate's material is left. Never recursive,
1330
+ * never forced; a folder that stays is named with the reason.
1331
+ */
1332
+ async function pruneMirror(
1333
+ companionPath: string,
1334
+ mirror: { worksetId: string; umbrella: string; repositoryId: string },
1335
+ deps: WorktreeDeps,
1336
+ result: PruneResult,
1337
+ ): Promise<void> {
1338
+ const { worksetId, umbrella, repositoryId } = mirror;
1339
+ const folder = await canonical(worktreePathFor(umbrella, worksetId));
1340
+ // Only this companion's mirrored worktree, never a folder it does not own.
1341
+ if (!(await isMirrorOf(folder, companionPath, repositoryId))) return;
1342
+ const umbrellas = (result.umbrellas ??= { removed: [], kept: [] });
1343
+ const entry = { workset: worksetId, umbrella, path: folder };
1344
+ const keep = (reason: string): void => void umbrellas.kept.push({ ...entry, reason });
1345
+ if (await holds(folder, (deps.cwd ?? process.cwd)())) return keep("in use (current directory)");
1346
+ const material = mirrorMaterial();
1347
+ const listed = await fs.readdir(folder).catch(() => null);
1348
+ if (listed === null) return keep("cannot list its entries");
1349
+ const others = listed.filter((name) => !material.has(name)).toSorted();
1350
+ if (others.length > 0) return keep(`still holds ${others.join(", ")}`);
1351
+ try {
1352
+ await (deps.unwrap ?? cleanupWorkingRepository)(folder, [companionPath]);
1353
+ } catch (error) {
1354
+ return keep(`removing its wrap failed: ${errorMessage(error)}`);
1355
+ }
1356
+ // A failure shows below as what unwrapping left.
1357
+ await Promise.all(
1358
+ listed
1359
+ .filter((name) => OS_METADATA.has(name))
1360
+ .map((name) => fs.rm(path.join(folder, name), { force: true }).catch(() => undefined)),
1361
+ );
1362
+ try {
1363
+ await fs.rmdir(folder);
1364
+ } catch (error) {
1365
+ const left = await fs.readdir(folder).catch(() => []);
1366
+ const refused =
1367
+ left.length > 0
1368
+ ? `unwrapping left ${left.toSorted().join(", ")}`
1369
+ : `removing it failed: ${errorMessage(error)}`;
1370
+ // Kept, so it gets its link and guardrails back, and a later prune finds it again.
1371
+ const restored = await linkAndWrap(
1372
+ companionPath,
1373
+ { id: repositoryId, path: folder },
1374
+ umbrella,
1375
+ false,
1376
+ deps,
1377
+ );
1378
+ const failure = restored.error ?? restored.warning;
1379
+ return keep(
1380
+ failure
1381
+ ? `${refused}; restoring it failed, run \`${FRAMEWORK_NAME} wrap\` there: ${failure}`
1382
+ : refused,
1383
+ );
1384
+ }
1385
+ umbrellas.removed.push(entry);
1386
+ // The parent stays while another Workset's mirror is in it.
1387
+ await fs.rmdir(path.dirname(folder)).catch(() => undefined);
1388
+ }