@uniqbit/mate-core 0.20.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (287) hide show
  1. package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +1 -1
  2. package/claude-capability-plugins/companion-mentions/hooks/register.ts +1 -1
  3. package/claude-plugin/hooks/hooks.json +10 -1
  4. package/claude-plugin/hooks/rtk-worktree-git.mjs +58 -0
  5. package/opencode-plugin/src/server.ts +9 -2
  6. package/package.json +2 -1
  7. package/src/cli/commands/artifact/delivery/environment.ts +28 -8
  8. package/src/cli/commands/artifact/delivery/link.ts +28 -9
  9. package/src/cli/commands/artifact/delivery/output.ts +7 -0
  10. package/src/cli/commands/companion/update.ts +2 -19
  11. package/src/cli/commands/factory/factory.ts +11 -1
  12. package/src/cli/commands/install.ts +47 -36
  13. package/src/cli/commands/launch/claude.ts +2 -0
  14. package/src/cli/commands/launch/shared.ts +33 -6
  15. package/src/cli/commands/plugin/install.ts +27 -11
  16. package/src/cli/commands/report/index.ts +180 -184
  17. package/src/cli/commands/report/markdown.ts +67 -72
  18. package/src/cli/commands/shared/companion-selection.ts +3 -1
  19. package/src/cli/commands/studio/access.ts +6 -14
  20. package/src/cli/commands/studio/areas.ts +112 -33
  21. package/src/cli/commands/studio/companion-add.ts +87 -0
  22. package/src/cli/commands/studio/companion-removal.ts +15 -8
  23. package/src/cli/commands/studio/factory-credential.ts +1 -15
  24. package/src/cli/commands/studio/factory-git-tokens.ts +40 -0
  25. package/src/cli/commands/studio/factory-relay.ts +18 -0
  26. package/src/cli/commands/studio/graph-model.ts +61 -0
  27. package/src/cli/commands/studio/graph.ts +336 -0
  28. package/src/cli/commands/studio/index.ts +4 -4
  29. package/src/cli/commands/studio/payload.ts +42 -15
  30. package/src/cli/commands/studio/repository-add.ts +116 -0
  31. package/src/cli/commands/studio/routes.ts +6 -0
  32. package/src/cli/commands/studio/selection.ts +12 -3
  33. package/src/cli/commands/studio/server.ts +127 -5
  34. package/src/cli/commands/studio/services.ts +40 -0
  35. package/src/cli/commands/studio/terminal.ts +45 -3
  36. package/src/cli/commands/studio/views/vault/markdown-tree.ts +84 -3
  37. package/src/cli/commands/studio/workset-session.ts +47 -14
  38. package/src/cli/commands/unwrap.ts +3 -0
  39. package/src/cli/commands/update.ts +2 -0
  40. package/src/cli/commands/vscode/release-vsix.json +4 -0
  41. package/src/cli/commands/vscode/setup.ts +71 -13
  42. package/src/cli/commands/vscode/vsix.ts +48 -7
  43. package/src/cli/commands/working/cleanup.ts +40 -8
  44. package/src/cli/commands/working/worktree.ts +176 -35
  45. package/src/cli/main.ts +17 -2
  46. package/src/cli/usage.ts +1 -1
  47. package/src/hooks/rtk-worktree-git.ts +48 -0
  48. package/src/hooks/validate-artifact-path.ts +38 -7
  49. package/src/lib/delivery/branch-template.ts +122 -0
  50. package/src/lib/delivery/branches.ts +21 -16
  51. package/src/lib/delivery/checkout.ts +102 -0
  52. package/src/lib/delivery/environment.ts +2 -0
  53. package/src/lib/delivery/merge-git.ts +13 -1
  54. package/src/lib/delivery/record-delivery.ts +83 -29
  55. package/src/lib/delivery/record.ts +15 -3
  56. package/src/lib/delivery/resolve-branch.ts +157 -110
  57. package/src/lib/factory/attach-client.ts +11 -1
  58. package/src/lib/factory/broker.ts +37 -40
  59. package/src/lib/factory/client.ts +22 -1
  60. package/src/lib/factory/clone-url.ts +39 -0
  61. package/src/lib/factory/command.ts +21 -5
  62. package/src/lib/factory/git-auth.ts +61 -0
  63. package/src/lib/factory/git-credential-store.ts +181 -0
  64. package/src/lib/factory/ids.ts +12 -2
  65. package/src/lib/factory/outcomes/actions.ts +20 -4
  66. package/src/lib/factory/outcomes/index.ts +77 -11
  67. package/src/lib/factory/outcomes/lifecycle.ts +9 -2
  68. package/src/lib/factory/outcomes/sessions.ts +23 -1
  69. package/src/lib/factory/prepare.ts +9 -3
  70. package/src/lib/factory/runner/scheduler.ts +96 -14
  71. package/src/lib/factory/runner/workflow.ts +5 -1
  72. package/src/lib/factory/runtime.ts +143 -43
  73. package/src/lib/orchestrator/companion-hub.ts +6 -1
  74. package/src/lib/orchestrator/engine-floor.ts +48 -0
  75. package/src/lib/orchestrator/launcher.ts +34 -1
  76. package/src/lib/orchestrator/projection-claude-commands.ts +2 -2
  77. package/src/lib/orchestrator/projection-claude-entry.ts +42 -21
  78. package/src/lib/orchestrator/projection-claude-links.ts +32 -8
  79. package/src/lib/orchestrator/projection-claude-skills.ts +2 -2
  80. package/src/lib/orchestrator/projection-entries.ts +22 -18
  81. package/src/lib/orchestrator/projection-opencode-copies.ts +65 -21
  82. package/src/lib/orchestrator/projection-runtime-documents.ts +66 -43
  83. package/src/lib/orchestrator/projection-types.ts +28 -1
  84. package/src/lib/orchestrator/refresh-working-claude-links.ts +3 -1
  85. package/src/lib/orchestrator/session-prepare.ts +6 -1
  86. package/src/lib/orchestrator/setup-compatibilities.ts +1 -1
  87. package/src/lib/orchestrator/types.ts +4 -0
  88. package/src/lib/orchestrator/umbrella-checkouts.ts +102 -0
  89. package/src/lib/orchestrator/working-repo-projection.ts +24 -4
  90. package/src/lib/orchestrator/wrap-pass.ts +1 -0
  91. package/src/lib/public-npm.ts +95 -50
  92. package/src/lib/session-state.ts +72 -2
  93. package/src/lib/update-checker.ts +7 -1
  94. package/src/lib/usage/aggregate.ts +202 -0
  95. package/src/lib/usage/cache.ts +87 -0
  96. package/src/lib/usage/claude-pricing.ts +71 -0
  97. package/src/lib/usage/claude.ts +189 -0
  98. package/src/lib/usage/collect.ts +56 -0
  99. package/src/lib/usage/opencode.ts +188 -0
  100. package/src/lib/usage/records.ts +80 -0
  101. package/src/lib/usage/rtk-database.ts +72 -0
  102. package/src/lib/usage/savings.ts +209 -0
  103. package/src/lib/usage/scope.ts +182 -0
  104. package/src/lib/usage/source.ts +102 -0
  105. package/src/lib/usage/types.ts +143 -0
  106. package/src/lib/usage/window.ts +37 -0
  107. package/src/lib/workset/factory-local.ts +157 -0
  108. package/src/lib/workset/record.ts +25 -11
  109. package/src/lib/workset/repositories.ts +118 -25
  110. package/src/lib/workset/worktree-include.ts +161 -0
  111. package/src/lib/workset/worktree-index.ts +6 -2
  112. package/src/lib/workset/worktree.ts +591 -101
  113. package/src/opencode/companion-hooks.ts +46 -8
  114. package/src/opencode/companion-policy.ts +18 -5
  115. package/src/opencode/enter-worktree.ts +254 -6
  116. package/src/opencode/session-register.ts +2 -2
  117. package/src/runtime/claude-bg-isolation.ts +138 -0
  118. package/src/runtime/companion-git.ts +10 -2
  119. package/src/runtime/companion-guidance.ts +17 -4
  120. package/src/runtime/current-branch.ts +16 -2
  121. package/src/runtime/entered-worktree.ts +24 -0
  122. package/src/runtime/git-tracked.ts +60 -0
  123. package/src/runtime/repo-destination.ts +72 -0
  124. package/src/runtime/repo-local.ts +25 -3
  125. package/src/runtime/rtk-git-guard.ts +66 -0
  126. package/src/runtime/runtime-document-manifest.ts +229 -19
  127. package/src/runtime/runtime-document-manifest.typecheck.ts +10 -0
  128. package/src/runtime/secret-guard.ts +9 -2
  129. package/src/runtime/secret-policy-weakening.ts +122 -0
  130. package/src/runtime/serving-claude-wrap.ts +15 -2
  131. package/src/runtime/umbrella-folder.ts +56 -0
  132. package/src/runtime/wrap-state.ts +5 -13
  133. package/src/studio.ts +37 -0
  134. package/src/templates/mate-skills/agents/mate-apply-change/SKILL.md +61 -6
  135. package/src/templates/mate-skills/agents/mate-explore-change/SKILL.md +8 -4
  136. package/src/templates/mate-skills/agents/mate-propose-change/SKILL.md +9 -5
  137. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +5 -4
  138. package/src/templates/mate-skills/agents/mate-show-me/SKILL.md +10 -4
  139. package/src/templates/mate-skills/agents/mate-simplify-code/SKILL.md +5 -1
  140. package/src/templates/mate-skills/claude/mate-apply-change/SKILL.md +61 -6
  141. package/src/templates/mate-skills/claude/mate-explore-change/SKILL.md +8 -4
  142. package/src/templates/mate-skills/claude/mate-propose-change/SKILL.md +9 -5
  143. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +5 -4
  144. package/src/templates/mate-skills/claude/mate-show-me/SKILL.md +10 -4
  145. package/src/templates/mate-skills/claude/mate-simplify-code/SKILL.md +5 -1
  146. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +307 -42
  147. package/src/tools/setup/capabilities/rtk.ts +93 -1
  148. package/src/tools/setup/dynamic-plugins/audiences.ts +65 -21
  149. package/src/tools/setup/dynamic-plugins/frozen.ts +32 -13
  150. package/src/tools/setup/dynamic-plugins/hydrate.ts +4 -4
  151. package/src/tools/setup/dynamic-plugins/install.ts +24 -22
  152. package/src/tools/setup/dynamic-plugins/loader.ts +11 -7
  153. package/src/tools/setup/dynamic-plugins/paths.ts +30 -10
  154. package/src/tools/setup/dynamic-plugins/verify.ts +10 -7
  155. package/src/tools/setup/dynamic-plugins/workspaces.ts +153 -0
  156. package/src/tools/setup/mate.ts +3 -3
  157. package/src/tools/setup/plugins/gitignore.ts +15 -9
  158. package/src/tools/setup/providers/claude-plugin-hooks.ts +12 -0
  159. package/src/tools/setup/providers/claude.ts +25 -3
  160. package/src/tools/setup/utils.ts +4 -2
  161. package/src/tools/setup/working-repo-cleanup.ts +2 -2
  162. package/src/tools/setup/working-repo-local-state.ts +2 -0
  163. package/src/tools/setup.ts +25 -14
  164. package/studio-dist/client/assets/app-D9cw6szy.css +2 -0
  165. package/studio-dist/client/assets/artifacts-WD2ZXYrx.js +1 -0
  166. package/studio-dist/client/assets/button-Br0O1sXw.js +1 -0
  167. package/studio-dist/client/assets/combobox-DA7RAUUZ.js +1 -0
  168. package/studio-dist/client/assets/companion-view-CrabvxS8.js +1 -0
  169. package/studio-dist/client/assets/factory-DGS0E16C.js +6 -0
  170. package/studio-dist/client/assets/fields-6aXBpFhJ.js +1 -0
  171. package/studio-dist/client/assets/getting-started-Clde4w6P.js +1 -0
  172. package/studio-dist/client/assets/getting-started-D6kgWwWZ.js +1 -0
  173. package/studio-dist/client/assets/getting-started._topic-BiunccbT.js +1 -0
  174. package/studio-dist/client/assets/getting-started.index-DpiNoGw8.js +1 -0
  175. package/studio-dist/client/assets/graph-B_TCBVbu.js +2 -0
  176. package/studio-dist/client/assets/graph-canvas-Ba37Y5AE.js +3242 -0
  177. package/studio-dist/client/assets/guides-Du_RtJxP.js +1 -0
  178. package/studio-dist/client/assets/index-Df8L1LQa.js +40 -0
  179. package/studio-dist/client/assets/jsx-runtime-MZURdZre.js +1 -0
  180. package/studio-dist/client/assets/markdown-view-BOX6x0rL.js +1 -0
  181. package/studio-dist/client/assets/panel-dbmCx7Mx.js +1 -0
  182. package/studio-dist/client/assets/queries-RvHeXY12.js +1 -0
  183. package/studio-dist/client/assets/react-3QStrcDO.js +27 -0
  184. package/studio-dist/client/assets/report-url-XRL0x1SY.js +1 -0
  185. package/studio-dist/client/assets/reports-r3IK7Doz.js +1 -0
  186. package/studio-dist/client/assets/routes-C0A5LTFc.js +1 -0
  187. package/studio-dist/client/assets/select-CnaMd617.js +1 -0
  188. package/studio-dist/client/assets/skills-CzjzHpBT.js +1 -0
  189. package/studio-dist/client/assets/specs-B0ldF_6J.js +1 -0
  190. package/studio-dist/client/assets/specs-view-BnCLA0gW.js +1 -0
  191. package/studio-dist/client/assets/spinner-Dcm3fqK1.js +1 -0
  192. package/studio-dist/client/assets/steps-C0p2N1Pb.js +1 -0
  193. package/studio-dist/client/assets/store-Dw34catY.js +1 -0
  194. package/studio-dist/client/assets/studio-Cpz_HRHp.js +100 -0
  195. package/studio-dist/client/assets/studio-queries-ibmpFo6R.js +2 -0
  196. package/studio-dist/client/assets/usage-C2QJ_0IZ.js +55 -0
  197. package/studio-dist/client/assets/useAnchoredPopupScrollLock-Bj-FWb8z.js +1 -0
  198. package/studio-dist/client/assets/useMutation-aAr2uiay.js +1 -0
  199. package/studio-dist/client/assets/useSelector-AYcH7lB0.js +2 -0
  200. package/studio-dist/client/assets/vault-BGcxkSIY.js +1 -0
  201. package/studio-dist/client/assets/warnings-R1cE1rLf.js +1 -0
  202. package/studio-dist/client/assets/workflow-C2qTrMDH.js +1 -0
  203. package/studio-dist/server/assets/__23tanstack-start-server-fn-resolver-Bn896ZYj.js +122 -0
  204. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +102 -35
  205. package/studio-dist/server/assets/{actions-Bvgj9eb8.js → actions-DYSv-9VV.js} +10 -4
  206. package/studio-dist/server/assets/artifacts-DnF9L3dZ.js +216 -0
  207. package/studio-dist/server/assets/{button-CIJqAhni.js → button-CgOIVdmD.js} +13 -1702
  208. package/studio-dist/server/assets/combobox-DV_s9W0s.js +483 -0
  209. package/studio-dist/server/assets/{companion-view-DISASvdJ.js → companion-view-BKVXD3TO.js} +3 -3
  210. package/studio-dist/server/assets/companions-C7fctnU9.js +31 -0
  211. package/studio-dist/server/assets/{createServerRpc-tK2lE9R2.js → createServerRpc-bFKFpGFG.js} +1 -1
  212. package/studio-dist/server/assets/{factory-DUTa0eDs.js → factory-C7Ybg0xG.js} +1256 -353
  213. package/studio-dist/server/assets/{factory-DGPmNGbo.js → factory-Df5uAHjb.js} +53 -6
  214. package/studio-dist/server/assets/fields-BbieQTD0.js +1190 -0
  215. package/studio-dist/server/assets/getting-started-B136TP57.js +4 -0
  216. package/studio-dist/server/assets/getting-started-CRxMWorQ.js +67 -0
  217. package/studio-dist/server/assets/getting-started._topic-DJKQAzYl.js +13 -0
  218. package/studio-dist/server/assets/getting-started.index-D84gec1t.js +13 -0
  219. package/studio-dist/server/assets/graph-CSje3029.js +801 -0
  220. package/studio-dist/server/assets/graph-DDZzXM1L.js +16 -0
  221. package/studio-dist/server/assets/graph-canvas-22bWB5-2.js +21066 -0
  222. package/studio-dist/server/assets/graph-wire-BdSUx0G5.js +58 -0
  223. package/studio-dist/server/assets/guides-D9dk1Frq.js +13 -0
  224. package/studio-dist/server/assets/guides-IE-19POz.js +5 -0
  225. package/studio-dist/server/assets/guides.server-vcYRY5wx.js +66 -0
  226. package/studio-dist/server/assets/jsx-runtime-Bt0s0YKS.js +451 -0
  227. package/studio-dist/server/assets/{markdown-view-Bn7xPdks.js → markdown-view-BR8dJ7aR.js} +28 -9
  228. package/studio-dist/server/assets/{panel-3Jmn4awF.js → panel-BR_t9iMM.js} +4 -4
  229. package/studio-dist/server/assets/queries-DWoTin-q.js +32 -0
  230. package/studio-dist/server/assets/react-CdqSUhaL.js +89 -0
  231. package/studio-dist/server/assets/redirect-BaZ_QyqF.js +39 -0
  232. package/studio-dist/server/assets/report-url-BUXPcE_8.js +9 -0
  233. package/studio-dist/server/assets/{reports-D6YMqhnO.js → reports-CQ9qQ1-n.js} +9 -10
  234. package/studio-dist/server/assets/{reports-C06RXVE2.js → reports-dYDEoBeq.js} +3 -3
  235. package/studio-dist/server/assets/{router-C8MGqlAY.js → router-DkRHNTpE.js} +787 -2862
  236. package/studio-dist/server/assets/{routes-BcFgvqf7.js → routes-B6GfOew4.js} +22 -171
  237. package/studio-dist/server/assets/{search-JAKurDNh.js → search-BJnWLfkG.js} +21 -2
  238. package/studio-dist/server/assets/select-Af7Wibii.js +1609 -0
  239. package/studio-dist/server/assets/{shell-DS3wUexh.js → shell-Hq-hXgnT.js} +6 -5
  240. package/studio-dist/server/assets/{skills-BEnOxiDl.js → skills-B7nEuVbx.js} +9 -8
  241. package/studio-dist/server/assets/{skills-CtrBAtX3.js → skills-B_YYL7q8.js} +3 -3
  242. package/studio-dist/server/assets/specs-BpLUFntA.js +51 -0
  243. package/studio-dist/server/assets/specs-view-0peMVd22.js +426 -0
  244. package/studio-dist/server/assets/spinner-CdwJW4VB.js +20 -0
  245. package/studio-dist/server/assets/{steps-Dq_CwY_s.js → steps-D56DApvK.js} +1 -1
  246. package/studio-dist/server/assets/store-Cs17okNG.js +280 -0
  247. package/studio-dist/server/assets/studio-CAcKp3bM.js +10340 -0
  248. package/studio-dist/server/assets/studio-queries-BtRGzDdh.js +1451 -0
  249. package/studio-dist/server/assets/usage-COdjd1gD.js +25570 -0
  250. package/studio-dist/server/assets/usage-f6pqE1tm.js +24 -0
  251. package/studio-dist/server/assets/useAnchoredPopupScrollLock-DlBKHRw7.js +756 -0
  252. package/studio-dist/server/assets/useMutation-DzTZGenE.js +690 -0
  253. package/studio-dist/server/assets/{__23tanstack-start-server-fn-resolver-M2GBs8s3.js → useSelector-DUmCUXAs.js} +4 -668
  254. package/studio-dist/server/assets/{vault-Fvxt2Tzl.js → vault-BDuIUq0F.js} +8 -5
  255. package/studio-dist/server/assets/{vault-BmWnryh3.js → vault-BVLp6zu3.js} +3 -3
  256. package/studio-dist/server/assets/{views-BgYa-za2.js → views-flRUr21z.js} +4 -4
  257. package/studio-dist/server/assets/{warnings-DzR6fyZh.js → warnings-CDy9pdgL.js} +3 -2
  258. package/studio-dist/server/assets/{delivery-path-C29fBynY.js → workflow-D9GKI2EV.js} +132 -106
  259. package/studio-dist/server/server.js +582 -8
  260. package/src/cli/commands/report/collector.ts +0 -288
  261. package/studio-dist/client/assets/app-CdPiFv59.css +0 -2
  262. package/studio-dist/client/assets/button-BIIHE0EQ.js +0 -3
  263. package/studio-dist/client/assets/companion-view-DM6YyXaR.js +0 -1
  264. package/studio-dist/client/assets/delivery-path-DELxj0Av.js +0 -1
  265. package/studio-dist/client/assets/factory-BZy0E8ty.js +0 -4
  266. package/studio-dist/client/assets/index-B3wkMzjA.js +0 -40
  267. package/studio-dist/client/assets/markdown-view-pQ2Qp_i5.js +0 -1
  268. package/studio-dist/client/assets/panel-CbajlC3p.js +0 -1
  269. package/studio-dist/client/assets/prepaint-CwSrpdFA.js +0 -27
  270. package/studio-dist/client/assets/react-CN2GSx7x.js +0 -1
  271. package/studio-dist/client/assets/reports-DllhYQ5_.js +0 -1
  272. package/studio-dist/client/assets/rolldown-runtime-WkwZ5CU-.js +0 -1
  273. package/studio-dist/client/assets/routes-COm-G3mK.js +0 -1
  274. package/studio-dist/client/assets/skills-DmWAy-jZ.js +0 -1
  275. package/studio-dist/client/assets/specs-BG3Wi3ln.js +0 -1
  276. package/studio-dist/client/assets/steps-DFsH3Neu.js +0 -1
  277. package/studio-dist/client/assets/vault-B2q1nBY5.js +0 -1
  278. package/studio-dist/client/assets/warnings-BSXIyuSQ.js +0 -1
  279. package/studio-dist/client/assets/workflow-DlsQD6Hc.js +0 -1
  280. package/studio-dist/server/assets/companions-BYbHWKOZ.js +0 -15
  281. package/studio-dist/server/assets/createServerFn-F5sAOF8V.js +0 -459
  282. package/studio-dist/server/assets/prepaint-DJfTQ_VH.js +0 -45
  283. package/studio-dist/server/assets/react-Ce6dj15C.js +0 -46
  284. package/studio-dist/server/assets/rolldown-runtime-DYf_mQCB.js +0 -34
  285. package/studio-dist/server/assets/specs-C8rv34-5.js +0 -211
  286. package/studio-dist/server/assets/studio-BeltxxKt.js +0 -216
  287. package/studio-dist/server/assets/workflow-liRYecHk.js +0 -73
@@ -0,0 +1,39 @@
1
+ import { parseRemote } from "../delivery/forge";
2
+ import { FactoryError, hasSpaceOrControl } from "./ids";
3
+
4
+ /** A Git URL a person may ask the factory to clone: where it is, and what it names. */
5
+ export interface CloneUrl {
6
+ url: string;
7
+ host: string;
8
+ /** `owner/repo`, the repository's identity on its host. */
9
+ identity: string;
10
+ /** The last path segment, which names a companion's folder. */
11
+ name: string;
12
+ }
13
+
14
+ const SCHEMES = new Set(["http:", "https:", "ssh:"]);
15
+
16
+ /**
17
+ * Accepts an HTTP(S) or SSH remote URL, or the scp form, that names an organization and a
18
+ * repository. A local path, a `file` URL, an option-like value and a transport that runs a
19
+ * command are refused, so a browser cannot point the factory at its own filesystem.
20
+ */
21
+ export function checkedCloneUrl(value: unknown): CloneUrl {
22
+ const url = typeof value === "string" ? value.trim() : "";
23
+ if (!url) throw new FactoryError("no Git URL was given");
24
+ if (url.startsWith("-") || hasSpaceOrControl(url)) {
25
+ throw new FactoryError("a Git URL has no spaces, control characters or leading dash");
26
+ }
27
+ const scheme = /^([a-z][a-z\d+.-]*):\/\//i.exec(url)?.[1];
28
+ if (scheme !== undefined && !SCHEMES.has(`${scheme.toLowerCase()}:`)) {
29
+ throw new FactoryError("a Git URL starts with https://, http://, ssh:// or is user@host:path");
30
+ }
31
+ if (scheme === undefined && !/^(?:[^/\s@]+@)?[^/\s:]{2,}:[^:]/.test(url)) {
32
+ throw new FactoryError("a Git URL starts with https://, http://, ssh:// or is user@host:path");
33
+ }
34
+ const repo = parseRemote(url);
35
+ if (!repo) {
36
+ throw new FactoryError("a Git URL names an organization and a repository, as in host/acme/web");
37
+ }
38
+ return { url, host: repo.host, identity: `${repo.owner}/${repo.repo}`, name: repo.repo };
39
+ }
@@ -9,13 +9,15 @@ export interface CommandResult {
9
9
  }
10
10
 
11
11
  export interface CommandOptions {
12
- /** Added to the inherited environment for this command only; never part of argv. */
12
+ /** Inherited additions, never request values: Bun resolves bare commands through PATH. */
13
13
  env?: Record<string, string>;
14
14
  /** Run as this user (by name) through `setpriv`, with that user's home. */
15
15
  asUser?: string;
16
16
  /** Written to the command's standard input, which is then closed. */
17
17
  stdin?: Uint8Array;
18
18
  cwd?: string;
19
+ /** Killed after this long and answered as failed. */
20
+ timeoutMs?: number;
19
21
  }
20
22
 
21
23
  export type CommandRunner = (
@@ -48,14 +50,28 @@ export const runCommand: CommandRunner = (command, args, options = {}) => {
48
50
  ...(options.cwd ? { cwd: options.cwd } : {}),
49
51
  stdio: [options.stdin ? "pipe" : "ignore", "pipe", "pipe"],
50
52
  });
53
+ // Own timer, so only its kill reads as a timeout.
54
+ // `setpriv` execs the command, so the kill reaches it.
55
+ let timedOut = false;
56
+ const timer =
57
+ options.timeoutMs !== undefined
58
+ ? setTimeout(() => {
59
+ timedOut = true;
60
+ child.kill("SIGTERM");
61
+ }, options.timeoutMs)
62
+ : undefined;
51
63
  if (options.stdin) child.stdin?.end(options.stdin);
52
64
  let stdout = "";
53
65
  let stderr = "";
54
66
  child.stdout?.on("data", (chunk: Buffer) => (stdout += chunk.toString()));
55
67
  child.stderr?.on("data", (chunk: Buffer) => (stderr += chunk.toString()));
56
- child.on("error", (error) =>
57
- resolve({ status: 127, stdout, stderr: `${stderr}${error.message}` }),
58
- );
59
- child.on("close", (code) => resolve({ status: code ?? 1, stdout, stderr }));
68
+ child.on("error", (error) => {
69
+ clearTimeout(timer);
70
+ resolve({ status: 127, stdout, stderr: `${stderr}${error.message}` });
71
+ });
72
+ child.on("close", (code) => {
73
+ clearTimeout(timer);
74
+ resolve({ status: code ?? 1, stdout, stderr: timedOut ? `${stderr}timed out` : stderr });
75
+ });
60
76
  });
61
77
  };
@@ -0,0 +1,61 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ import { gitKeyOf } from "./git-credential-store";
5
+
6
+ /**
7
+ * How a token reaches Git: an askpass helper that prints it from the child's own environment, so
8
+ * it is never in a URL, an argument, `.git/config` or a file beside a checkout.
9
+ */
10
+
11
+ /** A placeholder user name that GitHub and GitLab accept together with a personal token. */
12
+ export const GIT_USERNAME = "x-access-token";
13
+
14
+ const ASKPASS_FILE = "git-askpass.sh";
15
+ const ASKPASS_SCRIPT = `#!/bin/sh
16
+ case "$1" in
17
+ Username*) printf '%s\\n' "$MATE_GIT_ASKPASS_USERNAME" ;;
18
+ *) printf '%s\\n' "$MATE_GIT_ASKPASS_TOKEN" ;;
19
+ esac
20
+ `;
21
+
22
+ /** The helper's path in the state directory, written on first use and readable by the Git user. */
23
+ function askpassFile(stateDir: string): string {
24
+ const file = path.join(stateDir, ASKPASS_FILE);
25
+ fs.mkdirSync(stateDir, { recursive: true });
26
+ if (!fs.existsSync(file) || fs.readFileSync(file, "utf8") !== ASKPASS_SCRIPT) {
27
+ fs.writeFileSync(file, ASKPASS_SCRIPT, { mode: 0o755 });
28
+ fs.chmodSync(file, 0o755);
29
+ }
30
+ return file;
31
+ }
32
+
33
+ /** The environment of the one Git command that needs `token`; prompts are off either way. */
34
+ export function gitAuthEnv(stateDir: string, token: string | null): Record<string, string> {
35
+ if (token === null) return { GIT_TERMINAL_PROMPT: "0" };
36
+ return {
37
+ GIT_TERMINAL_PROMPT: "0",
38
+ GIT_ASKPASS: askpassFile(stateDir),
39
+ MATE_GIT_ASKPASS_USERNAME: GIT_USERNAME,
40
+ MATE_GIT_ASKPASS_TOKEN: token,
41
+ };
42
+ }
43
+
44
+ const AUTH_FAILURE =
45
+ /authentication failed|could not read (username|password)|terminal prompts disabled|invalid username or password|http[s]? (basic: )?access denied|returned error: 40[13]|requested url returned error: 40[13]/i;
46
+
47
+ export function isAuthFailure(output: string): boolean {
48
+ return AUTH_FAILURE.test(output);
49
+ }
50
+
51
+ /** The text with every copy of the token replaced. */
52
+ export function scrubToken(text: string, token: string | null): string {
53
+ return token ? text.split(token).join("***") : text;
54
+ }
55
+
56
+ /** What a refused clone says: where, and that a token is missing or refused; never a token. */
57
+ export function authFailureMessage(url: string): string {
58
+ const key = gitKeyOf(url);
59
+ const where = key ? `${key.host}/${key.org}` : "the remote";
60
+ return `authentication to ${where} failed: no Git token is stored for it, or the stored token was refused`;
61
+ }
@@ -0,0 +1,181 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ import { parseRemote } from "../delivery/forge";
5
+ import { FactoryError, hasSpaceOrControl } from "./ids";
6
+
7
+ /**
8
+ * The Git tokens the broker holds, per host or per host and organization: those set from
9
+ * Studio, kept in a root-only file in the factory state volume, and the startup token, which
10
+ * covers only the hosts the operator named. Nothing here returns a token except `forUrl`,
11
+ * which only the broker's own Git commands read.
12
+ */
13
+
14
+ export const GIT_CREDENTIAL_FILE = "git-credentials.json";
15
+
16
+ /** The startup token and the variable naming the hosts it may be used for. */
17
+ export const GIT_STARTUP_TOKEN_ENV = "MATE_GIT_CLONE_TOKEN";
18
+ export const GIT_STARTUP_HOSTS_ENV = "MATE_FACTORY_GIT_TOKEN_HOSTS";
19
+
20
+ const MAX_TOKEN_LENGTH = 1024;
21
+ const KEY = /^[a-z0-9]([a-z0-9.-]*[a-z0-9])?(\/[a-z0-9._-]+)?$/;
22
+
23
+ export interface GitTokenStatus {
24
+ /** `host` or `host/org`. */
25
+ key: string;
26
+ source: "studio" | "startup";
27
+ /** When it was set in Studio, as an ISO date; null for a startup token. */
28
+ setAt: string | null;
29
+ }
30
+
31
+ export interface GitStartupToken {
32
+ token: string;
33
+ /** Lowercase hosts the token may be used for. */
34
+ hosts: string[];
35
+ }
36
+
37
+ /** What a Git command reads: the token for a URL, or null when none applies. */
38
+ export interface GitCredentials {
39
+ forUrl(url: string): string | null;
40
+ }
41
+
42
+ /** The host and the first path segment of a forge URL; null when it names neither. */
43
+ export function gitKeyOf(url: string): { host: string; org: string } | null {
44
+ const repo = parseRemote(url);
45
+ const org = repo?.owner.split("/")[0]?.toLowerCase();
46
+ return repo && org ? { host: repo.host, org } : null;
47
+ }
48
+
49
+ /** The `host/org` key a token applies to for a clone URL; null for SSH and other non-HTTP(S) URLs. */
50
+ export function gitTokenKeyOf(url: string): string | null {
51
+ if (!/^https?:\/\//i.test(url.trim())) return null;
52
+ const key = gitKeyOf(url);
53
+ return key ? `${key.host}/${key.org}` : null;
54
+ }
55
+
56
+ /** A key as stored: lowercase `host` or `host/org`. */
57
+ export function checkedGitKey(value: unknown): string {
58
+ const key = typeof value === "string" ? value.trim().toLowerCase() : "";
59
+ if (!key) throw new FactoryError("no host was given for the Git token");
60
+ if (!KEY.test(key)) {
61
+ throw new FactoryError(
62
+ "a Git token key is a host such as git.acme.test, or a host and one organization such as git.acme.test/acme; nothing was stored",
63
+ );
64
+ }
65
+ return key;
66
+ }
67
+
68
+ /** A token as stored; the message never quotes it. */
69
+ export function checkedGitToken(value: unknown): string {
70
+ const token = typeof value === "string" ? value.trim() : "";
71
+ if (!token) throw new FactoryError("no Git token was given");
72
+ if (token.length > MAX_TOKEN_LENGTH || hasSpaceOrControl(token)) {
73
+ throw new FactoryError(
74
+ `a Git token has no spaces or control characters and is at most ${MAX_TOKEN_LENGTH} characters; nothing was stored`,
75
+ );
76
+ }
77
+ return token;
78
+ }
79
+
80
+ /**
81
+ * Takes the startup token out of the process environment so no child inherits it; it is
82
+ * usable only for the hosts the supervisor lists.
83
+ */
84
+ export function takeGitStartupToken(env: NodeJS.ProcessEnv = process.env): GitStartupToken | null {
85
+ const token = env[GIT_STARTUP_TOKEN_ENV]?.trim();
86
+ const hosts = (env[GIT_STARTUP_HOSTS_ENV] ?? "")
87
+ .split(",")
88
+ .map((host) => host.trim().toLowerCase())
89
+ .filter(Boolean);
90
+ delete env[GIT_STARTUP_TOKEN_ENV];
91
+ delete env[GIT_STARTUP_HOSTS_ENV];
92
+ return token && hosts.length > 0 ? { token, hosts } : null;
93
+ }
94
+
95
+ interface Stored {
96
+ token: string;
97
+ setAt: string;
98
+ }
99
+
100
+ function parse(text: string): Map<string, Stored> {
101
+ const entries = new Map<string, Stored>();
102
+ const data: unknown = JSON.parse(text);
103
+ if (data === null || typeof data !== "object" || Array.isArray(data)) return entries;
104
+ for (const [name, entry] of Object.entries(data)) {
105
+ const value = entry as Partial<Stored> | null;
106
+ if (typeof value?.token !== "string" || typeof value.setAt !== "string") continue;
107
+ try {
108
+ entries.set(checkedGitKey(name), { token: value.token, setAt: value.setAt });
109
+ } catch {
110
+ /** A key that no longer validates is dropped. */
111
+ }
112
+ }
113
+ return entries;
114
+ }
115
+
116
+ export class GitCredentialStore implements GitCredentials {
117
+ private stored = new Map<string, Stored>();
118
+
119
+ /** `file` null keeps nothing on disk and refuses set and clear. */
120
+ constructor(
121
+ private readonly file: string | null,
122
+ private readonly startup: GitStartupToken | null,
123
+ private readonly now: () => Date = () => new Date(),
124
+ ) {
125
+ if (file === null) return;
126
+ try {
127
+ this.stored = parse(fs.readFileSync(file, "utf8"));
128
+ } catch {
129
+ this.stored = new Map();
130
+ }
131
+ }
132
+
133
+ forUrl(url: string): string | null {
134
+ const key = gitTokenKeyOf(url);
135
+ if (!key) return null;
136
+ const host = key.split("/")[0]!;
137
+ const entry = this.stored.get(key) ?? this.stored.get(host);
138
+ if (entry) return entry.token;
139
+ return this.startup?.hosts.includes(host) ? this.startup.token : null;
140
+ }
141
+
142
+ status(): GitTokenStatus[] {
143
+ const stored = [...this.stored].map(([key, entry]): GitTokenStatus => ({
144
+ key,
145
+ source: "studio",
146
+ setAt: entry.setAt,
147
+ }));
148
+ const startup = (this.startup?.hosts ?? [])
149
+ .filter((host) => !this.stored.has(host))
150
+ .map((host): GitTokenStatus => ({ key: host, source: "startup", setAt: null }));
151
+ return [...stored, ...startup].toSorted((a, b) => a.key.localeCompare(b.key));
152
+ }
153
+
154
+ set(key: string, token: string): void {
155
+ const file = this.writable();
156
+ const next = new Map(this.stored).set(key, { token, setAt: this.now().toISOString() });
157
+ this.write(file, next);
158
+ this.stored = next;
159
+ }
160
+
161
+ /** Removes a stored key; a key never stored is not an error. */
162
+ clear(key: string): void {
163
+ const file = this.writable();
164
+ const next = new Map(this.stored);
165
+ next.delete(key);
166
+ this.write(file, next);
167
+ this.stored = next;
168
+ }
169
+
170
+ private write(file: string, entries: Map<string, Stored>): void {
171
+ const temp = path.join(path.dirname(file), `.${GIT_CREDENTIAL_FILE}.${process.pid}.tmp`);
172
+ fs.writeFileSync(temp, JSON.stringify(Object.fromEntries(entries)), { mode: 0o600 });
173
+ fs.chmodSync(temp, 0o600);
174
+ fs.renameSync(temp, file);
175
+ }
176
+
177
+ private writable(): string {
178
+ if (this.file === null) throw new FactoryError("the broker keeps no Git token file");
179
+ return this.file;
180
+ }
181
+ }
@@ -4,16 +4,26 @@ import { defaultDeliveryBranch } from "../delivery/record";
4
4
  /** Workset identifiers and the names derived from them. */
5
5
 
6
6
  export class FactoryError extends Error {
7
- /** `busy`: every running Workset container is in use; retry once one frees. */
7
+ /**
8
+ * `busy`: every running Workset container is in use; retry once one frees. `auth`: a remote
9
+ * refused the clone for lack of a valid Git token.
10
+ */
8
11
  constructor(
9
12
  message: string,
10
- readonly code?: "busy",
13
+ readonly code?: "busy" | "auth",
11
14
  ) {
12
15
  super(message);
13
16
  this.name = "FactoryError";
14
17
  }
15
18
  }
16
19
 
20
+ /** Whether a value a person entered holds whitespace or a control character. */
21
+ export function hasSpaceOrControl(value: string): boolean {
22
+ return [...value].some(
23
+ (char) => /\s/.test(char) || char.charCodeAt(0) < 0x20 || char.charCodeAt(0) === 0x7f,
24
+ );
25
+ }
26
+
17
27
  export function assertWorksetId(id: unknown): asserts id is string {
18
28
  if (typeof id !== "string" || !isWorksetId(id)) {
19
29
  throw new FactoryError(
@@ -17,6 +17,7 @@ export const OUTCOME_ACTIONS = [
17
17
  "regenerate",
18
18
  "start-apply",
19
19
  "publish",
20
+ "delete",
20
21
  ] as const;
21
22
 
22
23
  export type OutcomeAction = (typeof OUTCOME_ACTIONS)[number];
@@ -30,6 +31,8 @@ export interface OutcomeFacts {
30
31
  id: string;
31
32
  stage: WorksetStageId;
32
33
  stageLabel: string;
34
+ /** The changes the Workset links; Delete is only for an Outcome with none. */
35
+ changes: readonly string[];
33
36
  }
34
37
 
35
38
  /** What the policy reads of a Workset's run; absent while it never ran. */
@@ -63,10 +66,14 @@ export function outcomeRefusal(
63
66
  ): string | null {
64
67
  const { id, stage, stageLabel } = workset;
65
68
  const state = run?.state ?? "idle";
66
- switch (action) {
67
- case "start":
68
- case "later":
69
- return stage === "done" ? `Workset ${id} is done` : null;
69
+ if (action === "start") return stage === "done" ? `Workset ${id} is done` : null;
70
+ if (action === "later") {
71
+ if (stage === "done") return `Workset ${id} is done`;
72
+ // Later only before work begins; a failed or interrupted clarify left nothing running.
73
+ const begun = stage !== "clarify-intent" || state === "running" || state === "waiting";
74
+ return begun
75
+ ? `work on Workset ${id} has begun (${stageLabel}, ${state}); it can no longer move to Later`
76
+ : null;
70
77
  }
71
78
  if (!companion.runner) return NO_RUNNER_REFUSAL;
72
79
  switch (action) {
@@ -99,6 +106,15 @@ export function outcomeRefusal(
99
106
  return stage === "publish"
100
107
  ? null
101
108
  : `Workset ${id} is not merged and archived; it is at ${stageLabel}`;
109
+ case "delete":
110
+ if (stage === "done") return `Workset ${id} is done`;
111
+ if (workset.changes.length > 0) {
112
+ return `Workset ${id} has a change (${workset.changes.join(", ")}); only an Outcome without one can be deleted`;
113
+ }
114
+ // A live run does not refuse: Delete stops it first.
115
+ return run?.control
116
+ ? "a person has taken over this Outcome; return it to automation first"
117
+ : null;
102
118
  }
103
119
  }
104
120
 
@@ -6,6 +6,7 @@ import {
6
6
  createOutcome,
7
7
  findWorkset,
8
8
  isWorksetId,
9
+ removeWorkset,
9
10
  setWorksetStarted,
10
11
  WorksetError,
11
12
  } from "../../workset/record";
@@ -85,6 +86,11 @@ export interface FactoryOutcomes extends Outcomes {
85
86
  onChanged(listener: () => void): () => void;
86
87
  /** For a Workset session: the factory conversation a person continues, `null` while automatic. */
87
88
  takenOver(id: string): Promise<{ claudeSession: string | null } | null>;
89
+ /**
90
+ * Claude exited in a person's session: Return to automation, as the button does. Does
91
+ * nothing unless the person has control; a failed return keeps it, with the reason recorded.
92
+ */
93
+ returnAfterExit(id: string): Promise<void>;
88
94
  }
89
95
 
90
96
  /** What the module asks of the server it runs in, given at construction. */
@@ -125,6 +131,14 @@ function assertWorksetId(id: string): void {
125
131
  }
126
132
  }
127
133
 
134
+ /** What the Outcome action policy reads of a Workset. */
135
+ const outcomeFacts = (id: string, workset: WorksetWithStage) => ({
136
+ id,
137
+ stage: workset.derived.stage,
138
+ stageLabel: workset.derived.label,
139
+ changes: workset.record.changes,
140
+ });
141
+
128
142
  /**
129
143
  * The Workset `action` targets once the Outcome action policy accepts it; refused with a
130
144
  * reason, changing nothing, otherwise. `undefined` for Start or Later on a Workset without a
@@ -149,12 +163,9 @@ async function acceptedAction(
149
163
  if (action === "start" || action === "later") return undefined;
150
164
  throw new StageError(`this companion has no valid Workset ${id}`);
151
165
  }
152
- const refusal = outcomeRefusal(
153
- action,
154
- { id, stage: workset.derived.stage, stageLabel: workset.derived.label },
155
- await companion.run?.(),
156
- { runner: companion.runner },
157
- );
166
+ const refusal = outcomeRefusal(action, outcomeFacts(id, workset), await companion.run?.(), {
167
+ runner: companion.runner,
168
+ });
158
169
  if (refusal) throw new StageError(refusal);
159
170
  return workset;
160
171
  }
@@ -227,6 +238,42 @@ function assemble(parts: OutcomesParts) {
227
238
  };
228
239
  };
229
240
 
241
+ /** Clears the start and drops a queued run, re-checked under the lock: work may have begun. */
242
+ const moveToLater = (id: string) =>
243
+ runner.park(
244
+ id,
245
+ async (running) => {
246
+ const current = (await stages()).worksets.find((entry) => entry.record.id === id);
247
+ if (!current) return null;
248
+ const run = await runFacts(id);
249
+ const facts = running ? { ...run, state: "running" as const } : run;
250
+ return outcomeRefusal("later", outcomeFacts(id, current), facts, { runner: true });
251
+ },
252
+ () => setWorksetStarted(companionPath, id, false),
253
+ );
254
+
255
+ /**
256
+ * Stops a live run, then ends the person's open session and removes the container and
257
+ * worktree, the run state and, last, the record; the first failure keeps the record, so the
258
+ * Outcome stays on the board to retry. A refusal stops nothing.
259
+ */
260
+ const deleteOutcome = async (id: string) => {
261
+ const refusal = async () => {
262
+ const current = (await stages()).worksets.find((entry) => entry.record.id === id);
263
+ if (!current) return `this companion has no valid Workset ${id}`;
264
+ return outcomeRefusal("delete", outcomeFacts(id, current), await runFacts(id), {
265
+ runner: true,
266
+ });
267
+ };
268
+ await runner.stop(id, refusal);
269
+ await runner.discard(id, refusal, async () => {
270
+ await sessions.close(companionPath, id, "deleted");
271
+ if ((await client.list()).some((workset) => workset.id === id)) await client.delete(id);
272
+ await runs.forget(id);
273
+ await removeWorkset(companionPath, id);
274
+ });
275
+ };
276
+
230
277
  const outcomes: FactoryOutcomes = {
231
278
  companionPath,
232
279
  automated: true,
@@ -237,10 +284,14 @@ function assemble(parts: OutcomesParts) {
237
284
  run: () => ready.then(() => runFacts(id)),
238
285
  });
239
286
  await ready;
240
- if (action === "start" || action === "later") {
241
- await setWorksetStarted(companionPath, id, action === "start");
242
- if (action === "later") await runner.dequeue(id);
243
- else await runner.rerank(id);
287
+ if (action === "start") {
288
+ await setWorksetStarted(companionPath, id, true);
289
+ await runner.rerank(id);
290
+ await pickUp();
291
+ return;
292
+ }
293
+ if (action === "later") {
294
+ await moveToLater(id);
244
295
  await pickUp();
245
296
  return;
246
297
  }
@@ -268,6 +319,8 @@ function assemble(parts: OutcomesParts) {
268
319
  return runner.request(id, "apply");
269
320
  case "publish":
270
321
  return runner.request(id, "publish");
322
+ case "delete":
323
+ return deleteOutcome(id);
271
324
  }
272
325
  },
273
326
  async create(fields) {
@@ -285,6 +338,17 @@ function assemble(parts: OutcomesParts) {
285
338
  if (facts.control.mode !== "manual") return null;
286
339
  return { claudeSession: facts.claudeSession };
287
340
  },
341
+ async returnAfterExit(id) {
342
+ await ready;
343
+ if (!(await outcomes.takenOver(id))) return;
344
+ try {
345
+ await runner.returnToAutomation(id);
346
+ } catch (error) {
347
+ process.stderr.write(
348
+ `mate studio: returning ${id} to automation after Claude exited failed: ${(error as Error).message}\n`,
349
+ );
350
+ }
351
+ },
288
352
  };
289
353
  return { outcomes, pickUp, reclaim };
290
354
  }
@@ -327,13 +391,14 @@ export function createFactoryOutcomes(
327
391
  async turn(request) {
328
392
  await requireAgentCredential(client);
329
393
  // A Workset may reach Ready without a session, so the turn spawns its container.
330
- await prepareWorkset(
394
+ const { warnings } = await prepareWorkset(
331
395
  client,
332
396
  companionPath,
333
397
  request.worksetId,
334
398
  env,
335
399
  memorySizeFor(request.stage),
336
400
  );
401
+ for (const warning of warnings) request.onText(`\n${warning}\n`);
337
402
  return harness.turn(request);
338
403
  },
339
404
  };
@@ -357,6 +422,7 @@ export function createFactoryOutcomes(
357
422
  },
358
423
  recordFor,
359
424
  sessionLive: (id) => ports.sessions.busy().has(id),
425
+ endSession: (id) => ports.sessions.close(companionPath, id, "returned"),
360
426
  });
361
427
  const { outcomes, pickUp, reclaim } = assemble({
362
428
  ...ports,
@@ -6,7 +6,7 @@ import { compareRanked, rankOf } from "../runner/rank";
6
6
  import { type FactoryRunner, pickableStage } from "../runner/scheduler";
7
7
  import type { Run } from "../runner/run";
8
8
  import { StageError } from "../runner/workflow";
9
- import { readWorksets } from "../../workset/record";
9
+ import { findWorkset, readWorksets } from "../../workset/record";
10
10
  import type { WorksetWithStage } from "../../workset/stages";
11
11
  import { NO_CREDENTIAL } from "../credential-store";
12
12
 
@@ -174,8 +174,15 @@ export async function pickUpReady(deps: PickUpDeps): Promise<string[]> {
174
174
  const requested: string[] = [];
175
175
  for (const candidate of candidates) {
176
176
  try {
177
+ // Re-read under the run's lock: Later may have cleared the start since the list was read.
178
+ const pickable = async () => {
179
+ const record = await findWorkset(deps.companionPath, candidate.id);
180
+ return record !== undefined && pickableStage(record) === candidate.stage;
181
+ };
177
182
  // oxlint-disable-next-line no-await-in-loop -- free slots go to the lowest rank first
178
- if (await deps.runner.pickUp(candidate.id, candidate.stage)) requested.push(candidate.id);
183
+ if (await deps.runner.pickUp(candidate.id, candidate.stage, pickable)) {
184
+ requested.push(candidate.id);
185
+ }
179
186
  } catch (error) {
180
187
  // Another request won the race; the Workset is running anyway.
181
188
  if (!(error instanceof StageError)) throw error;
@@ -1,11 +1,33 @@
1
+ /** Why Outcomes end a person's session; the terminal tells the person. */
2
+ export type SessionCloseReason = "returned" | "deleted";
3
+
4
+ /** Ends a companion's sessions for a Workset; resolves once they are reaped. */
5
+ export type SessionCloser = (
6
+ companionPath: string,
7
+ worksetId: string,
8
+ reason: SessionCloseReason,
9
+ ) => Promise<void>;
10
+
1
11
  /**
2
12
  * The Workset sessions a person has open in Studio's terminal. Created before both the
3
13
  * terminal and the factory's Outcomes, so neither needs the other: the terminal records
4
- * sessions here, the Outcomes read which Worksets are a person's and hear when one ends.
14
+ * sessions here and lends its closer, the Outcomes read which Worksets are a person's, hear
15
+ * when one ends and end one themselves.
5
16
  */
6
17
  export class LiveSessions {
7
18
  private readonly open = new Map<string, number>();
8
19
  private readonly listeners = new Set<(worksetId: string) => void>();
20
+ private closer: SessionCloser | null = null;
21
+
22
+ /** The terminal's way to end sessions; without one, `close` ends nothing. */
23
+ closeWith(closer: SessionCloser): void {
24
+ this.closer = closer;
25
+ }
26
+
27
+ /** Ends the companion's sessions for the Workset, telling the person why. */
28
+ close(companionPath: string, worksetId: string, reason: SessionCloseReason): Promise<void> {
29
+ return this.closer?.(companionPath, worksetId, reason) ?? Promise.resolve();
30
+ }
9
31
 
10
32
  /** A session for the Workset started; pickup leaves the Workset alone until it ends. */
11
33
  begin(worksetId: string): void {
@@ -4,6 +4,12 @@ import type { FactoryClient } from "./client";
4
4
  import { FactoryError } from "./ids";
5
5
  import type { MemorySize } from "./runtime";
6
6
 
7
+ export interface PreparedWorkset {
8
+ record: WorksetRecord;
9
+ /** What the spawn reported about a new worktree's Delivery Branch, for a person to read. */
10
+ warnings: string[];
11
+ }
12
+
7
13
  /**
8
14
  * Makes a Workset's container ready for work: cloned or fetched, its worktree on the
9
15
  * delivery branch, the container created or started, and the worktree linked to the
@@ -16,7 +22,7 @@ export async function prepareWorkset(
16
22
  id: string,
17
23
  env: NodeJS.ProcessEnv = process.env,
18
24
  size?: MemorySize,
19
- ): Promise<WorksetRecord> {
25
+ ): Promise<PreparedWorkset> {
20
26
  const record = (await readWorksets(companionPath)).worksets.find((entry) => entry.id === id);
21
27
  if (!record) throw new FactoryError(`this companion has no valid Workset ${id}`);
22
28
  if (record.repositories.length !== 1) {
@@ -31,7 +37,7 @@ export async function prepareWorkset(
31
37
  `${repository} is neither linked here nor a configured factory repository`,
32
38
  );
33
39
  }
34
- await client.spawn({
40
+ const spawned = await client.spawn({
35
41
  id,
36
42
  repository,
37
43
  remoteUrl,
@@ -45,5 +51,5 @@ export async function prepareWorkset(
45
51
  if (link.status !== 0) {
46
52
  throw new FactoryError(`linking the worktree failed: ${(link.stderr || link.stdout).trim()}`);
47
53
  }
48
- return record;
54
+ return { record, warnings: spawned?.warnings ?? [] };
49
55
  }