@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
@@ -11,7 +11,11 @@ import { realpath } from "node:fs/promises";
11
11
  import path from "node:path";
12
12
 
13
13
  import { MERMAID_RUNTIME_URL } from "../report/renderer";
14
- import { CompanionRemovalError, deleteRegisteredCompanion } from "./companion-removal";
14
+ import {
15
+ CompanionRemovalError,
16
+ deletableWithin,
17
+ deleteRegisteredCompanion,
18
+ } from "./companion-removal";
15
19
  import { collectStudioInventory, type StudioInventory } from "./inventory";
16
20
  import {
17
21
  assembleCompanionPayload,
@@ -31,10 +35,14 @@ import {
31
35
  } from "../../../lib/factory/outcomes";
32
36
  import { LiveSessions } from "../../../lib/factory/outcomes/sessions";
33
37
  import { FACTORY_BROKER_ENV, factoryClient, type FactoryClient } from "../../../lib/factory/client";
38
+ import { addCompanionByPath, addCompanionByUrl } from "./companion-add";
39
+ import { addRepository, removeRepository } from "./repository-add";
34
40
  import { factoryCredentialResponse } from "./factory-credential";
41
+ import { factoryGitTokensResponse } from "./factory-git-tokens";
35
42
  import { createWorksetResolver } from "./workset-session";
36
43
  import {
37
44
  FACTORY_CREDENTIAL_ROUTE,
45
+ FACTORY_GIT_TOKENS_ROUTE,
38
46
  FACTORY_WORKSETS_ROUTE,
39
47
  REPORTS_ROUTE,
40
48
  REPORT_VIEW_PREFIX,
@@ -59,6 +67,7 @@ import {
59
67
  type StudioProfile,
60
68
  } from "./selection";
61
69
  import { errorMessage } from "../../../runtime/error-message";
70
+ import type { SpecGraphCache } from "./graph";
62
71
  import { createStudioSnapshotCache, type StudioSnapshotCache } from "./snapshot";
63
72
  import type { StudioPage } from "./views/model";
64
73
  import { createVaultManager, resolveVaultPath, VaultPathError, type VaultManager } from "./vault";
@@ -69,6 +78,7 @@ import {
69
78
  type TerminalRegistryOptions,
70
79
  } from "./terminal";
71
80
  import type { StudioFormField, StudioServices } from "./services";
81
+ import type { UsageCache } from "../../../lib/usage/cache";
72
82
  import { studioAppAsset, type StudioApp } from "./studio-app";
73
83
  import { terminalAsset } from "./terminal-assets";
74
84
  import {
@@ -138,6 +148,7 @@ export interface StudioServerDeps {
138
148
  snapshots?: StudioSnapshotCache;
139
149
  vault?: VaultManager;
140
150
  reports?: ReportStore;
151
+ usage?: UsageCache;
141
152
  terminal?: Partial<TerminalRegistryOptions>;
142
153
  launchableAgents?: typeof launchableAgents;
143
154
  /**
@@ -159,7 +170,7 @@ export interface StudioServerOptions {
159
170
  terminal?: boolean;
160
171
  allowedHosts?: string[];
161
172
  publicOrigin?: string | null;
162
- /** Operator-pinned token; generated per start when absent and Studio is guarded. */
173
+ /** Operator-pinned token; generated per start when absent. */
163
174
  token?: string | null;
164
175
  detachMinutes?: number;
165
176
  /** Pins every terminal launch to this registered companion. */
@@ -234,6 +245,15 @@ function routeOf(url: URL, method: string, hasApp: boolean): RouteKind {
234
245
  writable: "start Studio with --writable to set the agent credential",
235
246
  };
236
247
  }
248
+ if (pathname === FACTORY_GIT_TOKENS_ROUTE) {
249
+ return method === "GET" || method === "HEAD"
250
+ ? { kind: "read", methods: [method] }
251
+ : {
252
+ kind: "write",
253
+ methods: [method],
254
+ writable: "start Studio with --writable to set Git tokens",
255
+ };
256
+ }
237
257
  if (pathname === TERMINAL_SOCKET_ROUTE) {
238
258
  return { kind: "terminal", methods: READS, privileged: true };
239
259
  }
@@ -370,6 +390,8 @@ export function createStudioFetch(
370
390
  const snapshots =
371
391
  deps.snapshots ?? createStudioSnapshotCache({ assembleCompanionPayload: companion });
372
392
  const vault = deps.vault ?? createVaultManager();
393
+ /** Created on the first Graph request, so other views never load the graph index. */
394
+ let graphs: Promise<SpecGraphCache> | null = null;
373
395
  const writable = options.writable === true;
374
396
  const policy = modePolicy(options.profile ?? "standard");
375
397
  const broker = deps.factoryClient !== undefined ? deps.factoryClient : factoryClient();
@@ -378,6 +400,8 @@ export function createStudioFetch(
378
400
  // Created before the terminal and the Outcomes, so neither needs the other.
379
401
  const sessions = new LiveSessions();
380
402
  const launchCompanion = options.launchCompanion ?? null;
403
+ /** Where the factory keeps the companions it cloned; the only place Studio deletes a folder. */
404
+ const companionsDir = process.env.MATE_COMPANIONS_DIR || "/companions";
381
405
  const outcomesPorts = (companionPath: string): OutcomesPorts => ({
382
406
  stages: () => stagesOf(companionPath),
383
407
  reports: {
@@ -436,6 +460,19 @@ export function createStudioFetch(
436
460
  // A person in control continues the factory's own conversation.
437
461
  takenOver: async (id) => (outcomes ? outcomes.takenOver(id) : null),
438
462
  }),
463
+ // Quitting Claude in a person's session hands the Outcome back to automation.
464
+ onWorksetExit: async (id, companionPath) => {
465
+ // Another companion's Workset may share the id; only the factory's own returns.
466
+ if (
467
+ !outcomes ||
468
+ path.resolve(companionPath) !== path.resolve(outcomes.companionPath)
469
+ ) {
470
+ return;
471
+ }
472
+ await outcomes.returnAfterExit(id);
473
+ // A return that starts no stage settles no run; the open board still has to learn of it.
474
+ boardChanged(companionDigest(outcomes.companionPath));
475
+ },
439
476
  }
440
477
  : {}),
441
478
  noGit: options.noGit === true,
@@ -525,14 +562,19 @@ export function createStudioFetch(
525
562
  outcomes.onChanged(() => boardChanged(digest));
526
563
  }
527
564
 
565
+ let usage: Promise<UsageCache> | undefined = deps.usage && Promise.resolve(deps.usage);
528
566
  const services: StudioServices = {
529
567
  writable,
530
568
  factoryMode: broker !== null,
569
+ keepsFolder: (companionPath) =>
570
+ broker !== null && !deletableWithin(companionPath, companionsDir),
531
571
  modePolicy: policy,
532
572
  page: collectPage,
533
573
  worksetAction: async (digest, id, action, field: StudioFormField) => {
534
574
  if (!writable) throw new WorksetError(NOT_WRITABLE);
535
- await outcomesFor(await companionPathOf(digest)).act(id, action, field);
575
+ const outcomesOfCompanion = outcomesFor(await companionPathOf(digest));
576
+ // Return and Delete end the person's session themselves, once accepted.
577
+ await outcomesOfCompanion.act(id, action, field);
536
578
  boardChanged(digest);
537
579
  },
538
580
  createOutcome: async (digest, field) => {
@@ -561,10 +603,26 @@ export function createStudioFetch(
561
603
  if (!writable) throw new VaultPathError("start Studio with --writable to enable saving");
562
604
  return vault.save(await companionPathOf(digest), path, content, token);
563
605
  },
606
+ graph: async (digest) => {
607
+ const companionPath = await companionPathOf(digest);
608
+ graphs ??= import("./graph").then(({ createSpecGraphCache }) => createSpecGraphCache());
609
+ return (await graphs).read(companionPath);
610
+ },
564
611
  reports: async (digest) => {
565
612
  await companionPathOf(digest);
566
613
  return reports.list(digest);
567
614
  },
615
+ usage: async (digest, request) => {
616
+ const companionPath = await companionPathOf(digest);
617
+ // A failed load is forgotten so Refresh can retry it.
618
+ usage ??= import("../../../lib/usage/cache")
619
+ .then(({ createUsageCache }) => createUsageCache())
620
+ .catch((error: unknown) => {
621
+ usage = undefined;
622
+ throw error;
623
+ });
624
+ return (await usage).read(companionPath, request);
625
+ },
568
626
  skillPreview: async (digest, agent, name, file) => {
569
627
  const { readSkillPreview } = await import("./skill-files");
570
628
  return readSkillPreview(await companionPathOf(digest), agent, name, file);
@@ -586,9 +644,42 @@ export function createStudioFetch(
586
644
  "Studio was started for this companion; it is not deleted.",
587
645
  );
588
646
  }
589
- const { deletedFolder } = await deleteRegisteredCompanion(companionPath);
647
+ // With the factory, only a folder in its companions directory is deleted.
648
+ const { deletedFolder } = await deleteRegisteredCompanion(
649
+ companionPath,
650
+ broker === null ? {} : { deleteWithin: companionsDir },
651
+ );
590
652
  return { deletedFolder };
591
653
  },
654
+ addRepository: async (digest, input) => {
655
+ if (!writable)
656
+ return { ok: false, reason: "start Studio with --writable to add repositories" };
657
+ if (broker === null)
658
+ return { ok: false, reason: "adding repositories needs the factory's broker" };
659
+ const added = await addRepository(await companionPathOf(digest), input, { client: broker });
660
+ if (added.ok && !added.existing) boardChanged(digest);
661
+ return added;
662
+ },
663
+ removeRepository: async (digest, identity) => {
664
+ if (!writable)
665
+ return { ok: false, reason: "start Studio with --writable to remove repositories" };
666
+ const removed = await removeRepository(await companionPathOf(digest), identity);
667
+ if (removed.ok) boardChanged(digest);
668
+ return removed;
669
+ },
670
+ addCompanion: async (input) => {
671
+ if (!writable) return { ok: false, reason: "start Studio with --writable to add companions" };
672
+ if (broker === null) {
673
+ return { ok: false, reason: "adding companions needs the factory's broker" };
674
+ }
675
+ const added =
676
+ input.kind === "url"
677
+ ? await addCompanionByUrl(input.url, { client: broker, companionsDir })
678
+ : await addCompanionByPath(input.path, {});
679
+ return added.ok
680
+ ? { ok: true, digest: companionDigest(added.companionPath), existing: added.existing }
681
+ : added;
682
+ },
592
683
  };
593
684
  const app = options.app ?? null;
594
685
 
@@ -623,7 +714,7 @@ export function createStudioFetch(
623
714
  return null;
624
715
  };
625
716
 
626
- const handler = async (
717
+ const dispatch = async (
627
718
  request: Request,
628
719
  server?: StudioUpgrader,
629
720
  ): Promise<Response | undefined> => {
@@ -681,6 +772,11 @@ export function createStudioFetch(
681
772
  return respond(await factoryCredentialResponse(broker, request));
682
773
  }
683
774
 
775
+ if (url.pathname === FACTORY_GIT_TOKENS_ROUTE) {
776
+ if (broker === null) return respond(notFound());
777
+ return respond(await factoryGitTokensResponse(broker, request));
778
+ }
779
+
684
780
  if (app) {
685
781
  const asset = await studioAppAsset(app, url.pathname);
686
782
  if (asset) return respond(asset);
@@ -770,6 +866,16 @@ export function createStudioFetch(
770
866
  return respond(notFound());
771
867
  };
772
868
 
869
+ // One place for every response, so refusals and the app's documents cannot miss it.
870
+ const handler = async (
871
+ request: Request,
872
+ server?: StudioUpgrader,
873
+ ): Promise<Response | undefined> => {
874
+ const response = await dispatch(request, server);
875
+ if (!response || new URL(request.url).pathname.startsWith(REPORT_VIEW_PREFIX)) return response;
876
+ return forbidFraming(response);
877
+ };
878
+
773
879
  handler.terminal = terminal;
774
880
  handler.services = services;
775
881
  handler.close = async () => {
@@ -779,6 +885,22 @@ export function createStudioFetch(
779
885
  return handler;
780
886
  }
781
887
 
888
+ /** A copy, because an app response such as `Response.redirect` has immutable headers. */
889
+ function forbidFraming(response: Response): Response {
890
+ const headers = new Headers(response.headers);
891
+ headers.set("x-frame-options", "DENY");
892
+ const policy = headers.get("content-security-policy")?.replace(/[;\s]+$/, "");
893
+ headers.set(
894
+ "content-security-policy",
895
+ policy ? `${policy}; frame-ancestors 'none'` : "frame-ancestors 'none'",
896
+ );
897
+ return new Response(response.body, {
898
+ status: response.status,
899
+ statusText: response.statusText,
900
+ headers,
901
+ });
902
+ }
903
+
782
904
  async function selectedCompanion(
783
905
  digest: string | null,
784
906
  collectInventory: () => Promise<StudioInventory>,
@@ -1,5 +1,9 @@
1
1
  import type { OutcomeAction } from "../../../lib/factory/outcomes/actions";
2
+ import type { UsageRequest } from "../../../lib/usage/cache";
3
+ import type { UsageResponse } from "../../../lib/usage/types";
4
+ import type { StudioSpecGraph } from "./graph";
2
5
  import type { StoredReport } from "./reports";
6
+ import type { RepositoryAddInput, RepositoryAddResult } from "./repository-add";
3
7
  import type { SkillAgent, SkillPreview } from "./skill-files";
4
8
  import type { StudioModePolicy } from "./selection";
5
9
  import type { VaultConflict, VaultSaved } from "./vault";
@@ -20,6 +24,11 @@ export interface StudioServices {
20
24
  readonly writable: boolean;
21
25
  /** Whether the factory broker is reachable, so the Agents panel can be offered. */
22
26
  readonly factoryMode: boolean;
27
+ /**
28
+ * Whether removing the companion only unregisters it: in factory mode, Studio deletes only
29
+ * folders inside the factory's companions directory.
30
+ */
31
+ keepsFolder(companionPath: string): boolean;
23
32
  /** The startup profile's Studio modes; every page selection is resolved through it. */
24
33
  readonly modePolicy: StudioModePolicy;
25
34
  /** Everything one view is derived from, for the address that asked for it. */
@@ -57,8 +66,12 @@ export interface StudioServices {
57
66
  content: string,
58
67
  token?: string,
59
68
  ): Promise<VaultSaved | VaultConflict>;
69
+ /** The spec graph of the companion's canonical specs and archives; read-only, rebuilt when they change. */
70
+ graph(companionDigest: string): Promise<StudioSpecGraph>;
60
71
  /** A registered companion's published reports, newest first; no paths or content. */
61
72
  reports(companionDigest: string): Promise<StoredReport[]>;
73
+ /** Read-only, explicitly refreshed usage; never collected for unrelated views. */
74
+ usage(companionDigest: string, request: UsageRequest): Promise<UsageResponse>;
62
75
  /** One installed skill's files and one of them rendered (SKILL.md by default); read-only. */
63
76
  skillPreview(
64
77
  companionDigest: string,
@@ -72,8 +85,35 @@ export interface StudioServices {
72
85
  * Studio was started for.
73
86
  */
74
87
  deleteCompanion(companionDigest: string): Promise<{ deletedFolder: boolean }>;
88
+ /**
89
+ * Adds a companion to Studio's registry, by Git URL (the factory clones it) or by the absolute
90
+ * path of a folder Studio can read (registered in place). Needs `writable` and factory mode.
91
+ * A refusal is an answer, not an error; `tokenKey` names the Git token that would unlock a
92
+ * private URL.
93
+ */
94
+ addCompanion(input: CompanionAddInput): Promise<CompanionAddResult>;
95
+ /** Adds a Working Repository to the companion's list; see {@link RepositoryAddInput}. */
96
+ addRepository(companionDigest: string, input: RepositoryAddInput): Promise<RepositoryAddResult>;
97
+ /** Removes an entry of the companion's list; a linked or configured repository is not one. */
98
+ removeRepository(
99
+ companionDigest: string,
100
+ identity: string,
101
+ ): Promise<{ ok: true } | { ok: false; reason: string }>;
75
102
  }
76
103
 
104
+ /**
105
+ * Adds a Working Repository to a companion's `factory.local.yaml`, by Git URL or from a local
106
+ * checkout's `origin`, after the factory checked the remote answers. Needs `writable` and factory
107
+ * mode; a refusal is an answer, and `tokenKey` names the Git token that would unlock a private one.
108
+ */
109
+ export type { RepositoryAddInput, RepositoryAddResult };
110
+
111
+ export type CompanionAddInput = { kind: "url"; url: string } | { kind: "path"; path: string };
112
+
113
+ export type CompanionAddResult =
114
+ | { ok: true; digest: string; existing: boolean }
115
+ | { ok: false; reason: string; tokenKey?: string };
116
+
77
117
  /** The request context Studio's application receives from core on every request. */
78
118
  export interface StudioRequestContext {
79
119
  studio: StudioServices;
@@ -1,6 +1,7 @@
1
1
  import { randomBytes, randomUUID } from "node:crypto";
2
+ import path from "node:path";
2
3
 
3
- import type { LiveSessions } from "../../../lib/factory/outcomes/sessions";
4
+ import type { LiveSessions, SessionCloseReason } from "../../../lib/factory/outcomes/sessions";
4
5
  import { tokensEqual } from "./access";
5
6
 
6
7
  export const TERMINAL_AGENTS = ["claude", "opencode"] as const;
@@ -184,7 +185,13 @@ export interface TerminalSessionInfo {
184
185
 
185
186
  /** A Workset session start, resolved on the server; the browser named only the Workset. */
186
187
  export type WorksetSessionResolution =
187
- | { companionPath: string; workset: { id: string; title: string }; argv: string[] }
188
+ | {
189
+ companionPath: string;
190
+ workset: { id: string; title: string };
191
+ argv: string[];
192
+ /** Shown before the session's output, e.g. the spawn's warnings. */
193
+ notice?: string;
194
+ }
188
195
  | { reason: string };
189
196
 
190
197
  /** A registered action and its subject; the client names them, the server builds the prompt. */
@@ -231,6 +238,11 @@ export interface TerminalRegistryOptions {
231
238
  limits?: Partial<typeof TERMINAL_LIMITS>;
232
239
  /** Where Workset sessions are recorded, for the factory's pickup and waiting runs. */
233
240
  sessions?: LiveSessions;
241
+ /**
242
+ * A Workset session's agent exited by itself, after the session was marked ended; not
243
+ * called when the session was ended, evicted, expired or Studio stopped.
244
+ */
245
+ onWorksetExit?: (worksetId: string, companionPath: string) => Promise<void>;
234
246
  }
235
247
 
236
248
  interface Session {
@@ -293,6 +305,9 @@ export class TerminalRegistry {
293
305
  this.spawn = options.spawn ?? bunTerminalSpawn;
294
306
  this.signal = options.signalGroup ?? signalGroup;
295
307
  this.now = options.now ?? Date.now;
308
+ options.sessions?.closeWith((companionPath, worksetId, reason) =>
309
+ this.endWorkset(companionPath, worksetId, reason),
310
+ );
296
311
  }
297
312
 
298
313
  list(): TerminalSessionInfo[] {
@@ -355,6 +370,23 @@ export class TerminalRegistry {
355
370
  return true;
356
371
  }
357
372
 
373
+ /**
374
+ * Ends the companion's live sessions for the Workset, if any: Return to automation and
375
+ * Delete close Claude themselves. `reason` tells the person which.
376
+ */
377
+ async endWorkset(
378
+ companionPath: string,
379
+ worksetId: string,
380
+ reason: SessionCloseReason,
381
+ ): Promise<void> {
382
+ const companion = path.resolve(companionPath);
383
+ const live = [...this.sessions.values()].filter(
384
+ (session) =>
385
+ session.workset?.id === worksetId && path.resolve(session.companionPath) === companion,
386
+ );
387
+ await Promise.all(live.map((session) => this.finish(session, { type: "ended", reason })));
388
+ }
389
+
358
390
  async stopAll(): Promise<void> {
359
391
  this.stopping = true;
360
392
  if (this.heartbeat) clearInterval(this.heartbeat);
@@ -488,6 +520,7 @@ export class TerminalRegistry {
488
520
  id,
489
521
  argv: resolved.argv,
490
522
  workset: resolved.workset,
523
+ ...(resolved.notice ? { notice: resolved.notice } : {}),
491
524
  });
492
525
  this.attachTo(connection, session, size);
493
526
  }
@@ -561,7 +594,16 @@ export class TerminalRegistry {
561
594
  if (session.workset) this.options.sessions?.begin(session.workset.id);
562
595
  void session.process.exited.then((status) => {
563
596
  session.exited = true;
564
- if (!session.ending) void this.finish(session, { type: "exit", status });
597
+ if (session.ending) return;
598
+ const worksetId = session.workset?.id;
599
+ void this.finish(session, { type: "exit", status })
600
+ // Only a quit (0, or 130 for Ctrl-C) hands the Outcome back; a crash leaves it with the person.
601
+ .then(() =>
602
+ worksetId && (status === 0 || status === 130)
603
+ ? this.options.onWorksetExit?.(worksetId, session.companionPath)
604
+ : undefined,
605
+ )
606
+ .catch(() => {});
565
607
  });
566
608
  return session;
567
609
  }
@@ -58,6 +58,9 @@ export interface MdAttributes {
58
58
  href?: string;
59
59
  /** A companion-relative markdown path the link opens in the vault. */
60
60
  note?: string;
61
+ /** An allowlisted Studio guide route or fragment. */
62
+ guide?: string;
63
+ id?: string;
61
64
  }
62
65
 
63
66
  const MARKDOWN_TARGET = /\.(md|markdown)$/i;
@@ -170,14 +173,18 @@ function markNormative(node: MdNode): MdNode {
170
173
 
171
174
  /** The same mapping the server-rendered vault used, producing data instead of markup. */
172
175
  class TreeMapper {
173
- constructor(private readonly path: string) {}
176
+ constructor(
177
+ private readonly path: string,
178
+ private readonly guide?: GuideContext,
179
+ ) {}
174
180
 
175
181
  blocks(tokens: Token[] | undefined): MdNode[] {
176
182
  const list = tokens ?? [];
177
183
  const nodes: MdNode[] = [];
178
184
  for (let index = 0; index < list.length; index += 1) {
179
185
  const token = list[index]!;
180
- const kind = token.type === "heading" ? sectionKind(token as Tokens.Heading) : null;
186
+ const kind =
187
+ !this.guide && token.type === "heading" ? sectionKind(token as Tokens.Heading) : null;
181
188
  if (!kind) {
182
189
  nodes.push(...this.block(token));
183
190
  continue;
@@ -261,7 +268,13 @@ class TreeMapper {
261
268
  return [];
262
269
  case "heading": {
263
270
  const heading = token as Tokens.Heading;
264
- return [el(headingTag(heading), this.inline(heading.tokens, heading.text))];
271
+ return [
272
+ el(
273
+ headingTag(heading),
274
+ this.inline(heading.tokens, heading.text),
275
+ this.guide ? { id: this.guide.heading(heading.text) } : undefined,
276
+ ),
277
+ ];
265
278
  }
266
279
  case "paragraph": {
267
280
  const paragraph = token as Tokens.Paragraph;
@@ -408,11 +421,79 @@ class TreeMapper {
408
421
  private link(link: Tokens.Link): MdNode {
409
422
  const label = this.inline(link.tokens, link.text);
410
423
  if (/^https?:\/\//i.test(link.href)) return el("a", label, { href: link.href });
424
+ if (this.guide) return el("a", label, this.guide.link(link.href));
411
425
  const note = resolveNoteLink(link.href, this.path);
412
426
  return note === null ? el("span", label) : el("a", label, { note });
413
427
  }
414
428
  }
415
429
 
430
+ interface GuideContext {
431
+ heading(text: string): string;
432
+ link(target: string): { guide: string } | { href: string };
433
+ }
434
+
435
+ /**
436
+ * Bundled Markdown only; rejects constructs the reader cannot faithfully render.
437
+ * A `routes` value that is an `https:` URL links out instead of to a guide topic.
438
+ */
439
+ export function guideTree(
440
+ source: string,
441
+ path: string,
442
+ routes: Readonly<Record<string, string>>,
443
+ ): MdNode[] {
444
+ const body = source.replace(FRONTMATTER, "");
445
+ const tokens = new Lexer({ gfm: true }).lex(body);
446
+ const fail = (value: string): never => {
447
+ throw new Error(`${path}: ${value}`);
448
+ };
449
+ const validate = (items: Token[]): void => {
450
+ for (const token of items) {
451
+ if (token.type === "code" || token.type === "codespan" || token.type === "escape") continue;
452
+ if (token.type === "html" || token.type === "image")
453
+ fail(`unsupported ${token.type}: ${token.raw}`);
454
+ if (
455
+ token.type === "text" &&
456
+ !("tokens" in token && token.tokens) &&
457
+ /[{}]|^\s*(?:import|export)\s/m.test(token.raw)
458
+ )
459
+ fail(`unsupported MDX: ${token.raw}`);
460
+ if ("tokens" in token && token.tokens) validate(token.tokens);
461
+ if (token.type === "list")
462
+ for (const item of (token as Tokens.List).items) {
463
+ if (item.task) fail("unsupported task list");
464
+ validate(item.tokens);
465
+ }
466
+ if (token.type === "table") {
467
+ const table = token as Tokens.Table;
468
+ for (const cell of [...table.header, ...table.rows.flat()]) validate(cell.tokens);
469
+ }
470
+ }
471
+ };
472
+ validate(tokens);
473
+ const counts = new Map<string, number>();
474
+ return new TreeMapper(path, {
475
+ heading(text) {
476
+ const slug = text
477
+ .toLowerCase()
478
+ .replace(/[^\p{L}\p{N}_\s-]/gu, "")
479
+ .replace(/\s/g, "-");
480
+ const count = counts.get(slug) ?? 0;
481
+ counts.set(slug, count + 1);
482
+ return count ? `${slug}-${count}` : slug;
483
+ },
484
+ link(target) {
485
+ if (target.startsWith("#")) return { guide: target };
486
+ const [page, fragment] = target.split("#");
487
+ const hash = fragment === undefined ? "" : `#${fragment}`;
488
+ const route = page && Object.hasOwn(routes, page) ? routes[page] : undefined;
489
+ if (!route) return fail(`unresolved or unsafe guide link: ${target}`);
490
+ return route.startsWith("https://")
491
+ ? { href: `${route}${hash}` }
492
+ : { guide: `${route}${hash}` };
493
+ },
494
+ }).blocks(tokens);
495
+ }
496
+
416
497
  /** A markdown file as data the browser renders; `path` is where its relative links start. */
417
498
  export function markdownTree(source: string, path: string): MdNode[] {
418
499
  const match = FRONTMATTER.exec(source);
@@ -1,11 +1,12 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
 
3
3
  import { type FactoryClient, factoryClient } from "../../../lib/factory/client";
4
- import type { AttachStart } from "../../../lib/factory/attach-client";
4
+ import { type AttachStart, prepareCommand } from "../../../lib/factory/attach-client";
5
5
  import { prepareWorkset } from "../../../lib/factory/prepare";
6
6
  import { writeWorkset } from "../../../lib/workset/record";
7
7
  import { effectiveLaunchCompanion } from "./terminal-launch";
8
8
  import type { StudioInventory } from "./inventory";
9
+ import type { WorksetSessionResolution } from "./terminal";
9
10
  import { NO_CREDENTIAL } from "../../../lib/factory/credential-store";
10
11
 
11
12
  /**
@@ -14,10 +15,6 @@ import { NO_CREDENTIAL } from "../../../lib/factory/credential-store";
14
15
  * the attach helper's argv. The browser names the Workset and nothing else.
15
16
  */
16
17
 
17
- export type WorksetLaunchResolution =
18
- | { companionPath: string; workset: { id: string; title: string }; argv: string[] }
19
- | { reason: string };
20
-
21
18
  export interface WorksetResolverOptions {
22
19
  collectInventory: () => Promise<StudioInventory>;
23
20
  launchCompanion?: string | null;
@@ -41,27 +38,50 @@ const HAS_CONVERSATION =
41
38
 
42
39
  /**
43
40
  * Interactive Claude shows its first-run login screen until `~/.claude.json` says onboarding is
44
- * done; the factory's headless turns never set it. Merged in place, every other key kept.
41
+ * done, and asks to trust the folder until it lists it as accepted; the factory's headless turns
42
+ * set neither. Run by exec in the Workset's worktree, so the trusted folder is that worktree and
43
+ * nothing the browser names. Merged in place, every other key kept.
45
44
  */
46
- const ONBOARDED = [
45
+ const CLAUDE_SETTINGS = [
47
46
  "node",
48
47
  "-e",
49
48
  [
50
49
  'const fs = require("fs");',
51
50
  "const file = `${process.env.HOME}/.claude.json`;",
52
51
  "let config = {};",
53
- 'try { config = JSON.parse(fs.readFileSync(file, "utf8")); } catch {}',
54
- "if (config.hasCompletedOnboarding !== true) {",
52
+ "let text = '';",
53
+ // A file that cannot be read is reported: nothing could be written there either.
54
+ 'try { text = fs.readFileSync(file, "utf8"); } catch (error) { if (error.code !== "ENOENT") { console.error(`${file} is unreadable: ${error.message}`); process.exit(1); } }',
55
+ "const isObject = (value) => value !== null && typeof value === 'object';",
56
+ // A blank file is empty config. A damaged one, as a write cut short leaves it, is kept beside it and replaced, so no session is blocked on a file nobody can reach.
57
+ "if (text.trim()) { let parsed; try { parsed = JSON.parse(text); } catch {} if (isObject(parsed) && !Array.isArray(parsed)) config = parsed; else { const kept = `${file}.damaged-${Date.now()}`; fs.copyFileSync(file, kept); console.error(`${file} was no JSON object; kept as ${kept}`); } }",
58
+ "const dir = process.cwd();",
59
+ "const projects = isObject(config.projects) ? config.projects : {};",
60
+ "const project = isObject(projects[dir]) ? projects[dir] : {};",
61
+ "if (config.hasCompletedOnboarding !== true || project.hasTrustDialogAccepted !== true) {",
62
+ " project.hasTrustDialogAccepted = true;",
55
63
  " config.hasCompletedOnboarding = true;",
64
+ " config.projects = { ...projects, [dir]: project };",
56
65
  " fs.writeFileSync(`${file}.tmp`, JSON.stringify(config, null, 2));",
57
66
  " fs.renameSync(`${file}.tmp`, file);",
58
67
  "}",
59
68
  ].join("\n"),
60
69
  ];
61
70
 
71
+ /** The first line of what a failed command said, for the dialog; the full output stays in the broker's log. */
72
+ function firstLine(text: string): string {
73
+ const line = text.trim().split(/\r?\n/)[0] ?? "";
74
+ return line.length > 200 ? `${line.slice(0, 200)}…` : line;
75
+ }
76
+
77
+ function failedStep(step: string, output: { stderr: string; stdout: string }): { reason: string } {
78
+ const detail = firstLine(output.stderr || output.stdout);
79
+ return { reason: `${step}${detail ? `: ${detail}` : ""}` };
80
+ }
81
+
62
82
  export function createWorksetResolver(
63
83
  options: WorksetResolverOptions,
64
- ): (id: string, digest: string | null, session: string) => Promise<WorksetLaunchResolution> {
84
+ ): (id: string, digest: string | null, session: string) => Promise<WorksetSessionResolution> {
65
85
  const clientFor = options.client ?? (() => factoryClient(options.env?.MATE_FACTORY_BROKER));
66
86
  const now = options.now ?? (() => new Date());
67
87
  return async (id, digest, session) => {
@@ -77,16 +97,25 @@ export function createWorksetResolver(
77
97
  if ((await client.info()).credential === null) {
78
98
  return { reason: NO_CREDENTIAL };
79
99
  }
80
- const record = await prepareWorkset(client, companion.path, id, options.env);
81
- const onboarded = await client.exec({ id, command: ONBOARDED });
82
- if (onboarded.status !== 0)
83
- return { reason: "the Workset's Claude settings could not be prepared" };
100
+ const { record, warnings } = await prepareWorkset(client, companion.path, id, options.env);
101
+ const settings = await client.exec({ id, command: CLAUDE_SETTINGS });
102
+ if (settings.status !== 0) {
103
+ return failedStep("the Workset's Claude settings could not be prepared", settings);
104
+ }
84
105
 
85
106
  const takenOver = (await options.takenOver?.(id)) ?? null;
86
107
  if (takenOver && !takenOver.claudeSession) {
87
108
  return { reason: "this Outcome has no factory conversation to take over" };
88
109
  }
89
110
  const resumeSession = takenOver?.claudeSession;
111
+ // The wrap and the index run here, their output captured, so the terminal opens on Claude.
112
+ const prepared = await client.exec({
113
+ id,
114
+ command: prepareCommand(options.noGit ? { noGit: true } : {}),
115
+ });
116
+ if (prepared.status !== 0) {
117
+ return failedStep("the Workset's session could not be prepared", prepared);
118
+ }
90
119
  let start: AttachStart;
91
120
  if (resumeSession) {
92
121
  start = "resume";
@@ -121,6 +150,10 @@ export function createWorksetResolver(
121
150
  ...(resumeSession ? ["--resume-session", resumeSession] : []),
122
151
  ...(options.noGit ? ["--no-git"] : []),
123
152
  ],
153
+ // The terminal needs CRLF: a bare LF moves down without returning.
154
+ ...(warnings.length > 0
155
+ ? { notice: warnings.join("\n").replaceAll(/\r?\n/g, "\r\n") }
156
+ : {}),
124
157
  };
125
158
  } catch (error) {
126
159
  return { reason: (error as Error).message };