@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,336 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ import {
5
+ archiveAnchors,
6
+ archiveDirOf,
7
+ filesBelow,
8
+ parseAnchor,
9
+ SPECS_RELATIVE_DIR,
10
+ } from "../../../lib/change-layout";
11
+ import { BOM, type ScopePair } from "../../../lib/openspec-scopes";
12
+ import { specScopes } from "./areas";
13
+ import {
14
+ areaNodeId,
15
+ capabilityNodeId,
16
+ GRAPH_ARTIFACTS,
17
+ GRAPH_EDGE_KINDS,
18
+ repositoryNodeId,
19
+ ROOT_AREA_LABEL,
20
+ type StudioGraphArchive,
21
+ type StudioGraphEdgeKind,
22
+ type StudioGraphNode,
23
+ type StudioSpecGraph,
24
+ } from "./graph-model";
25
+
26
+ export * from "./graph-model";
27
+
28
+ /**
29
+ * The Library's spec graph: capabilities, the repository/Area pairs they bind, and their
30
+ * repositories, linked by frontmatter binding, explicit mentions, and shared archives.
31
+ * Canonical spec contents are read; archives contribute directory and entry names only.
32
+ */
33
+
34
+ export interface GraphSpecSource {
35
+ capability: string;
36
+ content: string;
37
+ }
38
+
39
+ export interface GraphArchiveSource {
40
+ anchor: string;
41
+ /** Capabilities its delta specs name. */
42
+ capabilities: string[];
43
+ /** Entry names directly in the archive directory. */
44
+ entries: string[];
45
+ }
46
+
47
+ const WIKI_SPEC_LINK = /\[\[(?:[^\]|#]*?\/)?specs\/([^\]|#]+?)\/spec(?:\.md)?(?:[#|][^\]]*)?\]\]/g;
48
+ const MARKDOWN_SPEC_LINK = /\]\(<?([^)\s>]*?spec\.md)(?:#[^)\s>]*)?>?(?:\s+"[^"]*")?\)/g;
49
+ const BACKTICKED = /`([A-Za-z0-9][A-Za-z0-9._/-]*)`/g;
50
+ const SPECS_SUFFIX = /(?:^|\/)specs\/(.+)\/spec\.md$/;
51
+
52
+ /** Repository/Area pairs one spec binds, read as the Specs view reads them; BOM-tolerant. */
53
+ function scopeOf(source: string): ScopePair[] {
54
+ const content = source.startsWith(BOM) ? source.slice(BOM.length) : source;
55
+ return specScopes(content).flatMap(({ repository, area }) =>
56
+ repository && area ? [{ repository, area }] : [],
57
+ );
58
+ }
59
+
60
+ /** The capability a relative markdown link from `capability`'s spec names; null when none. */
61
+ function linkedCapability(capability: string, target: string): string | null {
62
+ // Site-absolute paths and URLs are not relative to the spec; only their `specs/` tail names it.
63
+ if (target.startsWith("/") || /^[a-z][a-z0-9+.-]*:/i.test(target)) {
64
+ return SPECS_SUFFIX.exec(decodeURI(target))?.[1] ?? null;
65
+ }
66
+ const from = `${SPECS_RELATIVE_DIR}/${capability}`;
67
+ const resolved = path.posix.normalize(path.posix.join(from, decodeURI(target)));
68
+ const prefix = `${SPECS_RELATIVE_DIR}/`;
69
+ if (resolved.startsWith(prefix) && resolved.endsWith("/spec.md")) {
70
+ return resolved.slice(prefix.length, -"/spec.md".length) || null;
71
+ }
72
+ return SPECS_SUFFIX.exec(target)?.[1] ?? null;
73
+ }
74
+
75
+ interface Mentions {
76
+ targets: Set<string>;
77
+ broken: Set<string>;
78
+ }
79
+
80
+ /** Explicit links and backticked ids in one spec, resolved against `known`. */
81
+ function resolveMentions(
82
+ capability: string,
83
+ content: string,
84
+ known: ReadonlySet<string>,
85
+ ): Mentions {
86
+ const targets = new Set<string>();
87
+ const broken = new Set<string>();
88
+ const explicit = (target: string | null) => {
89
+ if (!target || target === capability) return;
90
+ if (known.has(target)) targets.add(target);
91
+ else broken.add(target);
92
+ };
93
+ for (const match of content.matchAll(WIKI_SPEC_LINK)) explicit(match[1].trim());
94
+ for (const match of content.matchAll(MARKDOWN_SPEC_LINK)) {
95
+ try {
96
+ explicit(linkedCapability(capability, match[1]));
97
+ } catch {
98
+ // Malformed percent-encoding; not a resolvable link.
99
+ }
100
+ }
101
+ for (const match of content.matchAll(BACKTICKED)) {
102
+ const target = match[1];
103
+ if (target !== capability && known.has(target)) targets.add(target);
104
+ }
105
+ return { targets, broken };
106
+ }
107
+
108
+ /** The graph for already-read sources; pure, so it is tested without a companion. */
109
+ export function deriveSpecGraph(
110
+ specs: readonly GraphSpecSource[],
111
+ archives: readonly GraphArchiveSource[],
112
+ ): StudioSpecGraph {
113
+ const nodes: StudioGraphNode[] = [];
114
+ const indexOf = new Map<string, number>();
115
+ const node = (entry: StudioGraphNode): number => {
116
+ const existing = indexOf.get(entry.id);
117
+ if (existing !== undefined) return existing;
118
+ indexOf.set(entry.id, nodes.length);
119
+ nodes.push(entry);
120
+ return nodes.length - 1;
121
+ };
122
+
123
+ const sorted = specs.toSorted((a, b) => a.capability.localeCompare(b.capability));
124
+ const known = new Set(sorted.map((spec) => spec.capability));
125
+ for (const spec of sorted) {
126
+ node({ kind: "capability", id: capabilityNodeId(spec.capability), label: spec.capability });
127
+ }
128
+
129
+ const edges: number[] = [];
130
+ const edge = (source: number, target: number, kind: StudioGraphEdgeKind, weight = 1) => {
131
+ edges.push(source, target, GRAPH_EDGE_KINDS.indexOf(kind), weight);
132
+ };
133
+
134
+ const unbound: string[] = [];
135
+ const broken: StudioSpecGraph["broken"] = [];
136
+ const linkedAreas = new Set<number>();
137
+ for (const spec of sorted) {
138
+ const source = indexOf.get(capabilityNodeId(spec.capability))!;
139
+ const pairs = scopeOf(spec.content);
140
+ if (pairs.length === 0) unbound.push(spec.capability);
141
+ for (const { repository, area } of pairs) {
142
+ const repositoryIndex = node({
143
+ kind: "repository",
144
+ id: repositoryNodeId(repository),
145
+ label: repository,
146
+ });
147
+ const areaIndex = node({
148
+ kind: "area",
149
+ id: areaNodeId(repository, area),
150
+ label: area === "." ? ROOT_AREA_LABEL : area,
151
+ repository,
152
+ area,
153
+ });
154
+ edge(source, areaIndex, "binds");
155
+ if (!linkedAreas.has(areaIndex)) {
156
+ linkedAreas.add(areaIndex);
157
+ edge(areaIndex, repositoryIndex, "in");
158
+ }
159
+ }
160
+ const mentions = resolveMentions(spec.capability, spec.content, known);
161
+ for (const target of [...mentions.targets].toSorted()) {
162
+ edge(source, indexOf.get(capabilityNodeId(target))!, "mentions");
163
+ }
164
+ for (const target of [...mentions.broken].toSorted()) {
165
+ broken.push({ from: spec.capability, target });
166
+ }
167
+ }
168
+
169
+ const dated = archives
170
+ .flatMap((archive) => {
171
+ const anchor = parseAnchor(archive.anchor);
172
+ const capabilities = [...new Set(archive.capabilities)].filter((id) => known.has(id));
173
+ return anchor && capabilities.length > 0
174
+ ? [{ ...archive, parsed: anchor, capabilities }]
175
+ : [];
176
+ })
177
+ // Dated anchors sort newest first in code-unit order.
178
+ .toSorted((a, b) => (a.anchor === b.anchor ? 0 : a.anchor < b.anchor ? 1 : -1));
179
+
180
+ const history: number[][] = nodes.map(() => []);
181
+ const weights = new Map<string, number>();
182
+ const graphArchives: StudioGraphArchive[] = dated.map((archive, archiveIndex) => {
183
+ const members = archive.capabilities
184
+ .map((capability) => indexOf.get(capabilityNodeId(capability))!)
185
+ .toSorted((a, b) => a - b);
186
+ for (const member of members) history[member].push(archiveIndex);
187
+ for (let left = 0; left < members.length; left++) {
188
+ for (let right = left + 1; right < members.length; right++) {
189
+ const key = `${members[left]}:${members[right]}`;
190
+ weights.set(key, (weights.get(key) ?? 0) + 1);
191
+ }
192
+ }
193
+ return {
194
+ anchor: archive.anchor,
195
+ name: archive.parsed.name,
196
+ archivedOn: archive.parsed.date,
197
+ artifacts: GRAPH_ARTIFACTS.filter((artifact) => archive.entries.includes(artifact)),
198
+ };
199
+ });
200
+ for (const [key, weight] of weights) {
201
+ const [source, target] = key.split(":").map(Number);
202
+ edge(source, target, "co-change", weight);
203
+ }
204
+
205
+ return { nodes, edges, archives: graphArchives, history, unbound, broken };
206
+ }
207
+
208
+ const specsDirOf = (companionPath: string) =>
209
+ path.join(companionPath, ...SPECS_RELATIVE_DIR.split("/"));
210
+
211
+ /** Canonical specs with their contents, and dated archives by entry names. */
212
+ async function readSpecGraphSources(companionPath: string): Promise<{
213
+ specs: GraphSpecSource[];
214
+ archives: GraphArchiveSource[];
215
+ }> {
216
+ const specsDir = specsDirOf(companionPath);
217
+ const specFiles = (await filesBelow(specsDir)).filter(
218
+ (file) => path.posix.basename(file) === "spec.md" && path.posix.dirname(file) !== ".",
219
+ );
220
+ const known = new Set(specFiles.map((file) => path.posix.dirname(file)));
221
+ const parents = parentsOf(known);
222
+ const archiveDir = archiveDirOf(companionPath);
223
+ const [specs, archives] = await Promise.all([
224
+ Promise.all(
225
+ specFiles.map(async (file) => ({
226
+ capability: path.posix.dirname(file),
227
+ content: await fs.readFile(path.join(specsDir, ...file.split("/")), "utf8").catch(() => ""),
228
+ })),
229
+ ),
230
+ archiveAnchors(companionPath).then((anchors) =>
231
+ Promise.all(
232
+ anchors.map(async (anchor) => {
233
+ const dir = path.join(archiveDir, anchor);
234
+ const [capabilities, entries] = await Promise.all([
235
+ deltaCapabilities(path.join(dir, "specs"), known, parents),
236
+ fs.readdir(dir).catch((): string[] => []),
237
+ ]);
238
+ return { anchor, capabilities, entries };
239
+ }),
240
+ ),
241
+ ),
242
+ ]);
243
+ return { specs, archives };
244
+ }
245
+
246
+ /** Every path prefix of a nested capability id: `acme/billing` yields `acme`. */
247
+ function parentsOf(ids: Iterable<string>): Set<string> {
248
+ const parents = new Set<string>();
249
+ for (const id of ids) {
250
+ const parts = id.split("/");
251
+ for (let depth = 1; depth < parts.length; depth++) parents.add(parts.slice(0, depth).join("/"));
252
+ }
253
+ return parents;
254
+ }
255
+
256
+ /**
257
+ * The canonical capabilities an archive's delta specs name. A folder named after a known leaf
258
+ * capability counts without reading inside it; other folders, and known ones that have nested
259
+ * capabilities, are descended, and a known parent counts only when it holds its own `spec.md`.
260
+ * On large companions this is one directory read per archive instead of one per delta spec.
261
+ */
262
+ async function deltaCapabilities(
263
+ specsDir: string,
264
+ known: ReadonlySet<string>,
265
+ parents: ReadonlySet<string>,
266
+ ): Promise<string[]> {
267
+ const found: string[] = [];
268
+ const visit = async (relative: string): Promise<void> => {
269
+ const dir = relative ? path.join(specsDir, ...relative.split("/")) : specsDir;
270
+ const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => []);
271
+ if (
272
+ known.has(relative) &&
273
+ entries.some((entry) => entry.isFile() && entry.name === "spec.md")
274
+ ) {
275
+ found.push(relative);
276
+ }
277
+ await Promise.all(
278
+ entries.map(async (entry) => {
279
+ if (!entry.isDirectory()) return;
280
+ const id = relative ? `${relative}/${entry.name}` : entry.name;
281
+ if (!known.has(id) || parents.has(id)) await visit(id);
282
+ else found.push(id);
283
+ }),
284
+ );
285
+ };
286
+ await visit("");
287
+ return found;
288
+ }
289
+
290
+ export async function buildSpecGraph(companionPath: string): Promise<StudioSpecGraph> {
291
+ const { specs, archives } = await readSpecGraphSources(companionPath);
292
+ return deriveSpecGraph(specs, archives);
293
+ }
294
+
295
+ /**
296
+ * What the graph is built from, without reading contents: each canonical spec file's size and
297
+ * modification time, and the dated archive names. Equal fingerprints build equal graphs.
298
+ */
299
+ export async function specGraphFingerprint(companionPath: string): Promise<string> {
300
+ const specsDir = specsDirOf(companionPath);
301
+ const [files, anchors] = await Promise.all([filesBelow(specsDir), archiveAnchors(companionPath)]);
302
+ const stamps = await Promise.all(
303
+ files.map(async (file) => {
304
+ const stat = await fs.stat(path.join(specsDir, ...file.split("/"))).catch(() => null);
305
+ return `${file}:${stat?.size ?? -1}:${stat?.mtimeMs ?? -1}`;
306
+ }),
307
+ );
308
+ return [...stamps, "", ...anchors].join("\n");
309
+ }
310
+
311
+ export interface SpecGraphCache {
312
+ /** The companion's graph, rebuilt only when its fingerprint changes. */
313
+ read(companionPath: string): Promise<StudioSpecGraph>;
314
+ }
315
+
316
+ /** Holds one graph per companion; reads for the same fingerprint share one build. */
317
+ export function createSpecGraphCache(
318
+ build: (companionPath: string) => Promise<StudioSpecGraph> = buildSpecGraph,
319
+ fingerprint: (companionPath: string) => Promise<string> = specGraphFingerprint,
320
+ ): SpecGraphCache {
321
+ const held = new Map<string, { basis: string; graph: Promise<StudioSpecGraph> }>();
322
+ return {
323
+ async read(companionPath) {
324
+ const basis = await fingerprint(companionPath);
325
+ const entry = held.get(companionPath);
326
+ if (entry && entry.basis === basis) return entry.graph;
327
+ const graph = build(companionPath);
328
+ held.set(companionPath, { basis, graph });
329
+ // A failed build is not held, so the next read tries again.
330
+ graph.catch(() => {
331
+ if (held.get(companionPath)?.graph === graph) held.delete(companionPath);
332
+ });
333
+ return graph;
334
+ },
335
+ };
336
+ }
@@ -229,10 +229,10 @@ function splitHosts(value: string): string[] {
229
229
  * browser at it. Runs in the foreground on an operating-system-assigned
230
230
  * loopback port and dies with the process: no daemon, no stop command, and no
231
231
  * state written anywhere.
232
- * @remarks Both invocations are read-only unless passed `--writable`.
233
- * `--terminal` adds the agent terminal and guards Studio with a per-start
234
- * access token; `serve` is always guarded. Neither invocation resolves a
235
- * Repository Link, so it runs from any directory.
232
+ * @remarks Both invocations are read-only unless passed `--writable`. Every
233
+ * start is guarded by a per-start access token, and `--terminal` adds the
234
+ * agent terminal. Neither invocation resolves a Repository Link, so it runs
235
+ * from any directory.
236
236
  */
237
237
  export async function runStudioCommand(
238
238
  argv: string[] = [],
@@ -8,7 +8,11 @@ import {
8
8
  SPECS_RELATIVE_DIR,
9
9
  } from "../../../lib/change-layout";
10
10
  import { companionTicketFormat, type TicketFormat } from "../../../lib/delivery/branches";
11
- import { linkedRepositoryIdentities } from "../../../lib/workset/repositories";
11
+ import {
12
+ type LinkedRepositoryCatalog,
13
+ linkedRepositoryCatalog,
14
+ type RepositorySourceKind,
15
+ } from "../../../lib/workset/repositories";
12
16
  import type { readWorksets, WorksetProblem } from "../../../lib/workset/record";
13
17
  import type { WorksetStageId, WorksetTurn } from "../../../lib/workset/stage";
14
18
  import {
@@ -19,7 +23,7 @@ import {
19
23
  import { errorMessage } from "../../../runtime/error-message";
20
24
  import { canonicalSpecsFor, discoverArchives } from "../artifact/pending/discovery";
21
25
  import { defaultGitOps } from "../artifact/finish/git";
22
- import { readSpecAreas } from "./areas";
26
+ import { readSpecScopes } from "./areas";
23
27
  import { collectSkillInventory, type StudioSkillInventory } from "./mate-inventory";
24
28
  import {
25
29
  listChanges,
@@ -48,10 +52,18 @@ export interface StudioChange {
48
52
  issueCount?: number;
49
53
  }
50
54
 
55
+ /** One repository/Area pair a spec binds; at least one of the two is set. */
56
+ export interface StudioSpecScope {
57
+ /** `org/repository`, or the value the spec names when it matches no linked repository. */
58
+ repository?: string;
59
+ area?: string;
60
+ }
61
+
51
62
  export interface StudioSpec {
52
63
  capability: string;
53
64
  requirementCount?: number;
54
- areas: string[];
65
+ /** Sorted by repository, pairs without one last, then by Area. */
66
+ scopes: StudioSpecScope[];
55
67
  valid?: boolean;
56
68
  issueCount?: number;
57
69
  }
@@ -98,6 +110,10 @@ export interface StudioCompanionPayload {
98
110
  worksets: StudioWorkset[];
99
111
  /** `org/repository` identities linked to the companion: what a new Workset may name. */
100
112
  linkedRepositories: string[];
113
+ /** Where each of those comes from, so only the list's own can be removed in Studio. */
114
+ repositorySources?: Record<string, RepositorySourceKind>;
115
+ /** Each repository's Git token key, `host/org` of its clone URL, matched against stored token keys. */
116
+ repositoryKeys?: Record<string, string>;
101
117
  /** The companion's ticket setting; the Outcome form offers a Ticket field only for `jira`. */
102
118
  ticketFormat: TicketFormat;
103
119
  /** Records that could not be read, by path and reason. */
@@ -117,7 +133,7 @@ export interface CompanionPayloadDeps {
117
133
  readAllChangeStatus?: typeof readAllChangeStatus;
118
134
  validateAll?: typeof validateAll;
119
135
  readWorkflowTopology?: typeof readWorkflowTopology;
120
- readSpecAreas?: (specsRoot: string, specId: string) => Promise<string[]>;
136
+ readSpecScopes?: typeof readSpecScopes;
121
137
  collectSkillInventory?: typeof collectSkillInventory;
122
138
  discoverArchives?: typeof discoverArchives;
123
139
  canonicalSpecsFor?: typeof canonicalSpecsFor;
@@ -125,7 +141,7 @@ export interface CompanionPayloadDeps {
125
141
  readUncommittedPaths?: (companionPath: string) => Promise<string[]>;
126
142
  hasArchivedProposal?: (companionPath: string, anchor: string) => Promise<boolean>;
127
143
  readWorksets?: typeof readWorksets;
128
- linkedRepositoryIdentities?: typeof linkedRepositoryIdentities;
144
+ linkedRepositoryCatalog?: typeof linkedRepositoryCatalog;
129
145
  ticketFormat?: typeof companionTicketFormat;
130
146
  archiveAnchors?: typeof archiveAnchors;
131
147
  /** Whether an archive's Publication Merge Gate is open: merged, not applicable, or legacy. */
@@ -307,8 +323,13 @@ export async function assembleCompanionPayload(
307
323
  const collectStatus = deps.readAllChangeStatus ?? readAllChangeStatus;
308
324
  const collectValidation = deps.validateAll ?? validateAll;
309
325
  const collectTopology = deps.readWorkflowTopology ?? readWorkflowTopology;
310
- const collectAreas = deps.readSpecAreas ?? readSpecAreas;
326
+ const collectScopes = deps.readSpecScopes ?? readSpecScopes;
311
327
  const collectSkills = deps.collectSkillInventory ?? collectSkillInventory;
328
+ // Started now: spec scopes need its registry IDs, and it runs alongside the OpenSpec reads.
329
+ const linked = (deps.linkedRepositoryCatalog ?? linkedRepositoryCatalog)(companionPath).then(
330
+ (catalog) => ({ catalog }),
331
+ (error: unknown) => ({ error }),
332
+ );
312
333
 
313
334
  const [changeList, specList, status, validation, topology, skillInventory, shipped] =
314
335
  await Promise.all([
@@ -373,27 +394,31 @@ export async function assembleCompanionPayload(
373
394
  companionPath;
374
395
  const specsRoot = path.join(planningRoot, "openspec", "specs");
375
396
 
397
+ const linkedResult = await linked;
398
+ if ("error" in linkedResult) {
399
+ warnings.push(`linked repositories: ${errorMessage(linkedResult.error)}`);
400
+ }
401
+ const catalog: LinkedRepositoryCatalog =
402
+ "catalog" in linkedResult
403
+ ? linkedResult.catalog
404
+ : { identities: [], aliases: new Map(), kinds: new Map(), keys: new Map(), problem: null };
405
+ if (catalog.problem) warnings.push(catalog.problem);
406
+
376
407
  const specs: StudioSpec[] = await Promise.all(
377
408
  (specList.value.specs ?? []).map(async (spec) => ({
378
409
  capability: spec.id,
379
410
  ...(spec.requirementCount === undefined ? {} : { requirementCount: spec.requirementCount }),
380
- areas: await collectAreas(specsRoot, spec.id),
411
+ scopes: await collectScopes(specsRoot, spec.id, undefined, catalog.aliases),
381
412
  ...validationOf(validationItems, spec.id, "spec"),
382
413
  })),
383
414
  );
384
415
 
385
416
  const shippedChanges = "changes" in shipped ? shipped.changes : [];
386
- const [worksets, linkedRepositories, ticketFormat] = await Promise.all([
417
+ const [worksets, ticketFormat] = await Promise.all([
387
418
  collectWorksets(companionPath, changes, shippedChanges, deps).catch((error: unknown) => {
388
419
  warnings.push(`worksets: ${errorMessage(error)}`);
389
420
  return { worksets: [], problems: [] };
390
421
  }),
391
- (deps.linkedRepositoryIdentities ?? linkedRepositoryIdentities)(companionPath).catch(
392
- (error: unknown) => {
393
- warnings.push(`linked repositories: ${errorMessage(error)}`);
394
- return [];
395
- },
396
- ),
397
422
  (deps.ticketFormat ?? companionTicketFormat)(companionPath).catch(
398
423
  (error: unknown): TicketFormat => {
399
424
  warnings.push(`ticket setting: ${errorMessage(error)}`);
@@ -421,7 +446,9 @@ export async function assembleCompanionPayload(
421
446
  "skills" in skillInventory ? skillInventory.skills : { claude: [], opencode: [], agents: [] },
422
447
  topology: topology.ok ? topology.value : null,
423
448
  worksets: worksets.worksets,
424
- linkedRepositories,
449
+ linkedRepositories: catalog.identities,
450
+ repositorySources: Object.fromEntries(catalog.kinds),
451
+ repositoryKeys: Object.fromEntries(catalog.keys),
425
452
  ticketFormat,
426
453
  worksetProblems: worksets.problems,
427
454
  warnings,
@@ -0,0 +1,116 @@
1
+ import path from "node:path";
2
+
3
+ import { workingRepoGit } from "../../../lib/delivery/branches";
4
+ import { checkedCloneUrl } from "../../../lib/factory/clone-url";
5
+ import type { FactoryClient } from "../../../lib/factory/client";
6
+ import { gitKeyOf } from "../../../lib/factory/git-credential-store";
7
+ import { FactoryError } from "../../../lib/factory/ids";
8
+ import { pathIsDirectory } from "../../../lib/fs-utils";
9
+ import { addLocalRepository, removeLocalRepository } from "../../../lib/workset/factory-local";
10
+ import { linkedRepositoryIdentities } from "../../../lib/workset/repositories";
11
+
12
+ export type RepositoryAddInput = { kind: "url"; url: string } | { kind: "path"; path: string };
13
+
14
+ /** What adding a Working Repository came to; a refusal carries its reason as shown. */
15
+ export type RepositoryAddResult =
16
+ | { ok: true; identity: string; existing: boolean; warning?: string }
17
+ /** `tokenKey` is the `host/org` a Git token would unlock, when the check was refused for one. */
18
+ | { ok: false; reason: string; tokenKey?: string };
19
+
20
+ export interface RepositoryAddDeps {
21
+ client: Pick<FactoryClient, "checkRemote">;
22
+ env?: NodeJS.ProcessEnv;
23
+ isDirectory?: (target: string) => Promise<boolean>;
24
+ /** The `origin` URL of a checkout; null when it has none or is no checkout. */
25
+ originOf?: (checkout: string) => Promise<string | null>;
26
+ }
27
+
28
+ const refusal = (reason: string): RepositoryAddResult => ({ ok: false, reason });
29
+
30
+ /** The clone URL a local checkout stands for: its `origin`. */
31
+ async function urlOfCheckout(
32
+ rawPath: string,
33
+ deps: RepositoryAddDeps,
34
+ ): Promise<{ url: string } | RepositoryAddResult> {
35
+ const given = rawPath.trim();
36
+ if (!path.isAbsolute(given)) return refusal("Give the absolute path of the checkout.");
37
+ const checkout = path.resolve(given);
38
+ if (!(await (deps.isDirectory ?? pathIsDirectory)(checkout))) {
39
+ return refusal(`${checkout} is not a folder Studio can read.`);
40
+ }
41
+ const origin = await (deps.originOf ?? ((dir) => workingRepoGit(dir).remoteUrl()))(checkout);
42
+ if (!origin) return refusal(`${checkout} is not a Git checkout with an origin.`);
43
+ return { url: origin };
44
+ }
45
+
46
+ /**
47
+ * Adds a Working Repository to the companion's `factory.local.yaml`, by Git URL or from a local
48
+ * checkout's `origin`. One already offered from any source is reported and left alone; a remote
49
+ * that does not answer adds nothing, and a refusal for authentication names the Git token that
50
+ * would unlock it.
51
+ */
52
+ export async function addRepository(
53
+ companionPath: string,
54
+ input: RepositoryAddInput,
55
+ deps: RepositoryAddDeps,
56
+ ): Promise<RepositoryAddResult> {
57
+ let url: string;
58
+ if (input.kind === "path") {
59
+ const found = await urlOfCheckout(input.path, deps);
60
+ if (!("url" in found)) return found;
61
+ url = found.url;
62
+ } else {
63
+ url = input.url;
64
+ }
65
+
66
+ let remote;
67
+ try {
68
+ remote = checkedCloneUrl(url);
69
+ } catch (error) {
70
+ if (error instanceof FactoryError) return refusal(error.message);
71
+ throw error;
72
+ }
73
+ if ((await linkedRepositoryIdentities(companionPath, deps.env)).includes(remote.identity)) {
74
+ return { ok: true, identity: remote.identity, existing: true };
75
+ }
76
+
77
+ try {
78
+ await deps.client.checkRemote(remote.url);
79
+ } catch (error) {
80
+ if (!(error instanceof FactoryError)) throw error;
81
+ const key = error.code === "auth" ? gitKeyOf(remote.url) : null;
82
+ return {
83
+ ok: false,
84
+ reason: error.message,
85
+ ...(key ? { tokenKey: `${key.host}/${key.org}` } : {}),
86
+ };
87
+ }
88
+
89
+ try {
90
+ const { warning } = await addLocalRepository(companionPath, remote.url);
91
+ return {
92
+ ok: true,
93
+ identity: remote.identity,
94
+ existing: false,
95
+ ...(warning ? { warning } : {}),
96
+ };
97
+ } catch (error) {
98
+ return refusal(error instanceof Error ? error.message : "The repository was not added.");
99
+ }
100
+ }
101
+
102
+ /** Removes an entry of `factory.local.yaml`; a linked or environment repository is not one. */
103
+ export async function removeRepository(
104
+ companionPath: string,
105
+ identity: string,
106
+ ): Promise<{ ok: true } | { ok: false; reason: string }> {
107
+ try {
108
+ if (await removeLocalRepository(companionPath, identity)) return { ok: true };
109
+ } catch (error) {
110
+ return { ok: false, reason: error instanceof Error ? error.message : "Nothing was removed." };
111
+ }
112
+ return {
113
+ ok: false,
114
+ reason: `${identity} is not in the list Studio manages; a linked or configured repository is removed where it was set.`,
115
+ };
116
+ }
@@ -18,6 +18,12 @@ export const FACTORY_WORKSETS_ROUTE = "/api/factory/worksets";
18
18
  */
19
19
  export const FACTORY_CREDENTIAL_ROUTE = "/api/factory/credential";
20
20
 
21
+ /**
22
+ * The Git access panel: `GET` the Git tokens' keys with their source and date, `PUT`
23
+ * `{key, token}` to set one, `DELETE` `{key}` to clear one set in Studio. Factory mode only.
24
+ */
25
+ export const FACTORY_GIT_TOKENS_ROUTE = "/api/factory/git-tokens";
26
+
21
27
  /** `GET` a Workset's bounded run log as text. */
22
28
  export function factoryLogRoute(id: string): string {
23
29
  return `${FACTORY_WORKSETS_ROUTE}/${encodeURIComponent(id)}/log`;
@@ -6,19 +6,25 @@ export type StudioView =
6
6
  | "dashboard"
7
7
  | "factory"
8
8
  | "workflow"
9
+ | "getting-started"
9
10
  | "specs"
10
11
  | "skills"
11
12
  | "vault"
12
- | "reports";
13
+ | "reports"
14
+ | "usage"
15
+ | "graph";
13
16
 
14
17
  export const STUDIO_VIEWS: readonly StudioView[] = [
15
18
  "dashboard",
16
19
  "factory",
17
20
  "workflow",
21
+ "getting-started",
18
22
  "specs",
19
23
  "skills",
20
24
  "vault",
21
25
  "reports",
26
+ "usage",
27
+ "graph",
22
28
  ];
23
29
 
24
30
  /** A lens on the views offered, never access control. */
@@ -28,13 +34,13 @@ export const STUDIO_MODES: readonly StudioMode[] = ["engineering", "analysis"];
28
34
 
29
35
  /** Views only the mode is offered, in navigation order. */
30
36
  export const MODE_VIEWS: Readonly<Record<StudioMode, readonly StudioView[]>> = {
31
- engineering: ["dashboard", "factory", "workflow", "skills"],
37
+ engineering: ["dashboard", "factory", "workflow", "skills", "getting-started"],
32
38
  // The same `dashboard` id; `Content` renders each mode's own Overview.
33
39
  analysis: ["dashboard"],
34
40
  };
35
41
 
36
42
  /** Views every mode is offered, in navigation order. */
37
- export const SHARED_VIEWS: readonly StudioView[] = ["vault", "specs", "reports"];
43
+ export const SHARED_VIEWS: readonly StudioView[] = ["vault", "specs", "reports", "graph", "usage"];
38
44
 
39
45
  /** Where a mode lands when its URL names no view, or one it is not offered. */
40
46
  export const LANDING_VIEW: Readonly<Record<StudioMode, StudioView>> = {
@@ -92,6 +98,8 @@ export const REFRESH_PARAM = "refresh";
92
98
  export const FILE_PARAM = "path";
93
99
  export const DIR_PARAM = "dir";
94
100
  export const MODE_PARAM = "mode";
101
+ /** The Graph view's selected node id; Studio's graph route reads it, no other view does. */
102
+ export const NODE_PARAM = "node";
95
103
 
96
104
  /** Every URL parameter Studio names; no other module writes one out. */
97
105
  export const STUDIO_PARAMS: readonly string[] = [
@@ -103,6 +111,7 @@ export const STUDIO_PARAMS: readonly string[] = [
103
111
  FILE_PARAM,
104
112
  DIR_PARAM,
105
113
  MODE_PARAM,
114
+ NODE_PARAM,
106
115
  ];
107
116
 
108
117
  /** Filled into a prompt when no change is named, so a prompt is never half-written. */