@uniqbit/mate-core 1.0.0-canary.0 → 1.0.0-canary.2

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 (325) hide show
  1. package/claude-capability-plugins/companion-mentions/.claude-plugin/marketplace.json +14 -0
  2. package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +8 -0
  3. package/claude-capability-plugins/companion-mentions/hooks/companion.ts +457 -0
  4. package/claude-capability-plugins/companion-mentions/hooks/hooks.json +1 -0
  5. package/claude-capability-plugins/companion-mentions/hooks/register.ts +403 -0
  6. package/claude-plugin/hooks/hooks.json +10 -1
  7. package/claude-plugin/hooks/tokensave-route.mjs +52 -0
  8. package/opencode-plugin/src/server.ts +4 -0
  9. package/opencode-plugin/src/tui.tsx +2 -0
  10. package/opencode-plugin/tui.tsx +2 -0
  11. package/package.json +45 -16
  12. package/src/brand/terminal.ts +5 -0
  13. package/src/cli/commands/artifact/apply-context.ts +275 -0
  14. package/src/cli/commands/artifact/artifact.ts +4 -0
  15. package/src/cli/commands/artifact/delivery/archive.ts +13 -5
  16. package/src/cli/commands/artifact/delivery/environment.ts +36 -13
  17. package/src/cli/commands/artifact/delivery/link.ts +35 -15
  18. package/src/cli/commands/artifact/delivery/output.ts +31 -0
  19. package/src/cli/commands/artifact/finish/command.ts +50 -5
  20. package/src/cli/commands/artifact/finish/engine.ts +44 -11
  21. package/src/cli/commands/artifact/finish/git.ts +132 -19
  22. package/src/cli/commands/artifact/finish/openspec.ts +6 -1
  23. package/src/cli/commands/artifact/finish/worktree-cleanup.ts +92 -0
  24. package/src/cli/commands/cap/index-cmd.ts +64 -15
  25. package/src/cli/commands/cap/tokensave.ts +7 -5
  26. package/src/cli/commands/companion/link.ts +14 -1
  27. package/src/cli/commands/companion/open.ts +16 -11
  28. package/src/cli/commands/companion/sync.ts +10 -0
  29. package/src/cli/commands/companion/tui.ts +17 -7
  30. package/src/cli/commands/companion/update.ts +74 -12
  31. package/src/cli/commands/doctor.ts +20 -5
  32. package/src/cli/commands/factory/factory.ts +301 -0
  33. package/src/cli/commands/install.ts +133 -9
  34. package/src/cli/commands/launch/shared.ts +16 -11
  35. package/src/cli/commands/report/index.ts +20 -1
  36. package/src/cli/commands/session/context.ts +102 -0
  37. package/src/cli/commands/setup.ts +44 -10
  38. package/src/cli/commands/studio/factory-credential.ts +49 -0
  39. package/src/cli/commands/studio/index.ts +29 -2
  40. package/src/cli/commands/studio/payload.ts +249 -15
  41. package/src/cli/commands/studio/routes.ts +41 -8
  42. package/src/cli/commands/studio/selection.ts +142 -16
  43. package/src/cli/commands/studio/server.ts +403 -364
  44. package/src/cli/commands/studio/services.ts +60 -0
  45. package/src/cli/commands/studio/studio-app.ts +67 -0
  46. package/src/cli/commands/studio/terminal-assets.ts +21 -33
  47. package/src/cli/commands/studio/terminal.ts +85 -15
  48. package/src/cli/commands/studio/views/model.ts +18 -0
  49. package/src/cli/commands/studio/views/vault/markdown-tree.ts +267 -0
  50. package/src/cli/commands/studio/views/vault/view.ts +185 -0
  51. package/src/cli/commands/studio/workset-session.ts +131 -0
  52. package/src/cli/commands/unwrap.ts +8 -0
  53. package/src/cli/commands/update.ts +27 -1
  54. package/src/cli/commands/working/cleanup.ts +10 -1
  55. package/src/cli/commands/working/link.ts +76 -0
  56. package/src/cli/commands/working/working.ts +10 -0
  57. package/src/cli/commands/working/worktree.ts +356 -0
  58. package/src/cli/companion-link-wizard.tsx +2 -0
  59. package/src/cli/companion-selector.tsx +2 -0
  60. package/src/cli/confirm.ts +2 -0
  61. package/src/cli/install-plan.tsx +127 -160
  62. package/src/cli/launch-selector.tsx +2 -0
  63. package/src/cli/main.ts +18 -0
  64. package/src/cli/parse-flags.ts +9 -1
  65. package/src/cli/repo-list-table.tsx +2 -0
  66. package/src/cli/setup-selector.tsx +79 -20
  67. package/src/cli/usage.ts +11 -1
  68. package/src/create-mate.ts +5 -4
  69. package/src/hooks/tokensave-route.ts +26 -0
  70. package/src/lib/apply-context/fingerprint.ts +174 -0
  71. package/src/lib/apply-context/protocol.ts +193 -0
  72. package/src/lib/components/confirm-prompt.tsx +21 -9
  73. package/src/lib/components/select-menu.tsx +10 -3
  74. package/src/lib/components/spinner.tsx +4 -2
  75. package/src/lib/components/startup-progress.tsx +227 -41
  76. package/src/lib/components/text-input-display.tsx +2 -0
  77. package/src/lib/components/wizard-footer.tsx +2 -0
  78. package/src/lib/components/wizard-header.tsx +13 -11
  79. package/src/lib/delivery/archive-change.ts +14 -2
  80. package/src/lib/delivery/branches.ts +29 -5
  81. package/src/lib/delivery/environment.ts +7 -1
  82. package/src/lib/delivery/forge.ts +2 -2
  83. package/src/lib/delivery/merge-git.ts +261 -0
  84. package/src/lib/delivery/overlap.ts +11 -4
  85. package/src/lib/delivery/record-delivery.ts +97 -10
  86. package/src/lib/delivery/record.ts +67 -7
  87. package/src/lib/delivery/refresh.ts +104 -10
  88. package/src/lib/delivery/repository-access.ts +46 -2
  89. package/src/lib/delivery/resolve-branch.ts +162 -0
  90. package/src/lib/delivery/token.ts +7 -41
  91. package/src/lib/factory/attach-client.ts +113 -0
  92. package/src/lib/factory/attach.ts +178 -0
  93. package/src/lib/factory/broker.ts +190 -0
  94. package/src/lib/factory/bun-commands.ts +39 -0
  95. package/src/lib/factory/client.ts +92 -0
  96. package/src/lib/factory/command.ts +61 -0
  97. package/src/lib/factory/credential-store.ts +153 -0
  98. package/src/lib/factory/frames.ts +77 -0
  99. package/src/lib/factory/ids.ts +58 -0
  100. package/src/lib/factory/keyed-serial.ts +27 -0
  101. package/src/lib/factory/outcomes/actions.ts +114 -0
  102. package/src/lib/factory/outcomes/index.ts +381 -0
  103. package/src/lib/factory/outcomes/lifecycle.ts +205 -0
  104. package/src/lib/factory/outcomes/runs.ts +81 -0
  105. package/src/lib/factory/outcomes/sessions.ts +38 -0
  106. package/src/lib/factory/prepare.ts +49 -0
  107. package/src/lib/factory/pty.ts +103 -0
  108. package/src/lib/factory/runner/companion-context.ts +178 -0
  109. package/src/lib/factory/runner/control.ts +92 -0
  110. package/src/lib/factory/runner/harness-agent.ts +250 -0
  111. package/src/lib/factory/runner/live.ts +159 -0
  112. package/src/lib/factory/runner/questions.ts +22 -0
  113. package/src/lib/factory/runner/rank.ts +26 -0
  114. package/src/lib/factory/runner/run-policy.ts +12 -0
  115. package/src/lib/factory/runner/run.ts +199 -0
  116. package/src/lib/factory/runner/scheduler.ts +416 -0
  117. package/src/lib/factory/runner/state.ts +233 -0
  118. package/src/lib/factory/runner/workflow.ts +542 -0
  119. package/src/lib/factory/runtime.ts +972 -0
  120. package/src/lib/factory/sandbox.ts +292 -0
  121. package/src/lib/factory/worktree-branch.ts +17 -0
  122. package/src/lib/install.ts +66 -14
  123. package/src/lib/live-progress.ts +36 -0
  124. package/src/lib/member-choices.ts +67 -0
  125. package/src/lib/orchestrator/adapters/base.ts +55 -22
  126. package/src/lib/orchestrator/adapters/claude.ts +6 -1
  127. package/src/lib/orchestrator/config-store.ts +3 -2
  128. package/src/lib/orchestrator/editor.ts +29 -23
  129. package/src/lib/orchestrator/projection-entries.ts +56 -21
  130. package/src/lib/orchestrator/projection-opencode-copies.ts +32 -15
  131. package/src/lib/orchestrator/projection-openspec-store.ts +54 -9
  132. package/src/lib/orchestrator/projection-types.ts +33 -1
  133. package/src/lib/orchestrator/session-context-link.ts +67 -0
  134. package/src/lib/orchestrator/setup-compatibilities.ts +55 -12
  135. package/src/lib/orchestrator/types.ts +5 -0
  136. package/src/lib/orchestrator/working-repo-projection.ts +50 -7
  137. package/src/lib/orchestrator/workspace-document.ts +105 -0
  138. package/src/lib/package-paths.ts +29 -0
  139. package/src/lib/runtime-directory-refresh.ts +17 -1
  140. package/src/lib/workset/record.ts +513 -0
  141. package/src/lib/workset/repositories.ts +55 -0
  142. package/src/lib/workset/stage.ts +148 -0
  143. package/src/lib/workset/stages.ts +113 -0
  144. package/src/lib/workset/worktree-index.ts +116 -0
  145. package/src/lib/workset/worktree.ts +830 -0
  146. package/src/opencode/companion-hooks.ts +45 -2
  147. package/src/opencode/enter-worktree.ts +72 -0
  148. package/src/opencode/tui.tsx +9 -4
  149. package/src/plugins.ts +1 -0
  150. package/src/runtime/claude-delivery-plan.ts +22 -5
  151. package/src/runtime/companion-git.ts +52 -10
  152. package/src/runtime/companion-guidance.ts +7 -7
  153. package/src/runtime/companion-lock.ts +30 -7
  154. package/src/runtime/env.ts +48 -3
  155. package/src/runtime/git-layout.ts +219 -0
  156. package/src/runtime/index.ts +24 -0
  157. package/src/runtime/physical-path.ts +111 -0
  158. package/src/runtime/policy.ts +36 -2
  159. package/src/runtime/runtime-directory.ts +5 -0
  160. package/src/runtime/secret-guard.ts +19 -5
  161. package/src/runtime/secret-patterns.ts +267 -34
  162. package/src/runtime/session-context.ts +98 -0
  163. package/src/runtime/tokensave-route.ts +152 -0
  164. package/src/runtime/wrap-state.ts +24 -16
  165. package/src/studio.ts +124 -0
  166. package/src/templates/capabilities/openspec-cap/mate-minimal/schema.yaml +10 -8
  167. package/src/templates/capabilities/openspec-cap/mate-v1/schema.yaml +16 -98
  168. package/src/templates/capabilities/openspec-cap/openspec-conventions.yaml +10 -2
  169. package/src/templates/mate-skills/agents/mate-apply-change/SKILL.md +76 -18
  170. package/src/templates/mate-skills/agents/mate-apply-change/references/mate-compact-apply.md +47 -0
  171. package/src/templates/mate-skills/agents/mate-apply-change/references/openspec-apply-change.md +2 -0
  172. package/src/templates/mate-skills/agents/mate-archive-change/SKILL.md +32 -5
  173. package/src/templates/mate-skills/agents/mate-backfill-spec/SKILL.md +8 -1
  174. package/src/templates/mate-skills/agents/mate-clarify-intent/SKILL.md +16 -1
  175. package/src/templates/mate-skills/agents/mate-explore-change/SKILL.md +22 -6
  176. package/src/templates/mate-skills/agents/mate-explore-change/references/openspec-explore.md +2 -0
  177. package/src/templates/mate-skills/agents/mate-grill-me/SKILL.md +8 -1
  178. package/src/templates/mate-skills/agents/mate-grill-with-docs/SKILL.md +2 -2
  179. package/src/templates/mate-skills/agents/mate-interview-me/SKILL.md +7 -0
  180. package/src/templates/mate-skills/agents/mate-propose-change/SKILL.md +55 -50
  181. package/src/templates/mate-skills/agents/mate-propose-change/references/mate-revise.md +47 -0
  182. package/src/templates/mate-skills/agents/mate-propose-change/references/openspec-propose.md +2 -0
  183. package/src/templates/mate-skills/agents/mate-propose-change/references/openspec-update-change.md +2 -0
  184. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +29 -10
  185. package/src/templates/mate-skills/agents/mate-publish-artifact/references/openspec.md +4 -2
  186. package/src/templates/mate-skills/agents/mate-show-me/SKILL.md +21 -0
  187. package/src/templates/mate-skills/agents/mate-simplify-code/SKILL.md +13 -0
  188. package/src/templates/mate-skills/claude/mate-apply-change/SKILL.md +76 -18
  189. package/src/templates/mate-skills/claude/mate-apply-change/references/mate-compact-apply.md +47 -0
  190. package/src/templates/mate-skills/claude/mate-apply-change/references/openspec-apply-change.md +2 -0
  191. package/src/templates/mate-skills/claude/mate-archive-change/SKILL.md +32 -5
  192. package/src/templates/mate-skills/claude/mate-backfill-spec/SKILL.md +8 -1
  193. package/src/templates/mate-skills/claude/mate-clarify-intent/SKILL.md +16 -1
  194. package/src/templates/mate-skills/claude/mate-explore-change/SKILL.md +22 -6
  195. package/src/templates/mate-skills/claude/mate-explore-change/references/openspec-explore.md +2 -0
  196. package/src/templates/mate-skills/claude/mate-grill-me/SKILL.md +8 -1
  197. package/src/templates/mate-skills/claude/mate-grill-with-docs/SKILL.md +2 -2
  198. package/src/templates/mate-skills/claude/mate-interview-me/SKILL.md +7 -0
  199. package/src/templates/mate-skills/claude/mate-propose-change/SKILL.md +55 -50
  200. package/src/templates/mate-skills/claude/mate-propose-change/references/mate-revise.md +47 -0
  201. package/src/templates/mate-skills/claude/mate-propose-change/references/openspec-propose.md +2 -0
  202. package/src/templates/mate-skills/claude/mate-propose-change/references/openspec-update-change.md +2 -0
  203. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +29 -10
  204. package/src/templates/mate-skills/claude/mate-publish-artifact/references/openspec.md +4 -2
  205. package/src/templates/mate-skills/claude/mate-show-me/SKILL.md +21 -0
  206. package/src/templates/mate-skills/claude/mate-simplify-code/SKILL.md +13 -0
  207. package/src/templates/mate-skills/openspec-references.ts +2 -0
  208. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +364 -224
  209. package/src/tools/setup/capabilities/companion-mentions.ts +27 -0
  210. package/src/tools/setup/capabilities/context-mode.ts +34 -5
  211. package/src/tools/setup/capabilities/graphify-secrets.ts +2 -14
  212. package/src/tools/setup/capabilities/graphify.ts +34 -7
  213. package/src/tools/setup/capabilities/openspec.ts +12 -2
  214. package/src/tools/setup/capabilities/react-doctor.ts +8 -1
  215. package/src/tools/setup/capabilities/rtk.ts +4 -0
  216. package/src/tools/setup/capabilities/tokensave.ts +77 -68
  217. package/src/tools/setup/engine.ts +3 -2
  218. package/src/tools/setup/install-contract.ts +8 -0
  219. package/src/tools/setup/mate-skill-copies.ts +51 -0
  220. package/src/tools/setup/package-managers/uv.ts +73 -11
  221. package/src/tools/setup/plugin.ts +5 -0
  222. package/src/tools/setup/providers/claude-plugin-hooks.ts +12 -0
  223. package/src/tools/setup/providers/claude-worktree-plugins.ts +122 -0
  224. package/src/tools/setup/providers/claude.ts +11 -5
  225. package/src/tools/setup/utils.ts +4 -0
  226. package/src/tools/setup/working-repo-cleanup.ts +29 -1
  227. package/src/tools/setup/working-repo-local-state.ts +252 -75
  228. package/src/tools/setup.ts +57 -16
  229. package/studio-dist/client/assets/companion-view-Csva26Ir.js +1 -0
  230. package/studio-dist/client/assets/delivery-path-DJMpRmiY.js +1 -0
  231. package/studio-dist/client/assets/dist-Dm7MtyHc.js +5 -0
  232. package/studio-dist/client/assets/factory-B7l9ZQyx.js +4 -0
  233. package/studio-dist/client/assets/index-n6uo_92S.js +40 -0
  234. package/studio-dist/client/assets/preload-helper-BLdHbfdN.js +1 -0
  235. package/studio-dist/client/assets/prepaint-CD5OpmTM.js +24 -0
  236. package/studio-dist/client/assets/queries-CN3JwMBX.js +1 -0
  237. package/studio-dist/client/assets/react-CabXf2Ds.js +1 -0
  238. package/studio-dist/client/assets/report-time-Dc-KOqQu.js +1 -0
  239. package/studio-dist/client/assets/reports-C01RsnMA.js +1 -0
  240. package/studio-dist/client/assets/rolldown-runtime-WkwZ5CU-.js +1 -0
  241. package/studio-dist/client/assets/routes-4pbC-2Hj.js +1 -0
  242. package/studio-dist/client/assets/skills-CihQganl.js +1 -0
  243. package/studio-dist/client/assets/spec-areas-C2L48N4C.js +1 -0
  244. package/studio-dist/client/assets/specs-D24_35_K.js +1 -0
  245. package/studio-dist/client/assets/studio-DKxfi691.css +1 -0
  246. package/studio-dist/client/assets/studio-queries-rvbJupCy.js +3 -0
  247. package/studio-dist/client/assets/terminal-eU5fzQzv.css +1 -0
  248. package/studio-dist/client/assets/vault-Bd4CQiTK.js +1 -0
  249. package/studio-dist/client/assets/warnings-V_Ys51wJ.js +1 -0
  250. package/studio-dist/client/assets/wasm-inline-C2en61B5.js +1 -0
  251. package/studio-dist/client/assets/workflow-BJejeVwQ.js +1 -0
  252. package/studio-dist/server/assets/__23tanstack-start-server-fn-resolver-BQKuMdJW.js +3881 -0
  253. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +85 -0
  254. package/studio-dist/server/assets/actions-Bvgj9eb8.js +54 -0
  255. package/studio-dist/server/assets/actions-D8erOphH.js +44 -0
  256. package/studio-dist/server/assets/companion-view-aBady57v.js +33 -0
  257. package/studio-dist/server/assets/createServerFn-F5sAOF8V.js +459 -0
  258. package/studio-dist/server/assets/createServerRpc-tK2lE9R2.js +11 -0
  259. package/studio-dist/server/assets/delivery-path-BkKNjgkf.js +778 -0
  260. package/studio-dist/server/assets/dist-DpJWKyCm.js +5582 -0
  261. package/studio-dist/server/assets/empty-plugin-adapters-Cipd4ZH4.js +4 -0
  262. package/studio-dist/server/assets/factory-D6xnjedJ.js +2385 -0
  263. package/studio-dist/server/assets/factory-DT3UzHlh.js +68 -0
  264. package/studio-dist/server/assets/model-PyPALjii.js +18 -0
  265. package/studio-dist/server/assets/prepaint-BMke0fo1.js +41 -0
  266. package/studio-dist/server/assets/queries-Ag2iL8q2.js +107 -0
  267. package/studio-dist/server/assets/react-COs0LHn-.js +51 -0
  268. package/studio-dist/server/assets/report-time-DAfzln-N.js +8 -0
  269. package/studio-dist/server/assets/reports-BnUNJVtx.js +126 -0
  270. package/studio-dist/server/assets/rolldown-runtime-DYf_mQCB.js +34 -0
  271. package/studio-dist/server/assets/router-BH--drIx.js +4298 -0
  272. package/studio-dist/server/assets/routes-khSDK1bV.js +361 -0
  273. package/studio-dist/server/assets/search-JAKurDNh.js +36 -0
  274. package/studio-dist/server/assets/shell-CboT2f66.js +51 -0
  275. package/studio-dist/server/assets/skills-MWYnWoKs.js +106 -0
  276. package/studio-dist/server/assets/spec-areas-DcnO6vW-.js +16 -0
  277. package/studio-dist/server/assets/specs-DE3w8hZP.js +155 -0
  278. package/studio-dist/server/assets/start-BW5ovN0k.js +33 -0
  279. package/studio-dist/server/assets/studio-BeltxxKt.js +216 -0
  280. package/studio-dist/server/assets/studio-queries-CLnP9kGu.js +3365 -0
  281. package/studio-dist/server/assets/utils-C9CX1kcy.js +221 -0
  282. package/studio-dist/server/assets/vault-BGulVoNh.js +70 -0
  283. package/studio-dist/server/assets/vault-CuyyhLyB.js +832 -0
  284. package/studio-dist/server/assets/views-Bd7cRr27.js +82 -0
  285. package/studio-dist/server/assets/warnings-BH05rOuG.js +15 -0
  286. package/studio-dist/server/assets/wasm-inline-CNeBKGwC.js +3 -0
  287. package/studio-dist/server/assets/workflow-BSuIKWqH.js +42 -0
  288. package/studio-dist/server/server.js +16220 -0
  289. package/src/cli/commands/studio/client-asset.ts +0 -16
  290. package/src/cli/commands/studio/views/client.ts +0 -44
  291. package/src/cli/commands/studio/views/companion-picker.tsx +0 -95
  292. package/src/cli/commands/studio/views/companion-selector.tsx +0 -94
  293. package/src/cli/commands/studio/views/dashboard/changes.tsx +0 -102
  294. package/src/cli/commands/studio/views/dashboard/index.tsx +0 -19
  295. package/src/cli/commands/studio/views/document.tsx +0 -910
  296. package/src/cli/commands/studio/views/error.tsx +0 -20
  297. package/src/cli/commands/studio/views/markdown.tsx +0 -250
  298. package/src/cli/commands/studio/views/palette.ts +0 -134
  299. package/src/cli/commands/studio/views/reports/index.tsx +0 -44
  300. package/src/cli/commands/studio/views/selection-fields.tsx +0 -14
  301. package/src/cli/commands/studio/views/skills/index.tsx +0 -68
  302. package/src/cli/commands/studio/views/specs/index.tsx +0 -149
  303. package/src/cli/commands/studio/views/studio-client/actions.ts +0 -51
  304. package/src/cli/commands/studio/views/studio-client/companion.ts +0 -13
  305. package/src/cli/commands/studio/views/studio-client/index.ts +0 -32
  306. package/src/cli/commands/studio/views/studio-client/keys.ts +0 -3
  307. package/src/cli/commands/studio/views/studio-client/main.ts +0 -3
  308. package/src/cli/commands/studio/views/studio-client/page.ts +0 -146
  309. package/src/cli/commands/studio/views/studio-client/panels.ts +0 -57
  310. package/src/cli/commands/studio/views/studio-client/reports.ts +0 -122
  311. package/src/cli/commands/studio/views/studio-client/theme.ts +0 -63
  312. package/src/cli/commands/studio/views/studio-client/vault-editor.ts +0 -166
  313. package/src/cli/commands/studio/views/studio-client/vault-pane.ts +0 -202
  314. package/src/cli/commands/studio/views/studio-client/vault-tree.ts +0 -258
  315. package/src/cli/commands/studio/views/studio-client.generated.ts +0 -2
  316. package/src/cli/commands/studio/views/styles.ts +0 -530
  317. package/src/cli/commands/studio/views/terminal.tsx +0 -484
  318. package/src/cli/commands/studio/views/vault/state.ts +0 -41
  319. package/src/cli/commands/studio/views/warnings.tsx +0 -21
  320. package/src/cli/commands/studio/views/workflow/delivery-path.tsx +0 -370
  321. package/src/cli/commands/studio/views/workflow/graph.ts +0 -220
  322. package/src/cli/commands/studio/views/workflow/index.tsx +0 -20
  323. package/src/cli/commands/studio/views/workflow/steps.ts +0 -278
  324. package/src/lib/components/theme.ts +0 -2
  325. package/src/tools/setup/git-utils.ts +0 -30
@@ -0,0 +1,830 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ import { FRAMEWORK_NAME } from "../../framework";
6
+ import { gitEnvironment, withoutAskPass } from "../../runtime/companion-git";
7
+ import { withCompanionLock } from "../../runtime/companion-lock";
8
+ import { errorMessage } from "../../runtime/error-message";
9
+ import type { WrapRuntime } from "../../runtime/runtime-document-manifest";
10
+ import { readWrapState, WRAP_RUNTIMES } from "../../runtime/wrap-state";
11
+ import { cleanupWorkingRepository } from "../../tools/setup/working-repo-cleanup";
12
+ import { locateChange } from "../change-layout";
13
+ import { type DeliveryRecord, readDeliveryRecord } from "../delivery/record";
14
+ import {
15
+ newBranchBase,
16
+ resolveDeliveryBranch,
17
+ worktreeAddArgs,
18
+ type BranchSource,
19
+ } from "../delivery/resolve-branch";
20
+ import { scopedRepositories } from "../openspec-scopes";
21
+ import { attendedLockOptions } from "../orchestrator/companion-git-sync";
22
+ import {
23
+ readCompanionRegistry,
24
+ writeRepoLocalRegistryEntry,
25
+ } from "../orchestrator/repository-link";
26
+ import type { LinkedRepository } from "../orchestrator/types";
27
+ import { runWrapPass } from "../orchestrator/wrap-pass";
28
+ import { identityOf } from "./repositories";
29
+ import { indexWorktree, type IndexOutcome, type TokensaveRunner } from "./worktree-index";
30
+ import { findWorkset, readWorksets, resolveWorksetBranch, resolveWorksetOf } from "./record";
31
+
32
+ /**
33
+ * Workset worktrees outside the factory: one Git worktree per Working Repository at
34
+ * `<main checkout>.worktrees/<workset-id>`, on the Workset's Delivery Branch, linked to
35
+ * the companion, wrapped like its main checkout and installed. Env files are reported by
36
+ * path, never opened.
37
+ */
38
+
39
+ export interface GitResult {
40
+ code: number;
41
+ stdout: string;
42
+ stderr: string;
43
+ }
44
+
45
+ export interface GitRunOptions {
46
+ /** Added to the promptless environment every command gets. */
47
+ env?: Record<string, string>;
48
+ timeoutMs?: number;
49
+ }
50
+
51
+ export type GitRunner = (
52
+ cwd: string,
53
+ args: string[],
54
+ options?: GitRunOptions,
55
+ ) => Promise<GitResult>;
56
+
57
+ /** Runs an install command; `stream` passes its output through, otherwise it is discarded. */
58
+ export type InstallRunner = (cwd: string, command: string[], stream: boolean) => Promise<boolean>;
59
+
60
+ /** Wraps the worktree for `runtimes`; resolves to the failure message, or null. */
61
+ export type WorktreeWrapper = (
62
+ companionPath: string,
63
+ repository: LinkedRepository,
64
+ runtimes: readonly WrapRuntime[],
65
+ ) => Promise<string | null>;
66
+
67
+ export interface WorktreeDeps {
68
+ git?: GitRunner;
69
+ install?: InstallRunner;
70
+ writeLink?: typeof writeRepoLocalRegistryEntry;
71
+ readWrapState?: typeof readWrapState;
72
+ wrap?: WorktreeWrapper;
73
+ unwrap?: typeof cleanupWorkingRepository;
74
+ tokensave?: TokensaveRunner;
75
+ /** The process's working directory; a worktree holding it is kept. */
76
+ cwd?: () => string;
77
+ }
78
+
79
+ export type InstallOutcome = "ok" | "failed" | "skipped";
80
+
81
+ export interface WrapOutcome {
82
+ /** The runtimes the main checkout is wrapped for. */
83
+ runtimes: WrapRuntime[];
84
+ outcome: InstallOutcome;
85
+ reason?: string;
86
+ }
87
+
88
+ export interface WorktreeRepositoryResult {
89
+ repository: string;
90
+ /** The main checkout the worktree belongs to. */
91
+ checkout: string;
92
+ path: string;
93
+ branch: string;
94
+ action: "created" | "reused";
95
+ install: { command: string | null; outcome: InstallOutcome; reason?: string };
96
+ wrap: WrapOutcome;
97
+ /** The worktree's tokensave index; a failure only warns. */
98
+ index: IndexOutcome;
99
+ /** Env files of the main checkout the worktree lacks, relative to the repository root. */
100
+ missingEnv: string[];
101
+ /** Set when a step for this repository failed. */
102
+ error?: string;
103
+ }
104
+
105
+ export interface WorktreeResult {
106
+ workset: string;
107
+ ok: boolean;
108
+ repositories: WorktreeRepositoryResult[];
109
+ diagnostics: string[];
110
+ warnings: string[];
111
+ }
112
+
113
+ export interface PruneEntry {
114
+ workset: string;
115
+ repository: string;
116
+ path: string;
117
+ }
118
+
119
+ /** A Workset to prune: its id and the changes whose Delivery Records name its branches. */
120
+ export interface PruneTarget {
121
+ id: string;
122
+ changes: readonly string[];
123
+ }
124
+
125
+ export interface PruneResult {
126
+ removed: PruneEntry[];
127
+ kept: (PruneEntry & { reason: string })[];
128
+ warnings: string[];
129
+ }
130
+
131
+ /** Never prompts: worktree creation runs unattended, often under `--json`. */
132
+ function promptlessEnv(): NodeJS.ProcessEnv {
133
+ return {
134
+ ...withoutAskPass(gitEnvironment()),
135
+ GIT_TERMINAL_PROMPT: "0",
136
+ GCM_INTERACTIVE: "never",
137
+ } as NodeJS.ProcessEnv;
138
+ }
139
+
140
+ const runGit: GitRunner = (cwd, args, options = {}) =>
141
+ new Promise<GitResult>((resolve) => {
142
+ let timer: ReturnType<typeof setTimeout> | undefined;
143
+ const child = execFile(
144
+ "git",
145
+ args,
146
+ { cwd, env: { ...promptlessEnv(), ...options.env }, maxBuffer: 16 * 1024 * 1024 },
147
+ (error, stdout, stderr) => {
148
+ clearTimeout(timer);
149
+ const code = error ? (typeof error.code === "number" ? error.code : 1) : 0;
150
+ resolve({ code, stdout: String(stdout), stderr: String(stderr) });
151
+ },
152
+ );
153
+ const { timeoutMs } = options;
154
+ if (timeoutMs !== undefined) {
155
+ // Resolved without awaiting `close`: an SSH grandchild may hold the pipes open.
156
+ timer = setTimeout(() => {
157
+ child.kill("SIGKILL");
158
+ resolve({ code: 1, stdout: "", stderr: `git ${args[0]} timed out after ${timeoutMs} ms` });
159
+ }, timeoutMs);
160
+ }
161
+ });
162
+
163
+ const FETCH_TIMEOUT_MS = 60_000;
164
+
165
+ /** `git fetch --prune origin`, bounded; SSH runs in batch mode unless the user set their own command. */
166
+ async function fetchOrigin(git: GitRunner, checkout: string): Promise<GitResult> {
167
+ const ownSsh =
168
+ Boolean(process.env.GIT_SSH_COMMAND || process.env.GIT_SSH) ||
169
+ (await git(checkout, ["config", "--get", "core.sshCommand"])).code === 0;
170
+ return git(checkout, ["fetch", "--prune", "origin"], {
171
+ env: ownSsh ? {} : { GIT_SSH_COMMAND: "ssh -o BatchMode=yes" },
172
+ timeoutMs: FETCH_TIMEOUT_MS,
173
+ });
174
+ }
175
+
176
+ /** Serialized with `mate wrap`, Session Prepare and every sync, which rewrite the same manifests. */
177
+ const runWrap: WorktreeWrapper = async (companionPath, repository, runtimes) => {
178
+ const locked = await withCompanionLock(companionPath, attendedLockOptions(companionPath), () =>
179
+ runWrapPass(companionPath, repository, { runtimes }),
180
+ );
181
+ if (!locked.acquired) return "another companion synchronization is still running";
182
+ return locked.value.kind === "failed" ? locked.value.message : null;
183
+ };
184
+
185
+ const runInstall: InstallRunner = (cwd, [command, ...args], stream) =>
186
+ new Promise((resolve) => {
187
+ const child = spawn(command!, args, { cwd, stdio: stream ? "inherit" : "ignore" });
188
+ child.on("error", () => resolve(false));
189
+ child.on("close", (code) => resolve(code === 0));
190
+ });
191
+
192
+ /** First match wins, at the worktree root only: workspace managers install the whole repository. */
193
+ const LOCKFILES: [string, string[]][] = [
194
+ ["bun.lock", ["bun", "install"]],
195
+ ["bun.lockb", ["bun", "install"]],
196
+ ["pnpm-lock.yaml", ["pnpm", "install"]],
197
+ ["yarn.lock", ["yarn", "install"]],
198
+ ["package-lock.json", ["npm", "ci"]],
199
+ ];
200
+
201
+ /** The install skip reason of a repository whose worktree could not be created. */
202
+ export const NOT_CREATED = "worktree not created";
203
+
204
+ const ENV_NAME = /^\.env(\..+)?$/;
205
+ const ENV_EXAMPLE = /\.(example|sample|template|dist)$/;
206
+
207
+ async function exists(candidate: string): Promise<boolean> {
208
+ try {
209
+ await fs.access(candidate);
210
+ return true;
211
+ } catch {
212
+ return false;
213
+ }
214
+ }
215
+
216
+ /** Real path when it exists; otherwise the nearest existing parent resolved, so macOS `/var` matches `/private/var`. */
217
+ async function canonical(candidate: string): Promise<string> {
218
+ try {
219
+ return await fs.realpath(candidate);
220
+ } catch {
221
+ const parent = path.dirname(candidate);
222
+ if (parent === candidate) return candidate;
223
+ return path.join(await canonical(parent), path.basename(candidate));
224
+ }
225
+ }
226
+
227
+ function worktreePathFor(mainCheckout: string, worksetId: string): string {
228
+ return path.join(
229
+ path.dirname(mainCheckout),
230
+ `${path.basename(mainCheckout)}.worktrees`,
231
+ worksetId,
232
+ );
233
+ }
234
+
235
+ interface WorktreeEntry {
236
+ path: string;
237
+ /** Short branch name, or null when detached or bare. */
238
+ branch: string | null;
239
+ /** `git worktree lock` set; `git worktree remove` refuses it without `--force`. */
240
+ locked: boolean;
241
+ /** Set when Git marks the entry prunable (its directory or `.git` file is gone): Git's reason. */
242
+ stale: string | null;
243
+ }
244
+
245
+ async function listWorktrees(git: GitRunner, repo: string): Promise<WorktreeEntry[] | null> {
246
+ const result = await git(repo, ["worktree", "list", "--porcelain"]);
247
+ if (result.code !== 0) return null;
248
+ const entries = result.stdout.split(/\n\n+/).flatMap((block) => {
249
+ let entryPath: string | null = null;
250
+ let branch: string | null = null;
251
+ let locked = false;
252
+ let stale: string | null = null;
253
+ for (const line of block.split("\n")) {
254
+ if (line.startsWith("worktree ")) entryPath = line.slice("worktree ".length);
255
+ else if (line.startsWith("branch refs/heads/"))
256
+ branch = line.slice("branch refs/heads/".length);
257
+ else if (line === "locked" || line.startsWith("locked ")) locked = true;
258
+ else if (line === "prunable" || line.startsWith("prunable ")) {
259
+ stale = line.slice("prunable".length).trim() || "prunable";
260
+ }
261
+ }
262
+ return entryPath ? [{ path: entryPath, branch, locked, stale }] : [];
263
+ });
264
+ return Promise.all(
265
+ entries.map(async (entry) => ({ ...entry, path: await canonical(entry.path) })),
266
+ );
267
+ }
268
+
269
+ /** The first existing checkout linked to the companion whose `origin` is the repository. */
270
+ async function linkedCheckout(
271
+ companionPath: string,
272
+ repository: string,
273
+ git: GitRunner,
274
+ ): Promise<LinkedRepository | null> {
275
+ let repos: LinkedRepository[] = [];
276
+ try {
277
+ repos = (await readCompanionRegistry(companionPath)).repos;
278
+ } catch (error) {
279
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
280
+ }
281
+ const identities = await Promise.all(
282
+ repos.map(async (repo) => {
283
+ if (!(await exists(repo.path))) return null;
284
+ // Raw config, not `remote get-url`, so `insteadOf` rewrites do not change the identity.
285
+ const remote = await git(repo.path, ["config", "--get", "remote.origin.url"]);
286
+ return remote.code === 0 ? identityOf(remote.stdout.trim()) : null;
287
+ }),
288
+ );
289
+ // The first match in registry order decides.
290
+ const index = identities.findIndex(
291
+ (identity) => identity?.toLowerCase() === repository.toLowerCase(),
292
+ );
293
+ return index === -1 ? null : repos[index]!;
294
+ }
295
+
296
+ interface Plan {
297
+ repository: string;
298
+ /** The main checkout's Repository Link id, which the worktree's link repeats. */
299
+ repositoryId: string;
300
+ checkout: string;
301
+ target: string;
302
+ branch: string;
303
+ source: BranchSource;
304
+ /** Start point when `source` is `new`. */
305
+ base?: string;
306
+ reuse: boolean;
307
+ }
308
+
309
+ /** A resolved Workset: its id and the repositories that get a worktree. */
310
+ interface Target {
311
+ id: string;
312
+ repositories: readonly string[];
313
+ }
314
+
315
+ /** The explicit record with this id, or the diagnostics naming it and every invalid record. */
316
+ async function recordTarget(companionPath: string, worksetId: string): Promise<Target | string[]> {
317
+ const { worksets, problems } = await readWorksets(companionPath);
318
+ const record = worksets.find((entry) => entry.id === worksetId);
319
+ if (record) return record;
320
+ return [
321
+ `no valid Workset ${worksetId}`,
322
+ ...problems.map((problem) => `${problem.path}: ${problem.reason}`),
323
+ ];
324
+ }
325
+
326
+ /**
327
+ * The change's Workset as `mate artifact link` resolves it: the record listing it, else the
328
+ * implicit single-change Workset with the repositories of the change's scopes.
329
+ */
330
+ async function changeTarget(companionPath: string, change: string): Promise<Target | string[]> {
331
+ const location = await locateChange(companionPath, change);
332
+ if (!location || location.archived) return [`no active change ${change}`];
333
+ const resolution = await resolveWorksetOf(companionPath, change);
334
+ if (resolution.id === null) return resolution.diagnostics;
335
+ if (!resolution.implicit) {
336
+ const record = await findWorkset(companionPath, resolution.id);
337
+ return record ?? [`no valid Workset ${resolution.id}`];
338
+ }
339
+ const repositories = await scopedRepositories(location.dir);
340
+ if (repositories.length === 0) return [`change ${change} names no repository in its scopes`];
341
+ return { id: resolution.id, repositories };
342
+ }
343
+
344
+ /** Phase 1: every check for every repository; any failure means nothing is created. */
345
+ async function planWorktrees(
346
+ companionPath: string,
347
+ target: Target,
348
+ git: GitRunner,
349
+ ): Promise<{ plans: Plan[]; diagnostics: string[]; warnings: string[] }> {
350
+ const warnings: string[] = [];
351
+ const checked = await Promise.all(
352
+ target.repositories.map((repository) =>
353
+ planRepository(companionPath, target.id, repository, git, warnings),
354
+ ),
355
+ );
356
+ return {
357
+ plans: checked.filter((entry): entry is Plan => !Array.isArray(entry)),
358
+ diagnostics: checked.flatMap((entry) => (Array.isArray(entry) ? entry : [])),
359
+ warnings,
360
+ };
361
+ }
362
+
363
+ /** One repository's plan, or the diagnostics that stop the run. */
364
+ async function planRepository(
365
+ companionPath: string,
366
+ worksetId: string,
367
+ repository: string,
368
+ git: GitRunner,
369
+ warnings: string[],
370
+ ): Promise<Plan | string[]> {
371
+ const linked = await linkedCheckout(companionPath, repository, git);
372
+ if (!linked) {
373
+ // An identity problem outranks the missing link.
374
+ const identity = await resolveWorksetBranch(companionPath, worksetId, repository);
375
+ if (identity.id === null) return identity.diagnostics.map((line) => `${repository}: ${line}`);
376
+ return [`${repository}: not linked to ${companionPath} on this machine`];
377
+ }
378
+ // Resolved after the fetch, so a branch pushed elsewhere counts as existing.
379
+ const fetched = await fetchOrigin(git, linked.path);
380
+ if (fetched.code !== 0) {
381
+ warnings.push(
382
+ `${repository}: fetching origin failed, using local refs: ${fetched.stderr.trim()}`,
383
+ );
384
+ }
385
+ const hasRef = async (ref: string) =>
386
+ (await git(linked.path, ["rev-parse", "--verify", "--quiet", ref])).code === 0;
387
+ const resolution = await resolveDeliveryBranch({ companionPath, repository, hasRef, worksetId });
388
+ const { branch, source } = resolution;
389
+ if (branch === null || source === null) {
390
+ return resolution.diagnostics.map((line) => `${repository}: ${line}`);
391
+ }
392
+ const entries = await listWorktrees(git, linked.path);
393
+ const main = entries?.[0];
394
+ if (!main) return [`${repository}: cannot list the worktrees of ${linked.path}`];
395
+ const target = await canonical(worktreePathFor(main.path, worksetId));
396
+ const atTarget = entries.find((entry) => entry.path === target);
397
+ // A stale entry is never reused: wrapping it would only refill a folder without a checkout.
398
+ const stale = entries.find(
399
+ (entry) => entry.stale && (entry.path === target || entry.branch === branch),
400
+ );
401
+ if (stale) {
402
+ return [
403
+ `${repository}: ${stale.path} is a stale worktree entry (${stale.stale}); remove any folder left there, run \`git worktree prune\` in ${main.path}, then retry`,
404
+ ];
405
+ }
406
+ const reuse = atTarget?.branch === branch;
407
+ if (!reuse && (atTarget || (await exists(target)))) {
408
+ return [`${repository}: ${target} exists and is not a worktree of ${repository} on ${branch}`];
409
+ }
410
+ const elsewhere = entries.find((entry) => entry.branch === branch && entry.path !== target);
411
+ if (elsewhere) return [`${repository}: ${branch} is already checked out at ${elsewhere.path}`];
412
+ return {
413
+ repository,
414
+ repositoryId: linked.id,
415
+ checkout: main.path,
416
+ target,
417
+ branch,
418
+ source,
419
+ base: source === "new" ? await newBranchBase(hasRef) : undefined,
420
+ reuse,
421
+ };
422
+ }
423
+
424
+ async function addWorktree(git: GitRunner, plan: Plan): Promise<string | null> {
425
+ const result = await git(plan.checkout, worktreeAddArgs(plan, plan.target, plan.base));
426
+ return result.code === 0 ? null : `creating the worktree failed: ${result.stderr.trim()}`;
427
+ }
428
+
429
+ /** The runtimes `checkout` is wrapped for, in wrap order. */
430
+ async function wrappedRuntimes(checkout: string, deps: WorktreeDeps): Promise<WrapRuntime[]> {
431
+ const state = await (deps.readWrapState ?? readWrapState)(checkout);
432
+ return WRAP_RUNTIMES.filter((runtime) => state.runtimes.has(runtime));
433
+ }
434
+
435
+ /** Wraps the worktree for exactly the runtimes its main checkout is wrapped for. */
436
+ async function wrapWorktree(
437
+ companionPath: string,
438
+ checkout: string,
439
+ repository: LinkedRepository,
440
+ deps: WorktreeDeps,
441
+ ): Promise<WrapOutcome> {
442
+ let runtimes: WrapRuntime[];
443
+ try {
444
+ runtimes = await wrappedRuntimes(checkout, deps);
445
+ } catch (error) {
446
+ return {
447
+ runtimes: [],
448
+ outcome: "failed",
449
+ reason: `cannot read the wrap of ${checkout}: ${errorMessage(error)}`,
450
+ };
451
+ }
452
+ if (runtimes.length === 0) {
453
+ return { runtimes, outcome: "skipped", reason: "main checkout not wrapped" };
454
+ }
455
+ let failure: string | null;
456
+ try {
457
+ failure = await (deps.wrap ?? runWrap)(companionPath, repository, runtimes);
458
+ } catch (error) {
459
+ failure = errorMessage(error);
460
+ }
461
+ return failure ? { runtimes, outcome: "failed", reason: failure } : { runtimes, outcome: "ok" };
462
+ }
463
+
464
+ async function installCommand(worktree: string): Promise<string[] | null> {
465
+ for (const [lockfile, command] of LOCKFILES) {
466
+ // oxlint-disable-next-line no-await-in-loop -- lockfile order decides
467
+ if (await exists(path.join(worktree, lockfile))) return command;
468
+ }
469
+ return null;
470
+ }
471
+
472
+ /** Ignored, untracked env files of the main checkout absent from the worktree; paths only. */
473
+ async function missingEnvFiles(
474
+ git: GitRunner,
475
+ checkout: string,
476
+ worktree: string,
477
+ ): Promise<string[]> {
478
+ const listed = await git(checkout, [
479
+ "ls-files",
480
+ "-z",
481
+ "--others",
482
+ "--ignored",
483
+ "--exclude-standard",
484
+ "--directory",
485
+ ]);
486
+ if (listed.code !== 0) return [];
487
+ const candidates = listed.stdout
488
+ .split("\0")
489
+ .filter(
490
+ (entry) =>
491
+ entry &&
492
+ !entry.endsWith("/") &&
493
+ !entry.split("/").includes("node_modules") &&
494
+ ENV_NAME.test(path.posix.basename(entry)) &&
495
+ !ENV_EXAMPLE.test(entry),
496
+ );
497
+ const missing = await Promise.all(
498
+ candidates.map(async (entry) => ((await exists(path.join(worktree, entry))) ? null : entry)),
499
+ );
500
+ return missing.filter((entry): entry is string => entry !== null).toSorted();
501
+ }
502
+
503
+ export interface CreateWorktreesOptions {
504
+ install: boolean;
505
+ /** Pass the installer's output through; false discards it, as `--json` needs. */
506
+ streamInstall: boolean;
507
+ }
508
+
509
+ /**
510
+ * Creates or reuses the Workset's worktree in each of its Working Repositories. Checks
511
+ * everything first and creates nothing when a check fails; a later failure is reported
512
+ * for its repository and keeps the worktrees already made.
513
+ */
514
+ export async function createWorksetWorktrees(
515
+ companionPath: string,
516
+ worksetId: string,
517
+ options: CreateWorktreesOptions,
518
+ deps: WorktreeDeps = {},
519
+ ): Promise<WorktreeResult> {
520
+ const target = await recordTarget(companionPath, worksetId);
521
+ return createTargetWorktrees(companionPath, worksetId, target, options, deps);
522
+ }
523
+
524
+ /**
525
+ * As `createWorksetWorktrees`, for the Workset the change resolves to, implicit ones
526
+ * included; writes no Workset record.
527
+ */
528
+ export async function createChangeWorktrees(
529
+ companionPath: string,
530
+ change: string,
531
+ options: CreateWorktreesOptions,
532
+ deps: WorktreeDeps = {},
533
+ ): Promise<WorktreeResult> {
534
+ const target = await changeTarget(companionPath, change);
535
+ return createTargetWorktrees(companionPath, change, target, options, deps);
536
+ }
537
+
538
+ /** `fallbackId` names the result when the target did not resolve. */
539
+ async function createTargetWorktrees(
540
+ companionPath: string,
541
+ fallbackId: string,
542
+ target: Target | string[],
543
+ options: CreateWorktreesOptions,
544
+ deps: WorktreeDeps,
545
+ ): Promise<WorktreeResult> {
546
+ if (Array.isArray(target)) {
547
+ return { workset: fallbackId, ok: false, repositories: [], diagnostics: target, warnings: [] };
548
+ }
549
+ const worksetId = target.id;
550
+ const git = deps.git ?? runGit;
551
+ const { plans, diagnostics, warnings } = await planWorktrees(companionPath, target, git);
552
+ if (diagnostics.length > 0) {
553
+ return { workset: worksetId, ok: false, repositories: [], diagnostics, warnings };
554
+ }
555
+ const repositories: WorktreeRepositoryResult[] = [];
556
+ const indexing: Promise<void>[] = [];
557
+ const progress = options.streamInstall
558
+ ? (line: string) => process.stderr.write(`${line}\n`)
559
+ : undefined;
560
+ for (const plan of plans) {
561
+ // oxlint-disable-next-line no-await-in-loop -- one repository at a time, installs included
562
+ const result = await realize(companionPath, plan, options, git, deps, warnings);
563
+ repositories.push(result);
564
+ if (result.index.reason === NOT_CREATED) continue;
565
+ // Indexing overlaps the next repository's setup; only the report waits for it.
566
+ indexing.push(
567
+ indexWorktree(plan.checkout, plan.target, companionPath, deps.tokensave, (action) =>
568
+ progress?.(`${plan.repository}: tokensave ${action} of ${plan.target}…`),
569
+ ).then((index) => {
570
+ result.index = index;
571
+ }),
572
+ );
573
+ }
574
+ await Promise.all(indexing);
575
+ for (const result of repositories) {
576
+ if (result.index.outcome === "failed") {
577
+ warnings.push(`${result.repository}: tokensave index step failed: ${result.index.reason}`);
578
+ }
579
+ }
580
+ return {
581
+ workset: worksetId,
582
+ ok: repositories.every((entry) => !entry.error),
583
+ repositories,
584
+ diagnostics,
585
+ warnings,
586
+ };
587
+ }
588
+
589
+ async function realize(
590
+ companionPath: string,
591
+ plan: Plan,
592
+ options: CreateWorktreesOptions,
593
+ git: GitRunner,
594
+ deps: WorktreeDeps,
595
+ warnings: string[],
596
+ ): Promise<WorktreeRepositoryResult> {
597
+ const result: WorktreeRepositoryResult = {
598
+ repository: plan.repository,
599
+ checkout: plan.checkout,
600
+ path: plan.target,
601
+ branch: plan.branch,
602
+ action: plan.reuse ? "reused" : "created",
603
+ install: { command: null, outcome: "skipped" },
604
+ wrap: { runtimes: [], outcome: "skipped" },
605
+ index: { outcome: "skipped" },
606
+ missingEnv: [],
607
+ };
608
+ if (!plan.reuse) {
609
+ const failure = await addWorktree(git, plan);
610
+ if (failure) {
611
+ return {
612
+ ...result,
613
+ install: { ...result.install, reason: NOT_CREATED },
614
+ wrap: { ...result.wrap, reason: NOT_CREATED },
615
+ index: { outcome: "skipped", reason: NOT_CREATED },
616
+ error: failure,
617
+ };
618
+ }
619
+ }
620
+ // The main checkout's id: a session moved here keeps its `MATE_REPOSITORY_ID`.
621
+ const repository = { id: plan.repositoryId, path: plan.target };
622
+ try {
623
+ await (deps.writeLink ?? writeRepoLocalRegistryEntry)(
624
+ plan.target,
625
+ companionPath,
626
+ repository,
627
+ "existing",
628
+ );
629
+ result.wrap = await wrapWorktree(companionPath, plan.checkout, repository, deps);
630
+ if (result.wrap.outcome === "failed") {
631
+ const message = `wrapping the worktree failed: ${result.wrap.reason}`;
632
+ // A reused worktree still wrapped from before stays usable; only refreshing it failed.
633
+ if (plan.reuse && (await stillWrapped(plan.target, result.wrap.runtimes, deps))) {
634
+ warnings.push(`${plan.repository}: ${message}; its earlier wrap stays`);
635
+ } else {
636
+ result.error = message;
637
+ }
638
+ }
639
+ } catch (error) {
640
+ result.error = `linking the worktree failed: ${errorMessage(error)}`;
641
+ result.wrap.reason = "worktree not linked";
642
+ }
643
+ const command = await installCommand(plan.target);
644
+ result.install.command = command ? command.join(" ") : null;
645
+ if (plan.reuse) result.install.reason = "reused worktree";
646
+ else if (!options.install) result.install.reason = "--no-install";
647
+ else if (!command) result.install.reason = "no lockfile";
648
+ else {
649
+ const ok = await (deps.install ?? runInstall)(plan.target, command, options.streamInstall);
650
+ result.install.outcome = ok ? "ok" : "failed";
651
+ if (!ok) result.error ??= `${command.join(" ")} failed`;
652
+ }
653
+ // The caller indexes after install, regardless of `--no-install`: the index is not a dependency install.
654
+ result.missingEnv = await missingEnvFiles(git, plan.checkout, plan.target);
655
+ return result;
656
+ }
657
+
658
+ async function stillWrapped(
659
+ worktree: string,
660
+ runtimes: readonly WrapRuntime[],
661
+ deps: WorktreeDeps,
662
+ ): Promise<boolean> {
663
+ try {
664
+ const own = await wrappedRuntimes(worktree, deps);
665
+ return runtimes.every((runtime) => own.includes(runtime));
666
+ } catch {
667
+ return false;
668
+ }
669
+ }
670
+
671
+ /** Whether `cwd` is the worktree or lies inside it. */
672
+ async function holds(worktree: string, cwd: string): Promise<boolean> {
673
+ const relative = path.relative(worktree, await canonical(cwd));
674
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
675
+ }
676
+
677
+ /** Why a worktree must stay, or null when it is clean and every commit is on a remote. */
678
+ async function keepReason(
679
+ git: GitRunner,
680
+ listed: WorktreeEntry,
681
+ cwd: string,
682
+ ): Promise<string | null> {
683
+ if (listed.locked) return "locked";
684
+ if (listed.stale) return `stale worktree entry (${listed.stale}); run \`git worktree prune\``;
685
+ const worktree = listed.path;
686
+ if (await holds(worktree, cwd)) return "in use (current directory)";
687
+ const status = await git(worktree, ["status", "--porcelain"]);
688
+ if (status.code !== 0) return `cannot read its status: ${status.stderr.trim()}`;
689
+ if (status.stdout.trim()) return "uncommitted changes or untracked files";
690
+ const unpushed = await git(worktree, ["log", "--oneline", "HEAD", "--not", "--remotes"]);
691
+ if (unpushed.code !== 0) return `cannot read its commits: ${unpushed.stderr.trim()}`;
692
+ if (unpushed.stdout.trim()) return "commits on no remote";
693
+ return null;
694
+ }
695
+
696
+ /** Recorded Delivery Branches per Working Repository; not-applicable deliveries name none. */
697
+ async function recordedBranches(
698
+ companionPath: string,
699
+ changes: readonly string[],
700
+ warnings: string[],
701
+ ): Promise<Map<string, Set<string>>> {
702
+ const byRepository = new Map<string, Set<string>>();
703
+ for (const change of changes) {
704
+ // oxlint-disable-next-line no-await-in-loop -- a few small files, in order
705
+ const location = await locateChange(companionPath, change);
706
+ if (!location) continue;
707
+ let record: DeliveryRecord | null;
708
+ try {
709
+ // oxlint-disable-next-line no-await-in-loop -- a few small files, in order
710
+ record = await readDeliveryRecord(location.dir);
711
+ } catch (error) {
712
+ warnings.push(`${change}: cannot read its Delivery Record: ${errorMessage(error)}`);
713
+ continue;
714
+ }
715
+ for (const delivery of record?.deliveries ?? []) {
716
+ if (!delivery.branch || delivery.notApplicable) continue;
717
+ const branches = byRepository.get(delivery.repository) ?? new Set<string>();
718
+ branches.add(delivery.branch);
719
+ byRepository.set(delivery.repository, branches);
720
+ }
721
+ }
722
+ return byRepository;
723
+ }
724
+
725
+ async function pruneRepository(
726
+ companionPath: string,
727
+ worksetId: string,
728
+ repository: string,
729
+ branches: ReadonlySet<string>,
730
+ git: GitRunner,
731
+ deps: WorktreeDeps,
732
+ result: PruneResult,
733
+ ): Promise<void> {
734
+ const linked = await linkedCheckout(companionPath, repository, git);
735
+ if (!linked) return;
736
+ const entries = await listWorktrees(git, linked.path);
737
+ const main = entries?.[0];
738
+ if (!main) {
739
+ result.warnings.push(`${repository}: cannot list the worktrees of ${linked.path}`);
740
+ return;
741
+ }
742
+ // The first entry is the main checkout; a detached HEAD has no branch and never matches.
743
+ const candidates = entries
744
+ .slice(1)
745
+ .filter((entry) => entry.branch !== null && branches.has(entry.branch));
746
+ for (const listed of candidates) {
747
+ // oxlint-disable-next-line no-await-in-loop -- Git operations on one checkout, one at a time
748
+ await pruneWorktree(
749
+ companionPath,
750
+ { worksetId, repository, main: main.path, linked, listed },
751
+ git,
752
+ deps,
753
+ result,
754
+ );
755
+ }
756
+ }
757
+
758
+ interface PruneCandidate {
759
+ worksetId: string;
760
+ repository: string;
761
+ /** The main checkout's path. */
762
+ main: string;
763
+ linked: LinkedRepository;
764
+ listed: WorktreeEntry;
765
+ }
766
+
767
+ async function pruneWorktree(
768
+ companionPath: string,
769
+ candidate: PruneCandidate,
770
+ git: GitRunner,
771
+ deps: WorktreeDeps,
772
+ result: PruneResult,
773
+ ): Promise<void> {
774
+ const { worksetId, repository, main, linked, listed } = candidate;
775
+ const target = listed.path;
776
+ const entry = { workset: worksetId, repository, path: target };
777
+ const cwd = (deps.cwd ?? process.cwd)();
778
+ const reason = await keepReason(git, listed, cwd);
779
+ if (reason) {
780
+ result.kept.push({ ...entry, reason });
781
+ return;
782
+ }
783
+ // Unwrap first: machine-local state keyed by its path (Claude local-scope MCP) must not outlive it.
784
+ try {
785
+ await (deps.unwrap ?? cleanupWorkingRepository)(target, [companionPath]);
786
+ } catch (error) {
787
+ result.kept.push({ ...entry, reason: `removing its wrap failed: ${errorMessage(error)}` });
788
+ return;
789
+ }
790
+ const removed = await git(main, ["worktree", "remove", target]);
791
+ if (removed.code === 0) {
792
+ result.removed.push(entry);
793
+ return;
794
+ }
795
+ const refused = removed.stderr.trim() || "git refused";
796
+ // Kept, so it gets its guardrails back.
797
+ const rewrap = await wrapWorktree(companionPath, main, { id: linked.id, path: target }, deps);
798
+ result.kept.push({
799
+ ...entry,
800
+ reason:
801
+ rewrap.outcome === "failed"
802
+ ? `${refused}; re-wrapping it failed, run \`${FRAMEWORK_NAME} wrap\` there: ${rewrap.reason}`
803
+ : refused,
804
+ });
805
+ }
806
+
807
+ /**
808
+ * Removes the worktrees of the given (Done) Worksets that are clean and fully pushed,
809
+ * without `--force`, and never deletes a branch. A worktree belongs to a Workset when it is
810
+ * a linked worktree with a Delivery Branch of the Workset's changes checked out, wherever
811
+ * it lives. The main checkout and a worktree holding the working directory stay, as does
812
+ * every other worktree. Each is unwrapped before removal.
813
+ */
814
+ export async function pruneWorksetWorktrees(
815
+ companionPath: string,
816
+ done: readonly PruneTarget[],
817
+ deps: WorktreeDeps = {},
818
+ ): Promise<PruneResult> {
819
+ const git = deps.git ?? runGit;
820
+ const result: PruneResult = { removed: [], kept: [], warnings: [] };
821
+ for (const workset of done) {
822
+ // oxlint-disable-next-line no-await-in-loop -- Worksets one at a time
823
+ const branches = await recordedBranches(companionPath, workset.changes, result.warnings);
824
+ for (const [repository, names] of branches) {
825
+ // oxlint-disable-next-line no-await-in-loop -- Git operations on shared checkouts, one at a time
826
+ await pruneRepository(companionPath, workset.id, repository, names, git, deps, result);
827
+ }
828
+ }
829
+ return result;
830
+ }