@uniqbit/mate-core 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (286) 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 +305 -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.ts +25 -14
  163. package/studio-dist/client/assets/app-D9cw6szy.css +2 -0
  164. package/studio-dist/client/assets/artifacts-WD2ZXYrx.js +1 -0
  165. package/studio-dist/client/assets/button-Br0O1sXw.js +1 -0
  166. package/studio-dist/client/assets/combobox-DA7RAUUZ.js +1 -0
  167. package/studio-dist/client/assets/companion-view-CrabvxS8.js +1 -0
  168. package/studio-dist/client/assets/factory-DGS0E16C.js +6 -0
  169. package/studio-dist/client/assets/fields-6aXBpFhJ.js +1 -0
  170. package/studio-dist/client/assets/getting-started-Clde4w6P.js +1 -0
  171. package/studio-dist/client/assets/getting-started-D6kgWwWZ.js +1 -0
  172. package/studio-dist/client/assets/getting-started._topic-BiunccbT.js +1 -0
  173. package/studio-dist/client/assets/getting-started.index-DpiNoGw8.js +1 -0
  174. package/studio-dist/client/assets/graph-B_TCBVbu.js +2 -0
  175. package/studio-dist/client/assets/graph-canvas-Ba37Y5AE.js +3242 -0
  176. package/studio-dist/client/assets/guides-Du_RtJxP.js +1 -0
  177. package/studio-dist/client/assets/index-Df8L1LQa.js +40 -0
  178. package/studio-dist/client/assets/jsx-runtime-MZURdZre.js +1 -0
  179. package/studio-dist/client/assets/markdown-view-BOX6x0rL.js +1 -0
  180. package/studio-dist/client/assets/panel-dbmCx7Mx.js +1 -0
  181. package/studio-dist/client/assets/queries-RvHeXY12.js +1 -0
  182. package/studio-dist/client/assets/react-3QStrcDO.js +27 -0
  183. package/studio-dist/client/assets/report-url-XRL0x1SY.js +1 -0
  184. package/studio-dist/client/assets/reports-r3IK7Doz.js +1 -0
  185. package/studio-dist/client/assets/routes-C0A5LTFc.js +1 -0
  186. package/studio-dist/client/assets/select-CnaMd617.js +1 -0
  187. package/studio-dist/client/assets/skills-CzjzHpBT.js +1 -0
  188. package/studio-dist/client/assets/specs-B0ldF_6J.js +1 -0
  189. package/studio-dist/client/assets/specs-view-BnCLA0gW.js +1 -0
  190. package/studio-dist/client/assets/spinner-Dcm3fqK1.js +1 -0
  191. package/studio-dist/client/assets/steps-C0p2N1Pb.js +1 -0
  192. package/studio-dist/client/assets/store-Dw34catY.js +1 -0
  193. package/studio-dist/client/assets/studio-Cpz_HRHp.js +100 -0
  194. package/studio-dist/client/assets/studio-queries-ibmpFo6R.js +2 -0
  195. package/studio-dist/client/assets/usage-C2QJ_0IZ.js +55 -0
  196. package/studio-dist/client/assets/useAnchoredPopupScrollLock-Bj-FWb8z.js +1 -0
  197. package/studio-dist/client/assets/useMutation-aAr2uiay.js +1 -0
  198. package/studio-dist/client/assets/useSelector-AYcH7lB0.js +2 -0
  199. package/studio-dist/client/assets/vault-BGcxkSIY.js +1 -0
  200. package/studio-dist/client/assets/warnings-R1cE1rLf.js +1 -0
  201. package/studio-dist/client/assets/workflow-C2qTrMDH.js +1 -0
  202. package/studio-dist/server/assets/__23tanstack-start-server-fn-resolver-Bn896ZYj.js +122 -0
  203. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +102 -35
  204. package/studio-dist/server/assets/{actions-Bvgj9eb8.js → actions-DYSv-9VV.js} +10 -4
  205. package/studio-dist/server/assets/artifacts-DnF9L3dZ.js +216 -0
  206. package/studio-dist/server/assets/{button-CIJqAhni.js → button-CgOIVdmD.js} +13 -1702
  207. package/studio-dist/server/assets/combobox-DV_s9W0s.js +483 -0
  208. package/studio-dist/server/assets/{companion-view-DISASvdJ.js → companion-view-BKVXD3TO.js} +3 -3
  209. package/studio-dist/server/assets/companions-C7fctnU9.js +31 -0
  210. package/studio-dist/server/assets/{createServerRpc-tK2lE9R2.js → createServerRpc-bFKFpGFG.js} +1 -1
  211. package/studio-dist/server/assets/{factory-DUTa0eDs.js → factory-C7Ybg0xG.js} +1256 -353
  212. package/studio-dist/server/assets/{factory-DGPmNGbo.js → factory-Df5uAHjb.js} +53 -6
  213. package/studio-dist/server/assets/fields-BbieQTD0.js +1190 -0
  214. package/studio-dist/server/assets/getting-started-B136TP57.js +4 -0
  215. package/studio-dist/server/assets/getting-started-CRxMWorQ.js +67 -0
  216. package/studio-dist/server/assets/getting-started._topic-DJKQAzYl.js +13 -0
  217. package/studio-dist/server/assets/getting-started.index-D84gec1t.js +13 -0
  218. package/studio-dist/server/assets/graph-CSje3029.js +801 -0
  219. package/studio-dist/server/assets/graph-DDZzXM1L.js +16 -0
  220. package/studio-dist/server/assets/graph-canvas-22bWB5-2.js +21066 -0
  221. package/studio-dist/server/assets/graph-wire-BdSUx0G5.js +58 -0
  222. package/studio-dist/server/assets/guides-D9dk1Frq.js +13 -0
  223. package/studio-dist/server/assets/guides-IE-19POz.js +5 -0
  224. package/studio-dist/server/assets/guides.server-vcYRY5wx.js +66 -0
  225. package/studio-dist/server/assets/jsx-runtime-Bt0s0YKS.js +451 -0
  226. package/studio-dist/server/assets/{markdown-view-Bn7xPdks.js → markdown-view-BR8dJ7aR.js} +28 -9
  227. package/studio-dist/server/assets/{panel-3Jmn4awF.js → panel-BR_t9iMM.js} +4 -4
  228. package/studio-dist/server/assets/queries-DWoTin-q.js +32 -0
  229. package/studio-dist/server/assets/react-CdqSUhaL.js +89 -0
  230. package/studio-dist/server/assets/redirect-BaZ_QyqF.js +39 -0
  231. package/studio-dist/server/assets/report-url-BUXPcE_8.js +9 -0
  232. package/studio-dist/server/assets/{reports-D6YMqhnO.js → reports-CQ9qQ1-n.js} +9 -10
  233. package/studio-dist/server/assets/{reports-C06RXVE2.js → reports-dYDEoBeq.js} +3 -3
  234. package/studio-dist/server/assets/{router-C8MGqlAY.js → router-DkRHNTpE.js} +787 -2862
  235. package/studio-dist/server/assets/{routes-BcFgvqf7.js → routes-B6GfOew4.js} +22 -171
  236. package/studio-dist/server/assets/{search-JAKurDNh.js → search-BJnWLfkG.js} +21 -2
  237. package/studio-dist/server/assets/select-Af7Wibii.js +1609 -0
  238. package/studio-dist/server/assets/{shell-DS3wUexh.js → shell-Hq-hXgnT.js} +6 -5
  239. package/studio-dist/server/assets/{skills-BEnOxiDl.js → skills-B7nEuVbx.js} +9 -8
  240. package/studio-dist/server/assets/{skills-CtrBAtX3.js → skills-B_YYL7q8.js} +3 -3
  241. package/studio-dist/server/assets/specs-BpLUFntA.js +51 -0
  242. package/studio-dist/server/assets/specs-view-0peMVd22.js +426 -0
  243. package/studio-dist/server/assets/spinner-CdwJW4VB.js +20 -0
  244. package/studio-dist/server/assets/{steps-Dq_CwY_s.js → steps-D56DApvK.js} +1 -1
  245. package/studio-dist/server/assets/store-Cs17okNG.js +280 -0
  246. package/studio-dist/server/assets/studio-CAcKp3bM.js +10340 -0
  247. package/studio-dist/server/assets/studio-queries-BtRGzDdh.js +1451 -0
  248. package/studio-dist/server/assets/usage-COdjd1gD.js +25570 -0
  249. package/studio-dist/server/assets/usage-f6pqE1tm.js +24 -0
  250. package/studio-dist/server/assets/useAnchoredPopupScrollLock-DlBKHRw7.js +756 -0
  251. package/studio-dist/server/assets/useMutation-DzTZGenE.js +690 -0
  252. package/studio-dist/server/assets/{__23tanstack-start-server-fn-resolver-M2GBs8s3.js → useSelector-DUmCUXAs.js} +4 -668
  253. package/studio-dist/server/assets/{vault-Fvxt2Tzl.js → vault-BDuIUq0F.js} +8 -5
  254. package/studio-dist/server/assets/{vault-BmWnryh3.js → vault-BVLp6zu3.js} +3 -3
  255. package/studio-dist/server/assets/{views-BgYa-za2.js → views-flRUr21z.js} +4 -4
  256. package/studio-dist/server/assets/{warnings-DzR6fyZh.js → warnings-CDy9pdgL.js} +3 -2
  257. package/studio-dist/server/assets/{delivery-path-C29fBynY.js → workflow-D9GKI2EV.js} +132 -106
  258. package/studio-dist/server/server.js +582 -8
  259. package/src/cli/commands/report/collector.ts +0 -288
  260. package/studio-dist/client/assets/app-CdPiFv59.css +0 -2
  261. package/studio-dist/client/assets/button-BIIHE0EQ.js +0 -3
  262. package/studio-dist/client/assets/companion-view-DM6YyXaR.js +0 -1
  263. package/studio-dist/client/assets/delivery-path-DELxj0Av.js +0 -1
  264. package/studio-dist/client/assets/factory-BZy0E8ty.js +0 -4
  265. package/studio-dist/client/assets/index-B3wkMzjA.js +0 -40
  266. package/studio-dist/client/assets/markdown-view-pQ2Qp_i5.js +0 -1
  267. package/studio-dist/client/assets/panel-CbajlC3p.js +0 -1
  268. package/studio-dist/client/assets/prepaint-CwSrpdFA.js +0 -27
  269. package/studio-dist/client/assets/react-CN2GSx7x.js +0 -1
  270. package/studio-dist/client/assets/reports-DllhYQ5_.js +0 -1
  271. package/studio-dist/client/assets/rolldown-runtime-WkwZ5CU-.js +0 -1
  272. package/studio-dist/client/assets/routes-COm-G3mK.js +0 -1
  273. package/studio-dist/client/assets/skills-DmWAy-jZ.js +0 -1
  274. package/studio-dist/client/assets/specs-BG3Wi3ln.js +0 -1
  275. package/studio-dist/client/assets/steps-DFsH3Neu.js +0 -1
  276. package/studio-dist/client/assets/vault-B2q1nBY5.js +0 -1
  277. package/studio-dist/client/assets/warnings-BSXIyuSQ.js +0 -1
  278. package/studio-dist/client/assets/workflow-DlsQD6Hc.js +0 -1
  279. package/studio-dist/server/assets/companions-BYbHWKOZ.js +0 -15
  280. package/studio-dist/server/assets/createServerFn-F5sAOF8V.js +0 -459
  281. package/studio-dist/server/assets/prepaint-DJfTQ_VH.js +0 -45
  282. package/studio-dist/server/assets/react-Ce6dj15C.js +0 -46
  283. package/studio-dist/server/assets/rolldown-runtime-DYf_mQCB.js +0 -34
  284. package/studio-dist/server/assets/specs-C8rv34-5.js +0 -211
  285. package/studio-dist/server/assets/studio-BeltxxKt.js +0 -216
  286. package/studio-dist/server/assets/workflow-liRYecHk.js +0 -73
@@ -0,0 +1,157 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ import { parse, stringify } from "yaml";
5
+
6
+ import { parseRemote, repositoryPath } from "../delivery/forge";
7
+ import { KeyedSerial } from "../factory/keyed-serial";
8
+
9
+ /**
10
+ * The companion's machine-local list of Working Repositories a Workset may name: a
11
+ * `repositories` list of clone URLs in `factory.local.yaml` at the companion's root. It is
12
+ * excluded from Git locally and never shared, committed or published.
13
+ */
14
+
15
+ export const FACTORY_LOCAL_FILE = "factory.local.yaml";
16
+
17
+ export interface LocalRepositories {
18
+ /** Clone URLs in file order; empty when the file is missing or unusable. */
19
+ urls: string[];
20
+ /** Why the file is unusable, naming it and the entry; the list is then empty. */
21
+ problem: string | null;
22
+ }
23
+
24
+ /** `org/repository` of a clone URL; null when it names none. */
25
+ export function repositoryIdentityOf(url: string): string | null {
26
+ const parsed = parseRemote(url);
27
+ return parsed ? repositoryPath(parsed) : null;
28
+ }
29
+
30
+ const fileOf = (companionPath: string) => path.join(companionPath, FACTORY_LOCAL_FILE);
31
+
32
+ const isMissing = (error: unknown) => (error as NodeJS.ErrnoException).code === "ENOENT";
33
+
34
+ const unusable = (reason: string) => ({
35
+ data: {} as Record<string, unknown>,
36
+ urls: [] as string[],
37
+ problem: `${FACTORY_LOCAL_FILE} ${reason}`,
38
+ });
39
+
40
+ /** The parsed file, or its problem; `data` keeps every key, known or not. */
41
+ async function load(
42
+ companionPath: string,
43
+ ): Promise<{ data: Record<string, unknown>; urls: string[]; problem: string | null }> {
44
+ let text: string;
45
+ try {
46
+ text = await fs.readFile(fileOf(companionPath), "utf8");
47
+ } catch (error) {
48
+ if (isMissing(error)) return { data: {}, urls: [], problem: null };
49
+ return unusable(`could not be read: ${(error as Error).message}`);
50
+ }
51
+ let data: unknown;
52
+ try {
53
+ data = parse(text) ?? {};
54
+ } catch {
55
+ return unusable("is not valid YAML");
56
+ }
57
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
58
+ return unusable("must be a mapping with a `repositories` list");
59
+ }
60
+ const record = data as Record<string, unknown>;
61
+ const entries = record.repositories ?? [];
62
+ if (!Array.isArray(entries))
63
+ return { ...unusable("`repositories` must be a list"), data: record };
64
+ for (const entry of entries) {
65
+ if (typeof entry !== "string" || repositoryIdentityOf(entry) === null) {
66
+ return {
67
+ ...unusable(`entry ${JSON.stringify(entry)} names no org/repository`),
68
+ data: record,
69
+ };
70
+ }
71
+ }
72
+ return { data: record, urls: (entries as string[]).map((entry) => entry.trim()), problem: null };
73
+ }
74
+
75
+ export async function readLocalRepositories(companionPath: string): Promise<LocalRepositories> {
76
+ const { urls, problem } = await load(companionPath);
77
+ return { urls, problem };
78
+ }
79
+
80
+ /** One writer per file at a time, so two Studio requests cannot lose each other's change. */
81
+ const writers = new KeyedSerial();
82
+
83
+ async function save(
84
+ companionPath: string,
85
+ data: Record<string, unknown>,
86
+ urls: string[],
87
+ ): Promise<void> {
88
+ const file = fileOf(companionPath);
89
+ const temporary = `${file}.${process.pid}.tmp`;
90
+ await fs.writeFile(temporary, stringify({ ...data, repositories: urls }), "utf8");
91
+ await fs.rename(temporary, file);
92
+ }
93
+
94
+ /**
95
+ * Adds the first line to the companion's `.git/info/exclude` so the file leaves no tracked
96
+ * change. Returns a warning when it could not, and nothing outside a Git repository.
97
+ */
98
+ export async function excludeLocalFile(companionPath: string): Promise<string | null> {
99
+ const git = path.join(companionPath, ".git");
100
+ let stats;
101
+ try {
102
+ stats = await fs.stat(git);
103
+ } catch {
104
+ return null;
105
+ }
106
+ if (!stats.isDirectory()) {
107
+ return `${FACTORY_LOCAL_FILE} could not be excluded from Git: the companion is a linked worktree`;
108
+ }
109
+ const exclude = path.join(git, "info", "exclude");
110
+ try {
111
+ const current = await fs.readFile(exclude, "utf8").catch((error: unknown) => {
112
+ if (isMissing(error)) return "";
113
+ throw error;
114
+ });
115
+ if (current.split("\n").some((line) => line.trim() === FACTORY_LOCAL_FILE)) return null;
116
+ await fs.mkdir(path.dirname(exclude), { recursive: true });
117
+ const separator = current === "" || current.endsWith("\n") ? "" : "\n";
118
+ await fs.writeFile(exclude, `${current}${separator}${FACTORY_LOCAL_FILE}\n`, "utf8");
119
+ return null;
120
+ } catch {
121
+ return `${FACTORY_LOCAL_FILE} could not be added to .git/info/exclude; keep it out of commits yourself`;
122
+ }
123
+ }
124
+
125
+ export interface LocalAdd {
126
+ /** False when the repository was already listed. */
127
+ added: boolean;
128
+ warning: string | null;
129
+ }
130
+
131
+ /** Lists a clone URL; one already listed under the same `org/repository` is left as it is. */
132
+ export function addLocalRepository(companionPath: string, url: string): Promise<LocalAdd> {
133
+ return writers.run(fileOf(companionPath), async () => {
134
+ const { data, urls, problem } = await load(companionPath);
135
+ if (problem) throw new Error(problem);
136
+ const identity = repositoryIdentityOf(url);
137
+ if (identity === null) throw new Error(`${url} names no org/repository`);
138
+ if (urls.some((entry) => repositoryIdentityOf(entry) === identity)) {
139
+ return { added: false, warning: null };
140
+ }
141
+ const warning = await excludeLocalFile(companionPath);
142
+ await save(companionPath, data, [...urls, url.trim()]);
143
+ return { added: true, warning };
144
+ });
145
+ }
146
+
147
+ /** Removes the entry for `identity`; false when none was listed. */
148
+ export function removeLocalRepository(companionPath: string, identity: string): Promise<boolean> {
149
+ return writers.run(fileOf(companionPath), async () => {
150
+ const { data, urls, problem } = await load(companionPath);
151
+ if (problem) throw new Error(problem);
152
+ const kept = urls.filter((entry) => repositoryIdentityOf(entry) !== identity);
153
+ if (kept.length === urls.length) return false;
154
+ await save(companionPath, data, kept);
155
+ return true;
156
+ });
157
+ }
@@ -138,6 +138,15 @@ export function toWorksetRecord(fileId: string, document: unknown): WorksetRecor
138
138
  };
139
139
  }
140
140
 
141
+ /** One record file: the record, or why it is not one. */
142
+ async function readWorksetFile(dir: string, id: string): Promise<WorksetRecord | string> {
143
+ try {
144
+ return toWorksetRecord(id, parse(await fs.readFile(path.join(dir, `${id}.yaml`), "utf8")));
145
+ } catch (error) {
146
+ return `cannot be read: ${errorMessage(error)}`;
147
+ }
148
+ }
149
+
141
150
  /** Every record, sorted by id; an unreadable one is a problem, never a reason to stop. */
142
151
  export async function readWorksets(companionPath: string): Promise<WorksetListing> {
143
152
  const dir = worksetsDirOf(companionPath);
@@ -153,16 +162,10 @@ export async function readWorksets(companionPath: string): Promise<WorksetListin
153
162
  .filter((name) => name.endsWith(".yaml"))
154
163
  .toSorted()
155
164
  .map(async (entry): Promise<WorksetRecord | WorksetProblem> => {
156
- const relative = path.join(WORKSETS_RELATIVE_DIR, entry);
157
- try {
158
- const record = toWorksetRecord(
159
- entry.slice(0, -".yaml".length),
160
- parse(await fs.readFile(path.join(dir, entry), "utf8")),
161
- );
162
- return typeof record === "string" ? { path: relative, reason: record } : record;
163
- } catch (error) {
164
- return { path: relative, reason: `cannot be read: ${errorMessage(error)}` };
165
- }
165
+ const record = await readWorksetFile(dir, entry.slice(0, -".yaml".length));
166
+ return typeof record === "string"
167
+ ? { path: path.join(WORKSETS_RELATIVE_DIR, entry), reason: record }
168
+ : record;
166
169
  }),
167
170
  );
168
171
  return {
@@ -176,7 +179,10 @@ export async function findWorkset(
176
179
  companionPath: string,
177
180
  id: string,
178
181
  ): Promise<WorksetRecord | undefined> {
179
- return (await readWorksets(companionPath)).worksets.find((entry) => entry.id === id);
182
+ // Reads only this record's file; an id that is no file name has none.
183
+ if (!isWorksetId(id)) return undefined;
184
+ const record = await readWorksetFile(worksetsDirOf(companionPath), id);
185
+ return typeof record === "string" ? undefined : record;
180
186
  }
181
187
 
182
188
  export type WorksetResolution =
@@ -437,6 +443,14 @@ export async function writeWorkset(companionPath: string, record: WorksetRecord)
437
443
  await fs.rename(temp, path.join(dir, `${record.id}.yaml`));
438
444
  }
439
445
 
446
+ /** Deletes a Workset's record; a record already gone is no error. */
447
+ export async function removeWorkset(companionPath: string, id: string): Promise<void> {
448
+ if (!isWorksetId(id)) {
449
+ throw new WorksetError(`Workset identifier ${JSON.stringify(id)} is not a kebab-case name`);
450
+ }
451
+ await fs.rm(path.join(worksetsDirOf(companionPath), `${id}.yaml`), { force: true });
452
+ }
453
+
440
454
  const NEXT_STAGE: Partial<Record<PreProposeStage, PreProposeStage>> = {
441
455
  "clarify-intent": "explore",
442
456
  explore: "ready",
@@ -1,55 +1,148 @@
1
1
  import fs from "node:fs";
2
2
 
3
3
  import { workingRepoGit } from "../delivery/branches";
4
- import { parseRemote } from "../delivery/forge";
4
+ import { repositoryPath } from "../delivery/forge";
5
5
  import { readCompanionRegistry } from "../orchestrator/repository-link";
6
+ import { linkedCheckoutsOf } from "../orchestrator/umbrella-checkouts";
7
+ import { gitTokenKeyOf } from "../factory/git-credential-store";
8
+ import { readLocalRepositories, repositoryIdentityOf } from "./factory-local";
6
9
 
7
10
  /** Factory mode's configured clone URLs, comma-separated, as the appliance hands them to Studio. */
8
11
  export const FACTORY_REPOSITORIES_ENV = "MATE_FACTORY_REPOSITORIES";
9
12
 
10
- /** `org/repository` of a remote URL, or null when it is not a forge URL. */
11
- export function identityOf(url: string): string | null {
12
- const parsed = parseRemote(url);
13
- return parsed ? `${parsed.owner}/${parsed.repo}` : null;
13
+ /** Where a repository a Workset may name comes from; a linked origin wins over the list, the list over the environment. */
14
+ export type RepositorySourceKind = "linked" | "list" | "environment";
15
+
16
+ interface Source {
17
+ url: string;
18
+ kind: RepositorySourceKind;
19
+ }
20
+
21
+ const readOrigin = (checkout: string) => workingRepoGit(checkout).remoteUrl();
22
+
23
+ interface LinkedRemote {
24
+ /** The registry ID the companion links the checkout under. */
25
+ id: string;
26
+ identity: string;
27
+ remote: string;
28
+ /** The registry entry's own folder, not one of an Umbrella Repository's children. */
29
+ own: boolean;
14
30
  }
15
31
 
16
32
  /**
17
- * Where each Working Repository a Workset may name is cloned from, by `org/repository`:
18
- * the `origin` of each repository linked to the companion whose path exists on this
19
- * machine, then the configured factory repositories. A linked origin wins.
33
+ * Each checkout linked to the companion whose path exists here and has a forge `origin`,
34
+ * an Umbrella Repository's children included.
20
35
  */
21
- export async function repositorySources(
22
- companionPath: string,
23
- env: NodeJS.ProcessEnv = process.env,
24
- ): Promise<Map<string, string>> {
25
- let repos: { path: string }[] = [];
36
+ async function linkedRemotes(companionPath: string): Promise<LinkedRemote[]> {
37
+ let repos: { id: string; path: string }[] = [];
26
38
  try {
27
39
  repos = (await readCompanionRegistry(companionPath)).repos;
28
40
  } catch (error) {
29
41
  if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
30
42
  }
31
43
  const linked = await Promise.all(
32
- repos.map(async (repo): Promise<[string, string] | null> => {
33
- if (!fs.existsSync(repo.path)) return null;
34
- const remote = await workingRepoGit(repo.path).remoteUrl();
35
- const identity = remote ? identityOf(remote) : null;
36
- return identity && remote ? [identity, remote] : null;
44
+ repos.map(async (repo): Promise<LinkedRemote[]> => {
45
+ if (!fs.existsSync(repo.path)) return [];
46
+ return (await linkedCheckoutsOf(repo, readOrigin)).flatMap(
47
+ ({ path: checkout, origin, remote }) =>
48
+ origin && remote
49
+ ? [
50
+ {
51
+ id: repo.id,
52
+ identity: repositoryPath(remote),
53
+ remote: origin,
54
+ own: checkout === repo.path,
55
+ },
56
+ ]
57
+ : [],
58
+ );
37
59
  }),
38
60
  );
39
- const sources = new Map<string, string>();
40
- for (const entry of linked) if (entry && !sources.has(entry[0])) sources.set(entry[0], entry[1]);
41
- for (const url of (env[FACTORY_REPOSITORIES_ENV] ?? "").split(",")) {
42
- const trimmed = url.trim();
43
- const identity = trimmed ? identityOf(trimmed) : null;
44
- if (identity && !sources.has(identity)) sources.set(identity, trimmed);
61
+ return linked.flat();
62
+ }
63
+
64
+ function sourcesOf(
65
+ linked: LinkedRemote[],
66
+ listed: string[],
67
+ env: NodeJS.ProcessEnv,
68
+ ): Map<string, Source> {
69
+ const sources = new Map<string, Source>();
70
+ for (const { identity, remote } of linked) {
71
+ if (!sources.has(identity)) sources.set(identity, { url: remote, kind: "linked" });
45
72
  }
73
+ const add = (url: string, kind: RepositorySourceKind) => {
74
+ const trimmed = url.trim();
75
+ const identity = trimmed ? repositoryIdentityOf(trimmed) : null;
76
+ if (identity && !sources.has(identity)) sources.set(identity, { url: trimmed, kind });
77
+ };
78
+ for (const url of listed) add(url, "list");
79
+ for (const url of (env[FACTORY_REPOSITORIES_ENV] ?? "").split(",")) add(url, "environment");
46
80
  return sources;
47
81
  }
48
82
 
83
+ /**
84
+ * Where each Working Repository a Workset may name is cloned from, by `org/repository`:
85
+ * the `origin` of each repository linked to the companion whose path exists on this
86
+ * machine, an Umbrella Repository's children included, then the companion's
87
+ * `factory.local.yaml` list, then the configured factory repositories. The first wins.
88
+ */
89
+ export async function repositorySources(
90
+ companionPath: string,
91
+ env: NodeJS.ProcessEnv = process.env,
92
+ ): Promise<Map<string, string>> {
93
+ const [linked, local] = await Promise.all([
94
+ linkedRemotes(companionPath),
95
+ readLocalRepositories(companionPath),
96
+ ]);
97
+ return new Map(
98
+ [...sourcesOf(linked, local.urls, env)].map(([identity, source]) => [identity, source.url]),
99
+ );
100
+ }
101
+
49
102
  /** The `org/repository` names a new Workset may name, sorted. */
50
103
  export async function linkedRepositoryIdentities(
51
104
  companionPath: string,
52
105
  env: NodeJS.ProcessEnv = process.env,
53
106
  ): Promise<string[]> {
54
- return [...(await repositorySources(companionPath, env)).keys()].toSorted();
107
+ return (await linkedRepositoryCatalog(companionPath, env)).identities;
108
+ }
109
+
110
+ export interface LinkedRepositoryCatalog {
111
+ /** The `org/repository` names a new Workset may name, sorted. */
112
+ identities: string[];
113
+ /** `org/repository` of each linked repository by its registry ID. */
114
+ aliases: Map<string, string>;
115
+ /** Where each of `identities` comes from, so a picker offers removal only for the list's own. */
116
+ kinds: Map<string, RepositorySourceKind>;
117
+ /** `host/org` Git token key of each of `identities`' HTTP(S) clone URL; SSH and organization-less URLs take no token and are left out. */
118
+ keys: Map<string, string>;
119
+ /** Why `factory.local.yaml` is unusable, naming the file and the entry; null when it is fine. */
120
+ problem: string | null;
121
+ }
122
+
123
+ /**
124
+ * {@link linkedRepositoryIdentities} plus the registry IDs, from one remote lookup per
125
+ * checkout. An Umbrella Repository's ID stands for several repositories, so it maps to none.
126
+ */
127
+ export async function linkedRepositoryCatalog(
128
+ companionPath: string,
129
+ env: NodeJS.ProcessEnv = process.env,
130
+ ): Promise<LinkedRepositoryCatalog> {
131
+ const [linked, local] = await Promise.all([
132
+ linkedRemotes(companionPath),
133
+ readLocalRepositories(companionPath),
134
+ ]);
135
+ const sources = sourcesOf(linked, local.urls, env);
136
+ return {
137
+ identities: [...sources.keys()].toSorted(),
138
+ aliases: new Map(linked.filter(({ own }) => own).map(({ id, identity }) => [id, identity])),
139
+ kinds: new Map([...sources].map(([identity, source]) => [identity, source.kind])),
140
+ keys: new Map(
141
+ [...sources].flatMap(([identity, source]) => {
142
+ const key = gitTokenKeyOf(source.url);
143
+ return key ? [[identity, key] as const] : [];
144
+ }),
145
+ ),
146
+ problem: local.problem,
147
+ };
55
148
  }
@@ -0,0 +1,161 @@
1
+ import { constants } from "node:fs";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ import { errorMessage } from "../../runtime/error-message";
6
+ import type { GitRunner } from "./worktree";
7
+
8
+ /** Shared with tools that read the same file (Claude Code, Conductor). */
9
+ const INCLUDE_FILE = ".worktreeinclude";
10
+ /** Mate-only; used while Git ignores it. */
11
+ const LOCAL_INCLUDE_FILE = ".worktreeinclude.local";
12
+
13
+ export interface IncludeOutcome {
14
+ /** The include files used, in pattern order. */
15
+ sources: string[];
16
+ /** Paths copied into the worktree, relative to the repository root. */
17
+ copied: string[];
18
+ /** Selected paths that were not copied; `reason` never holds file contents. */
19
+ failed: { path: string; reason: string }[];
20
+ }
21
+
22
+ export interface IncludeSelection {
23
+ sources: string[];
24
+ paths: string[];
25
+ warnings: string[];
26
+ }
27
+
28
+ async function isFile(candidate: string): Promise<boolean> {
29
+ try {
30
+ return (await fs.stat(candidate)).isFile();
31
+ } catch {
32
+ return false;
33
+ }
34
+ }
35
+
36
+ /** Splits `-z` output; Git ends every entry with NUL. */
37
+ function entries(stdout: string): string[] {
38
+ return stdout.split("\0").filter(Boolean);
39
+ }
40
+
41
+ /**
42
+ * Untracked files of `checkout` that match its include files and its standard ignore
43
+ * rules. Git matches, so gitignore semantics, `**`, directories and non-ASCII paths
44
+ * behave as Git defines them.
45
+ */
46
+ export async function selectIncludedFiles(
47
+ git: GitRunner,
48
+ checkout: string,
49
+ ): Promise<IncludeSelection> {
50
+ const sources: string[] = [];
51
+ const warnings: string[] = [];
52
+ if (await isFile(path.join(checkout, INCLUDE_FILE))) sources.push(INCLUDE_FILE);
53
+ if (await isFile(path.join(checkout, LOCAL_INCLUDE_FILE))) {
54
+ // Tracked files never count as ignored, so this also refuses a committed one.
55
+ const ignored = await git(checkout, ["check-ignore", "-q", "--", LOCAL_INCLUDE_FILE]);
56
+ if (ignored.code === 0) sources.push(LOCAL_INCLUDE_FILE);
57
+ else warnings.push(`${LOCAL_INCLUDE_FILE} skipped: Git does not ignore it`);
58
+ }
59
+ if (sources.length === 0) return { sources, paths: [], warnings };
60
+ const listed = await git(checkout, [
61
+ "ls-files",
62
+ "-z",
63
+ "--others",
64
+ "--ignored",
65
+ ...sources.map((source) => `--exclude-from=${path.join(checkout, source)}`),
66
+ ]);
67
+ if (listed.code !== 0) {
68
+ warnings.push(`listing include files failed: ${listed.stderr.trim()}`);
69
+ return { sources, paths: [], warnings };
70
+ }
71
+ // Install owns `node_modules`; a short pattern such as `.env` would also match in packages.
72
+ const candidates = entries(listed.stdout).filter(
73
+ (entry) => !entry.split("/").includes("node_modules"),
74
+ );
75
+ if (candidates.length === 0) return { sources, paths: [], warnings };
76
+ // Exit 1 means none is ignored.
77
+ const checked = await git(checkout, ["check-ignore", "-z", "--stdin"], {
78
+ input: `${candidates.join("\0")}\0`,
79
+ });
80
+ if (checked.code > 1) {
81
+ warnings.push(`checking ignored include files failed: ${checked.stderr.trim()}`);
82
+ return { sources, paths: [], warnings };
83
+ }
84
+ return { sources, paths: entries(checked.stdout).toSorted(), warnings };
85
+ }
86
+
87
+ function inside(parent: string, child: string): boolean {
88
+ const relative = path.relative(parent, child);
89
+ return (
90
+ relative !== "" &&
91
+ relative !== ".." &&
92
+ !relative.startsWith(`..${path.sep}`) &&
93
+ !path.isAbsolute(relative)
94
+ );
95
+ }
96
+
97
+ /** Resolves symlinks in the longest existing prefix of `candidate`. */
98
+ async function realpathExisting(candidate: string): Promise<string> {
99
+ try {
100
+ return await fs.realpath(candidate);
101
+ } catch (error) {
102
+ const parent = path.dirname(candidate);
103
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" || parent === candidate) throw error;
104
+ return path.join(await realpathExisting(parent), path.basename(candidate));
105
+ }
106
+ }
107
+
108
+ type CopyResult = "copied" | "skipped" | { reason: string };
109
+
110
+ async function copyOne(
111
+ checkout: string,
112
+ worktree: string,
113
+ realWorktree: string,
114
+ entry: string,
115
+ ): Promise<CopyResult> {
116
+ const source = path.join(checkout, entry);
117
+ // Symbolic links and other non-regular files are not copied.
118
+ if (!(await fs.lstat(source)).isFile()) return "skipped";
119
+ const target = path.join(worktree, entry);
120
+ // Checked before mkdir: a symlinked parent inside the worktree could lead elsewhere.
121
+ const realTarget = path.join(await realpathExisting(path.dirname(target)), path.basename(target));
122
+ if (!inside(worktree, target) || !inside(realWorktree, realTarget)) {
123
+ return { reason: "outside the worktree" };
124
+ }
125
+ await fs.mkdir(path.dirname(target), { recursive: true });
126
+ try {
127
+ // Keeps the source's permission bits.
128
+ await fs.copyFile(source, target, constants.COPYFILE_EXCL);
129
+ } catch (error) {
130
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") return "skipped";
131
+ throw error;
132
+ }
133
+ return "copied";
134
+ }
135
+
136
+ /**
137
+ * Copies the selected regular files from `checkout` to `worktree`, never overwriting an
138
+ * existing path; a failure is recorded and the rest still run.
139
+ */
140
+ export async function copyIncludedFiles(
141
+ checkout: string,
142
+ worktree: string,
143
+ selection: IncludeSelection,
144
+ ): Promise<IncludeOutcome> {
145
+ const outcome: IncludeOutcome = { sources: selection.sources, copied: [], failed: [] };
146
+ if (selection.paths.length === 0) return outcome;
147
+ const realWorktree = await fs.realpath(worktree);
148
+ for (const entry of selection.paths) {
149
+ let result: CopyResult;
150
+ try {
151
+ // oxlint-disable-next-line no-await-in-loop -- parents may be shared between entries
152
+ result = await copyOne(checkout, worktree, realWorktree, entry);
153
+ } catch (error) {
154
+ const code = (error as NodeJS.ErrnoException).code;
155
+ result = { reason: code ?? errorMessage(error) };
156
+ }
157
+ if (result === "copied") outcome.copied.push(entry);
158
+ else if (result !== "skipped") outcome.failed.push({ path: entry, reason: result.reason });
159
+ }
160
+ return outcome;
161
+ }
@@ -32,6 +32,8 @@ export interface TokensaveRunner {
32
32
  }
33
33
 
34
34
  const MAIN_NOT_INDEXED = "main checkout not indexed";
35
+ /** Skip reason when an Umbrella Repository, indexed like a checkout, has no index. */
36
+ export const UMBRELLA_NOT_INDEXED = "umbrella not indexed";
35
37
  const TOKENSAVE_NOT_ON_PATH = "tokensave not on PATH";
36
38
 
37
39
  const STDERR_TAIL = 4096;
@@ -76,7 +78,8 @@ async function cpuUsage(checkout: string): Promise<string | undefined> {
76
78
 
77
79
  /**
78
80
  * Indexes `worktree` like `checkout`: `init` plus Mate's posture when it has no
79
- * index yet, `sync` when it has one. `onRun` fires before tokensave starts.
81
+ * index yet, `sync` when it has one; skipped with `notIndexedReason` while `checkout` has
82
+ * none. `onRun` fires before tokensave starts.
80
83
  * Never throws; a failure is an outcome.
81
84
  */
82
85
  export async function indexWorktree(
@@ -85,9 +88,10 @@ export async function indexWorktree(
85
88
  companionPath: string,
86
89
  tokensave: TokensaveRunner = runTokensave,
87
90
  onRun?: (action: "init" | "sync") => void,
91
+ notIndexedReason = MAIN_NOT_INDEXED,
88
92
  ): Promise<IndexOutcome> {
89
93
  if (!(await isTokensaveIndexed(checkout)))
90
- return { outcome: "skipped", reason: MAIN_NOT_INDEXED };
94
+ return { outcome: "skipped", reason: notIndexedReason };
91
95
  if (!tokensave.available()) return { outcome: "skipped", reason: TOKENSAVE_NOT_ON_PATH };
92
96
  try {
93
97
  const posture = () =>