@uniqbit/mate-core 0.18.5 → 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 (532) hide show
  1. package/claude-capability-plugins/companion-mentions/.claude-plugin/marketplace.json +14 -0
  2. package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +8 -0
  3. package/claude-capability-plugins/companion-mentions/hooks/companion.ts +457 -0
  4. package/claude-capability-plugins/companion-mentions/hooks/hooks.json +1 -0
  5. package/claude-capability-plugins/companion-mentions/hooks/register.ts +403 -0
  6. package/claude-plugin/hooks/companion-instructions.mjs +9 -0
  7. package/claude-plugin/hooks/hooks.json +50 -2
  8. package/claude-plugin/hooks/rtk-worktree-git.mjs +58 -0
  9. package/claude-plugin/hooks/session-attention.mjs +10 -0
  10. package/claude-plugin/hooks/session-end.mjs +9 -0
  11. package/claude-plugin/hooks/session-guidance.mjs +1 -1
  12. package/claude-plugin/hooks/tokensave-route.mjs +52 -0
  13. package/opencode-plugin/src/server.ts +25 -3
  14. package/opencode-plugin/src/tui.tsx +3 -1
  15. package/opencode-plugin/tui.tsx +4 -1
  16. package/package.json +53 -15
  17. package/src/brand/art.generated.ts +69 -0
  18. package/src/brand/index.ts +12 -0
  19. package/src/brand/palette.ts +19 -0
  20. package/src/brand/svg.generated.ts +8 -0
  21. package/src/brand/terminal.ts +88 -0
  22. package/src/brand/types.ts +33 -0
  23. package/src/cli/commands/artifact/apply-context.ts +275 -0
  24. package/src/cli/commands/artifact/artifact.ts +12 -0
  25. package/src/cli/commands/artifact/delivery/archive.ts +125 -0
  26. package/src/cli/commands/artifact/delivery/branch-flags.ts +55 -0
  27. package/src/cli/commands/artifact/delivery/environment.ts +147 -0
  28. package/src/cli/commands/artifact/delivery/link.ts +210 -0
  29. package/src/cli/commands/artifact/delivery/output.ts +104 -0
  30. package/src/cli/commands/artifact/finish/command.ts +83 -8
  31. package/src/cli/commands/artifact/finish/engine.ts +91 -14
  32. package/src/cli/commands/artifact/finish/finisher.ts +10 -0
  33. package/src/cli/commands/artifact/finish/git.ts +132 -19
  34. package/src/cli/commands/artifact/finish/openspec.ts +180 -138
  35. package/src/cli/commands/artifact/finish/secret-scan.ts +43 -0
  36. package/src/cli/commands/artifact/finish/worktree-cleanup.ts +92 -0
  37. package/src/cli/commands/artifact/pending/command.ts +31 -3
  38. package/src/cli/commands/artifact/pending/discovery.ts +21 -57
  39. package/src/cli/commands/cap/graphify.ts +52 -3
  40. package/src/cli/commands/cap/index-cmd.ts +71 -15
  41. package/src/cli/commands/cap/openspec.ts +13 -25
  42. package/src/cli/commands/cap/tokensave.ts +7 -5
  43. package/src/cli/commands/companion/companion.ts +1 -1
  44. package/src/cli/commands/companion/link.ts +50 -5
  45. package/src/cli/commands/companion/open.ts +101 -51
  46. package/src/cli/commands/companion/sync.ts +10 -0
  47. package/src/cli/commands/companion/tui.ts +17 -7
  48. package/src/cli/commands/companion/update.ts +144 -66
  49. package/src/cli/commands/doctor.ts +317 -7
  50. package/src/cli/commands/factory/factory.ts +311 -0
  51. package/src/cli/commands/install.ts +180 -45
  52. package/src/cli/commands/launch/claude.ts +2 -0
  53. package/src/cli/commands/launch/shared.ts +48 -16
  54. package/src/cli/commands/plugin/install.ts +36 -15
  55. package/src/cli/commands/plugin/plugin.ts +3 -2
  56. package/src/cli/commands/report/adapter.ts +11 -2
  57. package/src/cli/commands/report/contract.ts +21 -0
  58. package/src/cli/commands/report/highlight.ts +34 -4
  59. package/src/cli/commands/report/index.ts +186 -171
  60. package/src/cli/commands/report/markdown.ts +105 -0
  61. package/src/cli/commands/report/palette.ts +118 -0
  62. package/src/cli/commands/report/renderer.ts +456 -153
  63. package/src/cli/commands/report/types.ts +16 -0
  64. package/src/cli/commands/session/context.ts +102 -0
  65. package/src/cli/commands/session/prepare.ts +32 -4
  66. package/src/cli/commands/session/registry.ts +90 -0
  67. package/src/cli/commands/setup.ts +50 -24
  68. package/src/cli/commands/shared/companion-selection.ts +3 -1
  69. package/src/cli/commands/studio/access.ts +6 -14
  70. package/src/cli/commands/studio/areas.ts +112 -33
  71. package/src/cli/commands/studio/companion-add.ts +87 -0
  72. package/src/cli/commands/studio/companion-removal.ts +86 -0
  73. package/src/cli/commands/studio/factory-credential.ts +35 -0
  74. package/src/cli/commands/studio/factory-git-tokens.ts +40 -0
  75. package/src/cli/commands/studio/factory-relay.ts +18 -0
  76. package/src/cli/commands/studio/graph-model.ts +61 -0
  77. package/src/cli/commands/studio/graph.ts +336 -0
  78. package/src/cli/commands/studio/index.ts +33 -6
  79. package/src/cli/commands/studio/mate-inventory.ts +1 -1
  80. package/src/cli/commands/studio/openspec-cli.ts +10 -58
  81. package/src/cli/commands/studio/payload.ts +292 -20
  82. package/src/cli/commands/studio/repository-add.ts +116 -0
  83. package/src/cli/commands/studio/routes.ts +47 -6
  84. package/src/cli/commands/studio/selection.ts +170 -17
  85. package/src/cli/commands/studio/server.ts +552 -327
  86. package/src/cli/commands/studio/services.ts +120 -0
  87. package/src/cli/commands/studio/skill-files.ts +133 -0
  88. package/src/cli/commands/studio/studio-app.ts +67 -0
  89. package/src/cli/commands/studio/terminal-assets.ts +21 -33
  90. package/src/cli/commands/studio/terminal.ts +128 -16
  91. package/src/cli/commands/studio/vault.ts +218 -44
  92. package/src/cli/commands/studio/views/model.ts +13 -0
  93. package/src/cli/commands/studio/views/vault/markdown-tree.ts +599 -0
  94. package/src/cli/commands/studio/views/vault/view.ts +185 -0
  95. package/src/cli/commands/studio/workset-session.ts +164 -0
  96. package/src/cli/commands/unwrap.ts +19 -0
  97. package/src/cli/commands/update.ts +55 -9
  98. package/src/cli/commands/vscode/release-vsix.json +4 -0
  99. package/src/cli/commands/vscode/setup.ts +213 -0
  100. package/src/cli/commands/vscode/vsix.ts +114 -0
  101. package/src/cli/commands/working/cleanup.ts +83 -18
  102. package/src/cli/commands/working/link.ts +76 -0
  103. package/src/cli/commands/working/working.ts +10 -0
  104. package/src/cli/commands/working/worktree.ts +547 -0
  105. package/src/cli/commands/wrap.ts +38 -20
  106. package/src/cli/companion-link-wizard.tsx +2 -0
  107. package/src/cli/companion-selector.tsx +2 -0
  108. package/src/cli/confirm.ts +2 -0
  109. package/src/cli/install-plan.tsx +127 -160
  110. package/src/cli/launch-selector.tsx +2 -0
  111. package/src/cli/main.ts +48 -5
  112. package/src/cli/parse-flags.ts +32 -6
  113. package/src/cli/repo-list-table.tsx +2 -0
  114. package/src/cli/setup-selector.tsx +86 -151
  115. package/src/cli/usage.ts +20 -1
  116. package/src/create-mate.ts +5 -4
  117. package/src/hooks/companion-instructions.ts +198 -0
  118. package/src/hooks/hook-io.ts +78 -0
  119. package/src/hooks/rtk-worktree-git.ts +48 -0
  120. package/src/hooks/session-banner.ts +24 -30
  121. package/src/hooks/session-end.ts +10 -0
  122. package/src/hooks/session-guidance.ts +18 -22
  123. package/src/hooks/session-prepare.ts +137 -34
  124. package/src/hooks/session-register.ts +199 -0
  125. package/src/hooks/tokensave-route.ts +30 -0
  126. package/src/hooks/validate-artifact-path.ts +121 -25
  127. package/src/index.ts +4 -0
  128. package/src/lib/apply-context/fingerprint.ts +174 -0
  129. package/src/lib/apply-context/protocol.ts +193 -0
  130. package/src/lib/change-layout.ts +154 -0
  131. package/src/lib/components/confirm-prompt.tsx +21 -9
  132. package/src/lib/components/select-menu.tsx +10 -3
  133. package/src/lib/components/spinner.tsx +4 -2
  134. package/src/lib/components/startup-progress.tsx +227 -41
  135. package/src/lib/components/text-input-display.tsx +2 -0
  136. package/src/lib/components/wizard-footer.tsx +2 -0
  137. package/src/lib/components/wizard-header.tsx +16 -12
  138. package/src/lib/context-mode-package.ts +24 -11
  139. package/src/lib/delivery/archive-change.ts +165 -0
  140. package/src/lib/delivery/branch-template.ts +122 -0
  141. package/src/lib/delivery/branches.ts +152 -0
  142. package/src/lib/delivery/checkout.ts +102 -0
  143. package/src/lib/delivery/environment.ts +37 -0
  144. package/src/lib/delivery/forge.ts +279 -0
  145. package/src/lib/delivery/merge-git.ts +273 -0
  146. package/src/lib/delivery/overlap.ts +209 -0
  147. package/src/lib/delivery/record-delivery.ts +392 -0
  148. package/src/lib/delivery/record.ts +417 -0
  149. package/src/lib/delivery/refresh.ts +288 -0
  150. package/src/lib/delivery/repository-access.ts +141 -0
  151. package/src/lib/delivery/resolve-branch.ts +430 -0
  152. package/src/lib/delivery/stages.ts +111 -0
  153. package/src/lib/delivery/token.ts +24 -0
  154. package/src/lib/factory/attach-client.ts +123 -0
  155. package/src/lib/factory/attach.ts +178 -0
  156. package/src/lib/factory/broker.ts +187 -0
  157. package/src/lib/factory/bun-commands.ts +39 -0
  158. package/src/lib/factory/client.ts +113 -0
  159. package/src/lib/factory/clone-url.ts +39 -0
  160. package/src/lib/factory/command.ts +77 -0
  161. package/src/lib/factory/credential-store.ts +153 -0
  162. package/src/lib/factory/frames.ts +77 -0
  163. package/src/lib/factory/git-auth.ts +61 -0
  164. package/src/lib/factory/git-credential-store.ts +181 -0
  165. package/src/lib/factory/ids.ts +68 -0
  166. package/src/lib/factory/keyed-serial.ts +27 -0
  167. package/src/lib/factory/outcomes/actions.ts +130 -0
  168. package/src/lib/factory/outcomes/index.ts +457 -0
  169. package/src/lib/factory/outcomes/lifecycle.ts +212 -0
  170. package/src/lib/factory/outcomes/runs.ts +81 -0
  171. package/src/lib/factory/outcomes/sessions.ts +60 -0
  172. package/src/lib/factory/prepare.ts +55 -0
  173. package/src/lib/factory/pty.ts +103 -0
  174. package/src/lib/factory/runner/companion-context.ts +178 -0
  175. package/src/lib/factory/runner/control.ts +92 -0
  176. package/src/lib/factory/runner/harness-agent.ts +250 -0
  177. package/src/lib/factory/runner/live.ts +159 -0
  178. package/src/lib/factory/runner/questions.ts +22 -0
  179. package/src/lib/factory/runner/rank.ts +26 -0
  180. package/src/lib/factory/runner/run-policy.ts +12 -0
  181. package/src/lib/factory/runner/run.ts +199 -0
  182. package/src/lib/factory/runner/scheduler.ts +498 -0
  183. package/src/lib/factory/runner/state.ts +233 -0
  184. package/src/lib/factory/runner/workflow.ts +546 -0
  185. package/src/lib/factory/runtime.ts +1081 -0
  186. package/src/lib/factory/sandbox.ts +292 -0
  187. package/src/lib/factory/worktree-branch.ts +17 -0
  188. package/src/lib/frontmatter.ts +18 -0
  189. package/src/lib/install.ts +66 -14
  190. package/src/lib/live-progress.ts +36 -0
  191. package/src/lib/member-choices.ts +67 -0
  192. package/src/lib/opencode-plugin-package.ts +5 -5
  193. package/src/lib/opencode-server.ts +238 -0
  194. package/src/lib/openspec-cli.ts +116 -0
  195. package/src/lib/openspec-scopes.ts +86 -0
  196. package/src/lib/orchestrator/adapters/base.ts +55 -22
  197. package/src/lib/orchestrator/adapters/claude-args.ts +50 -0
  198. package/src/lib/orchestrator/adapters/claude.ts +201 -43
  199. package/src/lib/orchestrator/adapters/opencode.ts +55 -2
  200. package/src/lib/orchestrator/checkout-adoption.ts +125 -0
  201. package/src/lib/orchestrator/companion-hub.ts +6 -1
  202. package/src/lib/orchestrator/companion-registry-store.ts +6 -2
  203. package/src/lib/orchestrator/config-store.ts +3 -2
  204. package/src/lib/orchestrator/editor.ts +32 -26
  205. package/src/lib/orchestrator/engine-floor.ts +48 -0
  206. package/src/lib/orchestrator/framework-context.ts +26 -14
  207. package/src/lib/orchestrator/global-config-store.ts +11 -0
  208. package/src/lib/orchestrator/launcher.ts +49 -3
  209. package/src/lib/orchestrator/openspec-store.ts +14 -54
  210. package/src/lib/orchestrator/projection-claude-commands.ts +36 -0
  211. package/src/lib/orchestrator/projection-claude-entry.ts +42 -21
  212. package/src/lib/orchestrator/projection-claude-links.ts +230 -0
  213. package/src/lib/orchestrator/projection-claude-skills.ts +39 -131
  214. package/src/lib/orchestrator/projection-companion-link.ts +12 -1
  215. package/src/lib/orchestrator/projection-entries.ts +121 -51
  216. package/src/lib/orchestrator/projection-opencode-copies.ts +93 -32
  217. package/src/lib/orchestrator/projection-openspec-store.ts +54 -9
  218. package/src/lib/orchestrator/projection-runtime-documents.ts +81 -49
  219. package/src/lib/orchestrator/projection-types.ts +63 -1
  220. package/src/lib/orchestrator/refresh-working-claude-links.ts +89 -0
  221. package/src/lib/orchestrator/registry-checkouts.ts +177 -0
  222. package/src/lib/orchestrator/repository-link.ts +216 -57
  223. package/src/lib/orchestrator/serving-claude-wrap.ts +43 -0
  224. package/src/lib/orchestrator/session-context-link.ts +73 -0
  225. package/src/lib/orchestrator/session-prepare.ts +87 -12
  226. package/src/lib/orchestrator/setup-compatibilities.ts +56 -70
  227. package/src/lib/orchestrator/types.ts +16 -2
  228. package/src/lib/orchestrator/umbrella-checkouts.ts +102 -0
  229. package/src/lib/orchestrator/working-repo-projection.ts +73 -10
  230. package/src/lib/orchestrator/workspace-document.ts +105 -0
  231. package/src/lib/orchestrator/workspace-inventory.ts +5 -1
  232. package/src/lib/orchestrator/wrap-pass.ts +23 -1
  233. package/src/lib/package-paths.ts +37 -0
  234. package/src/lib/public-npm.ts +105 -43
  235. package/src/lib/runtime-directory-refresh.ts +17 -1
  236. package/src/lib/session-attribution.ts +52 -0
  237. package/src/lib/session-state.ts +355 -0
  238. package/src/lib/session-stop.ts +64 -0
  239. package/src/lib/update-checker.ts +7 -1
  240. package/src/lib/usage/aggregate.ts +202 -0
  241. package/src/lib/usage/cache.ts +87 -0
  242. package/src/lib/usage/claude-pricing.ts +71 -0
  243. package/src/lib/usage/claude.ts +189 -0
  244. package/src/lib/usage/collect.ts +56 -0
  245. package/src/lib/usage/opencode.ts +188 -0
  246. package/src/lib/usage/records.ts +80 -0
  247. package/src/lib/usage/rtk-database.ts +72 -0
  248. package/src/lib/usage/savings.ts +209 -0
  249. package/src/lib/usage/scope.ts +182 -0
  250. package/src/lib/usage/source.ts +102 -0
  251. package/src/lib/usage/types.ts +143 -0
  252. package/src/lib/usage/window.ts +37 -0
  253. package/src/lib/workset/factory-local.ts +157 -0
  254. package/src/lib/workset/record.ts +547 -0
  255. package/src/lib/workset/repositories.ts +148 -0
  256. package/src/lib/workset/stage.ts +148 -0
  257. package/src/lib/workset/stages.ts +113 -0
  258. package/src/lib/workset/worktree-include.ts +161 -0
  259. package/src/lib/workset/worktree-index.ts +120 -0
  260. package/src/lib/workset/worktree.ts +1388 -0
  261. package/src/opencode/background-server.ts +145 -0
  262. package/src/opencode/companion-hooks.ts +151 -9
  263. package/src/opencode/companion-policy.ts +54 -22
  264. package/src/opencode/enter-worktree.ts +320 -0
  265. package/src/opencode/projected-guidance.ts +6 -2
  266. package/src/opencode/session-prepare.ts +2 -1
  267. package/src/opencode/session-register.ts +176 -0
  268. package/src/opencode/tui.tsx +24 -27
  269. package/src/plugins.ts +1 -0
  270. package/src/runtime/artifact-refusal.ts +63 -0
  271. package/src/runtime/claude-bg-isolation.ts +138 -0
  272. package/src/runtime/claude-delivery-plan.ts +121 -11
  273. package/src/runtime/commit-attribution-guard.ts +181 -0
  274. package/src/runtime/companion-git.ts +62 -12
  275. package/src/runtime/companion-guidance.ts +37 -12
  276. package/src/runtime/companion-instructions.ts +340 -0
  277. package/src/runtime/companion-lock.ts +30 -7
  278. package/src/runtime/current-branch.ts +24 -0
  279. package/src/runtime/entered-worktree.ts +24 -0
  280. package/src/runtime/env.ts +59 -8
  281. package/src/runtime/error-message.ts +4 -0
  282. package/src/runtime/git-layout.ts +366 -0
  283. package/src/runtime/git-tracked.ts +60 -0
  284. package/src/runtime/index.ts +29 -0
  285. package/src/runtime/launch-env-guard.ts +65 -0
  286. package/src/runtime/managed-block.ts +117 -0
  287. package/src/runtime/markdown-scan.ts +266 -0
  288. package/src/runtime/opencode-server-record.ts +136 -0
  289. package/src/runtime/physical-path.ts +111 -0
  290. package/src/runtime/policy.ts +50 -2
  291. package/src/runtime/projected-flag.ts +7 -0
  292. package/src/runtime/projected-guidance.ts +1 -0
  293. package/src/runtime/projection.ts +40 -6
  294. package/src/runtime/repo-destination.ts +72 -0
  295. package/src/runtime/repo-local.ts +29 -2
  296. package/src/runtime/rtk-git-guard.ts +66 -0
  297. package/src/runtime/runtime-directory.ts +5 -0
  298. package/src/runtime/runtime-document-manifest.ts +290 -29
  299. package/src/runtime/runtime-document-manifest.typecheck.ts +10 -0
  300. package/src/runtime/secret-guard.ts +169 -0
  301. package/src/runtime/secret-patterns.ts +397 -0
  302. package/src/runtime/secret-policy-weakening.ts +122 -0
  303. package/src/runtime/secret-scan.ts +90 -0
  304. package/src/runtime/serving-claude-wrap.ts +41 -0
  305. package/src/runtime/session-context.ts +99 -0
  306. package/src/runtime/session-kind.ts +13 -0
  307. package/src/runtime/session-registry.ts +434 -0
  308. package/src/runtime/shell-heredoc.ts +81 -0
  309. package/src/runtime/tokensave-route.ts +157 -0
  310. package/src/runtime/umbrella-folder.ts +56 -0
  311. package/src/runtime/wrap-state.ts +80 -15
  312. package/src/runtime/write-atomic.ts +64 -0
  313. package/src/studio.ts +163 -0
  314. package/src/templates/capabilities/openspec-cap/mate-minimal/schema.yaml +14 -10
  315. package/src/templates/capabilities/openspec-cap/mate-minimal/templates/spec.md +3 -5
  316. package/src/templates/capabilities/openspec-cap/mate-v1/schema.yaml +18 -102
  317. package/src/templates/capabilities/openspec-cap/mate-v1/templates/spec.md +3 -5
  318. package/src/templates/capabilities/openspec-cap/openspec-conventions.yaml +20 -14
  319. package/src/templates/mate-skills/THIRD-PARTY-NOTICES.md +40 -0
  320. package/src/templates/mate-skills/agents/mate-apply-change/SKILL.md +217 -0
  321. package/src/templates/mate-skills/agents/mate-apply-change/references/mate-compact-apply.md +47 -0
  322. package/src/templates/mate-skills/agents/mate-apply-change/references/openspec-apply-change.md +200 -0
  323. package/src/templates/mate-skills/agents/mate-archive-change/SKILL.md +81 -0
  324. package/src/templates/mate-skills/agents/{mate-openspec-backfill → mate-backfill-spec}/SKILL.md +11 -4
  325. package/src/templates/mate-skills/agents/mate-clarify-intent/SKILL.md +110 -0
  326. package/src/templates/mate-skills/agents/mate-explore-change/SKILL.md +70 -0
  327. package/src/templates/mate-skills/agents/mate-explore-change/references/openspec-explore.md +350 -0
  328. package/src/templates/mate-skills/agents/mate-grill-me/SKILL.md +11 -4
  329. package/src/templates/mate-skills/agents/mate-grill-with-docs/SKILL.md +2 -2
  330. package/src/templates/mate-skills/agents/mate-interview-me/SKILL.md +12 -5
  331. package/src/templates/mate-skills/agents/mate-propose-change/SKILL.md +106 -0
  332. package/src/templates/mate-skills/agents/mate-propose-change/references/mate-revise.md +45 -0
  333. package/src/templates/mate-skills/agents/mate-propose-change/references/openspec-propose.md +169 -0
  334. package/src/templates/mate-skills/agents/mate-propose-change/references/openspec-update-change.md +103 -0
  335. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +271 -0
  336. package/src/templates/mate-skills/{claude/mate-artifact-publish → agents/mate-publish-artifact}/references/openspec.md +8 -5
  337. package/src/templates/mate-skills/agents/mate-show-me/SKILL.md +105 -20
  338. package/src/templates/mate-skills/agents/mate-simplify-code/SKILL.md +91 -68
  339. package/src/templates/mate-skills/claude/mate-apply-change/SKILL.md +217 -0
  340. package/src/templates/mate-skills/claude/mate-apply-change/references/mate-compact-apply.md +47 -0
  341. package/src/templates/mate-skills/claude/mate-apply-change/references/openspec-apply-change.md +200 -0
  342. package/src/templates/mate-skills/claude/mate-archive-change/SKILL.md +81 -0
  343. package/src/templates/mate-skills/claude/{mate-openspec-backfill → mate-backfill-spec}/SKILL.md +11 -4
  344. package/src/templates/mate-skills/claude/mate-clarify-intent/SKILL.md +110 -0
  345. package/src/templates/mate-skills/claude/mate-explore-change/SKILL.md +70 -0
  346. package/src/templates/mate-skills/claude/mate-explore-change/references/openspec-explore.md +350 -0
  347. package/src/templates/mate-skills/claude/mate-grill-me/SKILL.md +11 -4
  348. package/src/templates/mate-skills/claude/mate-grill-with-docs/SKILL.md +2 -2
  349. package/src/templates/mate-skills/claude/mate-interview-me/SKILL.md +12 -5
  350. package/src/templates/mate-skills/claude/mate-propose-change/SKILL.md +106 -0
  351. package/src/templates/mate-skills/claude/mate-propose-change/references/mate-revise.md +45 -0
  352. package/src/templates/mate-skills/claude/mate-propose-change/references/openspec-propose.md +169 -0
  353. package/src/templates/mate-skills/claude/mate-propose-change/references/openspec-update-change.md +103 -0
  354. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +271 -0
  355. package/src/templates/mate-skills/{agents/mate-artifact-publish → claude/mate-publish-artifact}/references/openspec.md +8 -5
  356. package/src/templates/mate-skills/claude/mate-show-me/SKILL.md +105 -20
  357. package/src/templates/mate-skills/claude/mate-simplify-code/SKILL.md +91 -68
  358. package/src/templates/mate-skills/openspec-references.ts +142 -0
  359. package/src/templates/root/TEMPLATE_AGENTS.md +2 -2
  360. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +4581 -397
  361. package/src/tools/setup/capabilities/companion-mentions.ts +27 -0
  362. package/src/tools/setup/capabilities/context-mode.ts +56 -7
  363. package/src/tools/setup/capabilities/graphify-gate.ts +31 -0
  364. package/src/tools/setup/capabilities/graphify-secrets.ts +243 -0
  365. package/src/tools/setup/capabilities/graphify.ts +46 -7
  366. package/src/tools/setup/capabilities/openspec.ts +163 -272
  367. package/src/tools/setup/capabilities/react-doctor.ts +8 -1
  368. package/src/tools/setup/capabilities/rtk.ts +97 -1
  369. package/src/tools/setup/capabilities/tokensave.ts +113 -71
  370. package/src/tools/setup/context-services.ts +9 -17
  371. package/src/tools/setup/dynamic-plugins/audiences.ts +65 -21
  372. package/src/tools/setup/dynamic-plugins/frozen.ts +32 -13
  373. package/src/tools/setup/dynamic-plugins/hydrate.ts +8 -7
  374. package/src/tools/setup/dynamic-plugins/install.ts +46 -48
  375. package/src/tools/setup/dynamic-plugins/loader.ts +11 -7
  376. package/src/tools/setup/dynamic-plugins/paths.ts +30 -10
  377. package/src/tools/setup/dynamic-plugins/verify.ts +10 -7
  378. package/src/tools/setup/dynamic-plugins/workspaces.ts +153 -0
  379. package/src/tools/setup/engine.ts +100 -23
  380. package/src/tools/setup/install-contract.ts +8 -0
  381. package/src/tools/setup/managed-output.ts +51 -0
  382. package/src/tools/setup/mate-skill-copies.ts +51 -0
  383. package/src/tools/setup/mate.ts +88 -13
  384. package/src/tools/setup/package-managers/uv.ts +73 -11
  385. package/src/tools/setup/plugin.ts +40 -0
  386. package/src/tools/setup/plugins/gitignore.ts +15 -9
  387. package/src/tools/setup/plugins/guidance.ts +7 -4
  388. package/src/tools/setup/providers/agent-file-sections.ts +4 -2
  389. package/src/tools/setup/providers/claude-attribution.ts +65 -0
  390. package/src/tools/setup/providers/claude-plugin-folders.ts +625 -0
  391. package/src/tools/setup/providers/claude-plugin-hooks.ts +89 -19
  392. package/src/tools/setup/providers/claude-worktree-plugins.ts +122 -0
  393. package/src/tools/setup/providers/claude.ts +332 -8
  394. package/src/tools/setup/providers/opencode.ts +180 -1
  395. package/src/tools/setup/utils.ts +22 -6
  396. package/src/tools/setup/working-repo-cleanup.ts +30 -2
  397. package/src/tools/setup/working-repo-local-state.ts +252 -75
  398. package/src/tools/setup.ts +196 -28
  399. package/studio-dist/client/assets/app-D9cw6szy.css +2 -0
  400. package/studio-dist/client/assets/artifacts-WD2ZXYrx.js +1 -0
  401. package/studio-dist/client/assets/button-Br0O1sXw.js +1 -0
  402. package/studio-dist/client/assets/combobox-DA7RAUUZ.js +1 -0
  403. package/studio-dist/client/assets/companion-view-CrabvxS8.js +1 -0
  404. package/studio-dist/client/assets/dist-Dm7MtyHc.js +5 -0
  405. package/studio-dist/client/assets/factory-DGS0E16C.js +6 -0
  406. package/studio-dist/client/assets/fields-6aXBpFhJ.js +1 -0
  407. package/studio-dist/client/assets/getting-started-Clde4w6P.js +1 -0
  408. package/studio-dist/client/assets/getting-started-D6kgWwWZ.js +1 -0
  409. package/studio-dist/client/assets/getting-started._topic-BiunccbT.js +1 -0
  410. package/studio-dist/client/assets/getting-started.index-DpiNoGw8.js +1 -0
  411. package/studio-dist/client/assets/graph-B_TCBVbu.js +2 -0
  412. package/studio-dist/client/assets/graph-canvas-Ba37Y5AE.js +3242 -0
  413. package/studio-dist/client/assets/guides-Du_RtJxP.js +1 -0
  414. package/studio-dist/client/assets/index-Df8L1LQa.js +40 -0
  415. package/studio-dist/client/assets/jsx-runtime-MZURdZre.js +1 -0
  416. package/studio-dist/client/assets/markdown-view-BOX6x0rL.js +1 -0
  417. package/studio-dist/client/assets/panel-dbmCx7Mx.js +1 -0
  418. package/studio-dist/client/assets/preload-helper-BLdHbfdN.js +1 -0
  419. package/studio-dist/client/assets/queries-RvHeXY12.js +1 -0
  420. package/studio-dist/client/assets/react-3QStrcDO.js +27 -0
  421. package/studio-dist/client/assets/report-url-XRL0x1SY.js +1 -0
  422. package/studio-dist/client/assets/reports-r3IK7Doz.js +1 -0
  423. package/studio-dist/client/assets/routes-C0A5LTFc.js +1 -0
  424. package/studio-dist/client/assets/select-CnaMd617.js +1 -0
  425. package/studio-dist/client/assets/skills-CzjzHpBT.js +1 -0
  426. package/studio-dist/client/assets/specs-B0ldF_6J.js +1 -0
  427. package/studio-dist/client/assets/specs-view-BnCLA0gW.js +1 -0
  428. package/studio-dist/client/assets/spinner-Dcm3fqK1.js +1 -0
  429. package/studio-dist/client/assets/steps-C0p2N1Pb.js +1 -0
  430. package/studio-dist/client/assets/store-Dw34catY.js +1 -0
  431. package/studio-dist/client/assets/studio-Cpz_HRHp.js +100 -0
  432. package/studio-dist/client/assets/studio-queries-ibmpFo6R.js +2 -0
  433. package/studio-dist/client/assets/terminal-eU5fzQzv.css +1 -0
  434. package/studio-dist/client/assets/usage-C2QJ_0IZ.js +55 -0
  435. package/studio-dist/client/assets/useAnchoredPopupScrollLock-Bj-FWb8z.js +1 -0
  436. package/studio-dist/client/assets/useMutation-aAr2uiay.js +1 -0
  437. package/studio-dist/client/assets/useSelector-AYcH7lB0.js +2 -0
  438. package/studio-dist/client/assets/vault-BGcxkSIY.js +1 -0
  439. package/studio-dist/client/assets/warnings-R1cE1rLf.js +1 -0
  440. package/studio-dist/client/assets/wasm-inline-C2en61B5.js +1 -0
  441. package/studio-dist/client/assets/workflow-C2qTrMDH.js +1 -0
  442. package/studio-dist/server/assets/__23tanstack-start-server-fn-resolver-Bn896ZYj.js +122 -0
  443. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +162 -0
  444. package/studio-dist/server/assets/actions-D8erOphH.js +44 -0
  445. package/studio-dist/server/assets/actions-DYSv-9VV.js +60 -0
  446. package/studio-dist/server/assets/artifacts-DnF9L3dZ.js +216 -0
  447. package/studio-dist/server/assets/button-CgOIVdmD.js +10240 -0
  448. package/studio-dist/server/assets/combobox-DV_s9W0s.js +483 -0
  449. package/studio-dist/server/assets/companion-view-BKVXD3TO.js +39 -0
  450. package/studio-dist/server/assets/companions-C7fctnU9.js +31 -0
  451. package/studio-dist/server/assets/createServerRpc-bFKFpGFG.js +11 -0
  452. package/studio-dist/server/assets/dist-DpJWKyCm.js +5582 -0
  453. package/studio-dist/server/assets/empty-plugin-adapters-Cipd4ZH4.js +4 -0
  454. package/studio-dist/server/assets/factory-C7Ybg0xG.js +3075 -0
  455. package/studio-dist/server/assets/factory-Df5uAHjb.js +116 -0
  456. package/studio-dist/server/assets/fields-BbieQTD0.js +1190 -0
  457. package/studio-dist/server/assets/getting-started-B136TP57.js +4 -0
  458. package/studio-dist/server/assets/getting-started-CRxMWorQ.js +67 -0
  459. package/studio-dist/server/assets/getting-started._topic-DJKQAzYl.js +13 -0
  460. package/studio-dist/server/assets/getting-started.index-D84gec1t.js +13 -0
  461. package/studio-dist/server/assets/graph-CSje3029.js +801 -0
  462. package/studio-dist/server/assets/graph-DDZzXM1L.js +16 -0
  463. package/studio-dist/server/assets/graph-canvas-22bWB5-2.js +21066 -0
  464. package/studio-dist/server/assets/graph-wire-BdSUx0G5.js +58 -0
  465. package/studio-dist/server/assets/guides-D9dk1Frq.js +13 -0
  466. package/studio-dist/server/assets/guides-IE-19POz.js +5 -0
  467. package/studio-dist/server/assets/guides.server-vcYRY5wx.js +66 -0
  468. package/studio-dist/server/assets/jsx-runtime-Bt0s0YKS.js +451 -0
  469. package/studio-dist/server/assets/markdown-view-BR8dJ7aR.js +105 -0
  470. package/studio-dist/server/assets/model-PyPALjii.js +18 -0
  471. package/studio-dist/server/assets/panel-BR_t9iMM.js +169 -0
  472. package/studio-dist/server/assets/queries-DWoTin-q.js +32 -0
  473. package/studio-dist/server/assets/react-CdqSUhaL.js +89 -0
  474. package/studio-dist/server/assets/redirect-BaZ_QyqF.js +39 -0
  475. package/studio-dist/server/assets/report-url-BUXPcE_8.js +9 -0
  476. package/studio-dist/server/assets/reports-CQ9qQ1-n.js +141 -0
  477. package/studio-dist/server/assets/reports-dYDEoBeq.js +18 -0
  478. package/studio-dist/server/assets/router-DkRHNTpE.js +11638 -0
  479. package/studio-dist/server/assets/routes-B6GfOew4.js +473 -0
  480. package/studio-dist/server/assets/search-BJnWLfkG.js +55 -0
  481. package/studio-dist/server/assets/select-Af7Wibii.js +1609 -0
  482. package/studio-dist/server/assets/shell-Hq-hXgnT.js +53 -0
  483. package/studio-dist/server/assets/skills-B7nEuVbx.js +267 -0
  484. package/studio-dist/server/assets/skills-B_YYL7q8.js +28 -0
  485. package/studio-dist/server/assets/specs-BpLUFntA.js +51 -0
  486. package/studio-dist/server/assets/specs-view-0peMVd22.js +426 -0
  487. package/studio-dist/server/assets/spinner-CdwJW4VB.js +20 -0
  488. package/studio-dist/server/assets/start-h3ICWwd2.js +36 -0
  489. package/studio-dist/server/assets/steps-D56DApvK.js +181 -0
  490. package/studio-dist/server/assets/store-Cs17okNG.js +280 -0
  491. package/studio-dist/server/assets/studio-CAcKp3bM.js +10340 -0
  492. package/studio-dist/server/assets/studio-queries-BtRGzDdh.js +1451 -0
  493. package/studio-dist/server/assets/usage-COdjd1gD.js +25570 -0
  494. package/studio-dist/server/assets/usage-f6pqE1tm.js +24 -0
  495. package/studio-dist/server/assets/useAnchoredPopupScrollLock-DlBKHRw7.js +756 -0
  496. package/studio-dist/server/assets/useMutation-DzTZGenE.js +690 -0
  497. package/studio-dist/server/assets/useSelector-DUmCUXAs.js +3387 -0
  498. package/studio-dist/server/assets/utils-C9CX1kcy.js +221 -0
  499. package/studio-dist/server/assets/vault-BDuIUq0F.js +1035 -0
  500. package/studio-dist/server/assets/vault-BVLp6zu3.js +85 -0
  501. package/studio-dist/server/assets/views-flRUr21z.js +80 -0
  502. package/studio-dist/server/assets/warnings-CDy9pdgL.js +24 -0
  503. package/studio-dist/server/assets/wasm-inline-CNeBKGwC.js +3 -0
  504. package/studio-dist/server/assets/workflow-D9GKI2EV.js +680 -0
  505. package/studio-dist/server/server.js +16640 -0
  506. package/wrappers/bin/graphify +52 -4
  507. package/wrappers/bin/openspec +33 -9
  508. package/wrappers/lib/graphify-gate.mjs +8 -0
  509. package/src/cli/commands/report/collector.ts +0 -288
  510. package/src/cli/commands/studio/views/client.ts +0 -654
  511. package/src/cli/commands/studio/views/companion-picker.tsx +0 -95
  512. package/src/cli/commands/studio/views/companion-selector.tsx +0 -94
  513. package/src/cli/commands/studio/views/dashboard/changes.tsx +0 -107
  514. package/src/cli/commands/studio/views/dashboard/index.tsx +0 -19
  515. package/src/cli/commands/studio/views/document.tsx +0 -842
  516. package/src/cli/commands/studio/views/error.tsx +0 -20
  517. package/src/cli/commands/studio/views/reports/index.tsx +0 -49
  518. package/src/cli/commands/studio/views/selection-fields.tsx +0 -14
  519. package/src/cli/commands/studio/views/skills/index.tsx +0 -87
  520. package/src/cli/commands/studio/views/specs/index.tsx +0 -157
  521. package/src/cli/commands/studio/views/styles.ts +0 -519
  522. package/src/cli/commands/studio/views/terminal.tsx +0 -484
  523. package/src/cli/commands/studio/views/vault/state.ts +0 -43
  524. package/src/cli/commands/studio/views/warnings.tsx +0 -21
  525. package/src/cli/commands/studio/views/workflow/index.tsx +0 -21
  526. package/src/cli/commands/studio/views/workflow/steps.ts +0 -337
  527. package/src/cli/commands/studio/views/workflow/transcript.tsx +0 -190
  528. package/src/lib/components/theme.ts +0 -2
  529. package/src/templates/mate-skills/agents/mate-artifact-publish/SKILL.md +0 -185
  530. package/src/templates/mate-skills/claude/mate-artifact-publish/SKILL.md +0 -185
  531. package/src/tools/setup/git-utils.ts +0 -30
  532. package/src/tools/setup/runtime-documents.ts +0 -291
@@ -7,29 +7,69 @@ import {
7
7
  type StudioAccess,
8
8
  type StudioInvocation,
9
9
  } from "./access";
10
+ import { realpath } from "node:fs/promises";
11
+ import path from "node:path";
12
+
10
13
  import { MERMAID_RUNTIME_URL } from "../report/renderer";
14
+ import {
15
+ CompanionRemovalError,
16
+ deletableWithin,
17
+ deleteRegisteredCompanion,
18
+ } from "./companion-removal";
11
19
  import { collectStudioInventory, type StudioInventory } from "./inventory";
12
- import { assembleCompanionPayload, type StudioCompanionResponse } from "./payload";
20
+ import {
21
+ assembleCompanionPayload,
22
+ readCompanionWorksetStages,
23
+ type StudioCompanionResponse,
24
+ } from "./payload";
13
25
  import { createReportStore, isReportId, REPORT_LIMITS, type ReportStore } from "./reports";
26
+ import { isWorksetId, WorksetError } from "../../../lib/workset/record";
27
+ import type { WorksetWithStage } from "../../../lib/workset/stages";
28
+ import type { LiveViewer } from "../../../lib/factory/runner/live";
29
+ import {
30
+ createFactoryOutcomes,
31
+ type FactoryOutcomes,
32
+ type Outcomes,
33
+ type OutcomesPorts,
34
+ recordOutcomes,
35
+ } from "../../../lib/factory/outcomes";
36
+ import { LiveSessions } from "../../../lib/factory/outcomes/sessions";
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";
40
+ import { factoryCredentialResponse } from "./factory-credential";
41
+ import { factoryGitTokensResponse } from "./factory-git-tokens";
42
+ import { createWorksetResolver } from "./workset-session";
14
43
  import {
44
+ FACTORY_CREDENTIAL_ROUTE,
45
+ FACTORY_GIT_TOKENS_ROUTE,
46
+ FACTORY_WORKSETS_ROUTE,
15
47
  REPORTS_ROUTE,
16
48
  REPORT_VIEW_PREFIX,
49
+ STUDIO_EVENTS_ROUTE,
17
50
  STUDIO_HOSTNAME,
18
- VAULT_CHANGES_ROUTE,
19
- VAULT_DIR_ROUTE,
20
- VAULT_FILTER_ROUTE,
51
+ type StudioEvent,
52
+ TERMINAL_ASSET_PREFIX,
53
+ TERMINAL_SESSIONS_END_ROUTE,
54
+ TERMINAL_SESSIONS_ROUTE,
55
+ TERMINAL_SOCKET_ROUTE,
56
+ VAULT_EVENTS_ROUTE,
21
57
  } from "./routes";
22
58
  import {
23
59
  COMPANION_DIGEST_PATTERN,
24
60
  COMPANION_PARAM,
25
61
  companionDigest,
62
+ modePolicy,
26
63
  parse,
27
64
  parseVaultSelection,
28
65
  resolveCompanion,
29
- type StudioVaultSelection,
66
+ type StudioModePolicy,
67
+ type StudioProfile,
30
68
  } from "./selection";
69
+ import { errorMessage } from "../../../runtime/error-message";
70
+ import type { SpecGraphCache } from "./graph";
31
71
  import { createStudioSnapshotCache, type StudioSnapshotCache } from "./snapshot";
32
- import type { StudioPage, StudioVaultPage } from "./views/model";
72
+ import type { StudioPage } from "./views/model";
33
73
  import { createVaultManager, resolveVaultPath, VaultPathError, type VaultManager } from "./vault";
34
74
  import {
35
75
  DEFAULT_DETACH_MINUTES,
@@ -37,6 +77,9 @@ import {
37
77
  type TerminalConnection,
38
78
  type TerminalRegistryOptions,
39
79
  } from "./terminal";
80
+ import type { StudioFormField, StudioServices } from "./services";
81
+ import type { UsageCache } from "../../../lib/usage/cache";
82
+ import { studioAppAsset, type StudioApp } from "./studio-app";
40
83
  import { terminalAsset } from "./terminal-assets";
41
84
  import {
42
85
  createLaunchResolver,
@@ -46,8 +89,8 @@ import {
46
89
 
47
90
  export { STUDIO_HOSTNAME } from "./routes";
48
91
 
49
- /** Read methods; every other method is refused before any collection runs. */
50
- const READ_METHODS = new Set(["GET", "HEAD"]);
92
+ /** Where Start's server functions are called; the only POSTs the application makes. */
93
+ const STUDIO_APP_CALL_PREFIX = "/_serverFn/";
51
94
 
52
95
  /** The socket Bun hands a WebSocket handler; `data` is what the upgrade attached. */
53
96
  export interface StudioSocket {
@@ -101,13 +144,22 @@ export interface StudioServerHandle {
101
144
  export interface StudioServerDeps {
102
145
  collectStudioInventory?: () => Promise<StudioInventory>;
103
146
  assembleCompanionPayload?: (companionPath: string) => Promise<StudioCompanionResponse>;
104
- renderDocument?: (page: StudioPage) => string | Promise<string>;
105
147
  serve?: (options: StudioServeOptions) => StudioBoundServer;
106
148
  snapshots?: StudioSnapshotCache;
107
149
  vault?: VaultManager;
108
150
  reports?: ReportStore;
151
+ usage?: UsageCache;
109
152
  terminal?: Partial<TerminalRegistryOptions>;
110
153
  launchableAgents?: typeof launchableAgents;
154
+ /**
155
+ * The factory's Outcomes, built from the ports Studio creates first for the companion it
156
+ * serves; from the environment in factory mode when absent.
157
+ */
158
+ factoryOutcomes?: (portsFor: (companionPath: string) => OutcomesPorts) => FactoryOutcomes | null;
159
+ /** A companion's Workset stages; read from OpenSpec when absent. */
160
+ worksetStages?: (companionPath: string) => Promise<{ worksets: WorksetWithStage[] }>;
161
+ /** The factory broker's client; from the environment when absent, null outside factory mode. */
162
+ factoryClient?: FactoryClient | null;
111
163
  }
112
164
 
113
165
  export interface StudioServerOptions {
@@ -118,7 +170,7 @@ export interface StudioServerOptions {
118
170
  terminal?: boolean;
119
171
  allowedHosts?: string[];
120
172
  publicOrigin?: string | null;
121
- /** Operator-pinned token; generated per start when absent and Studio is guarded. */
173
+ /** Operator-pinned token; generated per start when absent. */
122
174
  token?: string | null;
123
175
  detachMinutes?: number;
124
176
  /** Pins every terminal launch to this registered companion. */
@@ -127,45 +179,23 @@ export interface StudioServerOptions {
127
179
  idleTimeout?: number;
128
180
  /** Terminal launches skip companion Git synchronization. */
129
181
  noGit?: boolean;
182
+ /** Which Studio modes are enabled; `standard` when absent. Never read from a request. */
183
+ profile?: StudioProfile;
184
+ /** Studio's built application, loaded by the studio command. */
185
+ app?: StudioApp | null;
130
186
  }
131
187
 
132
- /**
133
- * Loaded at the point of use so no other command pays for the renderer: `hono/jsx`
134
- * is reachable from the studio path alone.
135
- */
136
- async function renderStudioDocument(page: StudioPage): Promise<string> {
137
- const views = await import("./views/document");
138
- return views.renderStudioDocument(page);
139
- }
188
+ /** Answered to a document request when no Studio build is installed; carries no companion data. */
189
+ const MISSING_BUILD_PAGE = `<!doctype html>
190
+ <html lang="en">
191
+ <head><meta charset="utf-8"><title>Mate Studio</title></head>
192
+ <body><p>Studio's application build is missing. Run <code>bun run build</code> in <code>packages/mate-studio</code>, then reload.</p></body>
193
+ </html>
194
+ `;
140
195
 
141
- async function renderVaultView(page: StudioPage): Promise<string> {
142
- const views = await import("./views/document");
143
- return views.renderVaultView(page);
144
- }
145
-
146
- async function renderVaultChildren(page: StudioPage): Promise<string | null> {
147
- const views = await import("./views/document");
148
- return views.renderVaultChildren(page);
149
- }
150
-
151
- async function renderVaultMatches(page: StudioPage, query: string): Promise<string> {
152
- const views = await import("./views/document");
153
- return views.renderVaultMatches(page, query);
154
- }
155
-
156
- /** Keep the CLI entry free of eager Studio view imports. */
157
- async function collectVaultState(
158
- vault: VaultManager,
159
- companionPath: string,
160
- selection: StudioVaultSelection,
161
- options: { tree: "prefetch" | "await" },
162
- ): Promise<StudioVaultPage> {
163
- const { vaultState } = await import("./views/vault/state");
164
- return vaultState(vault, companionPath, selection, options);
165
- }
166
-
167
- function html(body: string): Response {
196
+ function html(body: string, status = 200): Response {
168
197
  return new Response(body, {
198
+ status,
169
199
  headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" },
170
200
  });
171
201
  }
@@ -179,6 +209,68 @@ const TOKEN_REQUIRED_PAGE = `<!doctype html>
179
209
  If the token was pinned with <code>--token</code> or <code>MATE_STUDIO_TOKEN</code>,
180
210
  open this address with <code>?token=</code> followed by that value.</p></main></body></html>`;
181
211
 
212
+ /** A Workset's run log, or its live stream when the second group matched. */
213
+ const FACTORY_LOG = new RegExp(`^${FACTORY_WORKSETS_ROUTE}/([^/]+)/log(/stream)?$`);
214
+
215
+ /**
216
+ * What a route is, for its guard. A read needs the token where the invocation requires it
217
+ * for reading; a write also needs the same origin, the token for saving and, when it names
218
+ * a reason, the write path; a terminal call needs the token for the terminal and, when
219
+ * privileged, the same origin; a session call is checked by its own bearer credential only.
220
+ */
221
+ type RouteKind =
222
+ | { kind: "read"; methods: readonly string[] }
223
+ | { kind: "write"; methods: readonly string[]; writable?: string }
224
+ | { kind: "terminal"; methods: readonly string[]; privileged: boolean }
225
+ | { kind: "session"; methods: readonly string[] };
226
+
227
+ const ORIGIN_REASON = {
228
+ write: "a change must come from Studio's own page",
229
+ terminal: "the terminal is reachable only from Studio's own page",
230
+ } as const;
231
+
232
+ const READS = ["GET", "HEAD"] as const;
233
+
234
+ /** Every route core answers, by kind; the rest are reads the application answers. */
235
+ function routeOf(url: URL, method: string, hasApp: boolean): RouteKind {
236
+ const { pathname } = url;
237
+ if (pathname === REPORTS_ROUTE && method === "POST")
238
+ return { kind: "session", methods: ["POST"] };
239
+ if (pathname === FACTORY_CREDENTIAL_ROUTE) {
240
+ return method === "GET" || method === "HEAD"
241
+ ? { kind: "read", methods: [method] }
242
+ : {
243
+ kind: "write",
244
+ methods: [method],
245
+ writable: "start Studio with --writable to set the agent credential",
246
+ };
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
+ }
257
+ if (pathname === TERMINAL_SOCKET_ROUTE) {
258
+ return { kind: "terminal", methods: READS, privileged: true };
259
+ }
260
+ if (pathname === TERMINAL_SESSIONS_END_ROUTE) {
261
+ return { kind: "terminal", methods: ["POST"], privileged: true };
262
+ }
263
+ if (pathname.startsWith(`${TERMINAL_SOCKET_ROUTE}/`)) {
264
+ return { kind: "terminal", methods: READS, privileged: false };
265
+ }
266
+ // A server function is a read when called with GET and a write when called with POST; the
267
+ // write path for its changes is checked by the services it calls.
268
+ if (hasApp && pathname.startsWith(STUDIO_APP_CALL_PREFIX) && method === "POST") {
269
+ return { kind: "write", methods: ["POST"] };
270
+ }
271
+ return { kind: "read", methods: READS };
272
+ }
273
+
182
274
  function refused(reason: string, status: number): Response {
183
275
  return new Response(JSON.stringify({ reason }), {
184
276
  status,
@@ -204,14 +296,10 @@ const REPORT_CSP = [
204
296
  "connect-src 'none'",
205
297
  ].join("; ");
206
298
 
207
- /** Page-facing report announcement; carries no path and no content. */
208
- interface ReportPublishedEvent {
209
- type: "report-published";
210
- /** Digest of the companion the report belongs to. */
211
- companion: string;
299
+ /** A published report as open pages are told of it; carries no path and no content. */
300
+ interface PublishedReport {
212
301
  id: string;
213
302
  title: string;
214
- createdAt: number;
215
303
  }
216
304
 
217
305
  /**
@@ -244,9 +332,17 @@ async function readCapped(request: Request, limit: number): Promise<string | nul
244
332
  return over ? null : Buffer.concat(chunks).toString("utf8");
245
333
  }
246
334
 
335
+ const NOT_WRITABLE = "start Studio with --writable to create or start Worksets";
336
+
247
337
  const TOKEN_REASON =
248
338
  "Studio's access token is required; open the address Studio printed when it started";
249
339
 
340
+ const NO_COMPANION = "no registered companion was selected";
341
+
342
+ function notFound(): Response {
343
+ return new Response("not found", { status: 404 });
344
+ }
345
+
250
346
  function json(value: unknown, status = 200): Response {
251
347
  return new Response(JSON.stringify(value), {
252
348
  status,
@@ -257,12 +353,13 @@ function json(value: unknown, status = 200): Response {
257
353
  interface StudioFetch {
258
354
  (request: Request, server?: StudioUpgrader): Promise<Response | undefined>;
259
355
  terminal: TerminalRegistry | null;
356
+ services: StudioServices;
260
357
  close(): Promise<void>;
261
358
  }
262
359
 
263
360
  export interface StudioFetchOptions extends Pick<
264
361
  StudioServerOptions,
265
- "writable" | "launchCompanion" | "noGit" | "detachMinutes"
362
+ "writable" | "launchCompanion" | "noGit" | "detachMinutes" | "profile"
266
363
  > {
267
364
  access?: StudioAccess;
268
365
  /** Loopback origin the terminal's processes publish to; read at spawn. */
@@ -271,6 +368,8 @@ export interface StudioFetchOptions extends Pick<
271
368
  publicOrigin?: string | null;
272
369
  /** Enables the terminal; the invocation sets its default detach window. */
273
370
  terminal?: boolean;
371
+ /** Studio's built application; paths the handler does not serve itself go to it. */
372
+ app?: StudioApp | null;
274
373
  }
275
374
 
276
375
  /**
@@ -288,11 +387,46 @@ export function createStudioFetch(
288
387
  ): StudioFetch {
289
388
  const inventory = deps.collectStudioInventory ?? collectStudioInventory;
290
389
  const companion = deps.assembleCompanionPayload ?? assembleCompanionPayload;
291
- const render = deps.renderDocument ?? renderStudioDocument;
292
390
  const snapshots =
293
391
  deps.snapshots ?? createStudioSnapshotCache({ assembleCompanionPayload: companion });
294
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;
295
395
  const writable = options.writable === true;
396
+ const policy = modePolicy(options.profile ?? "standard");
397
+ const broker = deps.factoryClient !== undefined ? deps.factoryClient : factoryClient();
398
+ const reports = deps.reports ?? createReportStore();
399
+ const stagesOf = deps.worksetStages ?? ((path: string) => readCompanionWorksetStages(path));
400
+ // Created before the terminal and the Outcomes, so neither needs the other.
401
+ const sessions = new LiveSessions();
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";
405
+ const outcomesPorts = (companionPath: string): OutcomesPorts => ({
406
+ stages: () => stagesOf(companionPath),
407
+ reports: {
408
+ publish: (report) => reports.publish(companionDigest(companionPath), report),
409
+ ids: async () =>
410
+ (await reports.list(companionDigest(companionPath))).map((report) => report.id),
411
+ },
412
+ sessions,
413
+ });
414
+ const outcomes = (() => {
415
+ try {
416
+ if (deps.factoryOutcomes) return deps.factoryOutcomes(outcomesPorts);
417
+ return createFactoryOutcomes(launchCompanion, outcomesPorts(launchCompanion ?? ""));
418
+ } catch (error) {
419
+ process.stderr.write(
420
+ `mate studio: the factory runner did not start: ${(error as Error).message}\n`,
421
+ );
422
+ return null;
423
+ }
424
+ })();
425
+ /** A companion's Outcomes: the factory's for the companion it runs, record-only otherwise. */
426
+ const outcomesFor = (companionPath: string): Outcomes =>
427
+ outcomes?.companionPath === companionPath
428
+ ? outcomes
429
+ : recordOutcomes(companionPath, () => stagesOf(companionPath));
296
430
  const access =
297
431
  options.access ??
298
432
  createStudioAccess({
@@ -301,11 +435,9 @@ export function createStudioFetch(
301
435
  hostname: STUDIO_HOSTNAME,
302
436
  port: () => 80,
303
437
  });
304
- const reports = deps.reports ?? createReportStore();
305
438
  void reports.cleanup().catch(() => {});
306
439
  const publicOrigin = options.publicOrigin ? normalizeOrigin(options.publicOrigin) : null;
307
- const reportListeners = new Map<string, Set<(event: ReportPublishedEvent) => void>>();
308
- const launchCompanion = options.launchCompanion ?? null;
440
+ const reportListeners = new Map<string, Set<(event: PublishedReport) => void>>();
309
441
  const agentsFor = deps.launchableAgents ?? launchableAgents;
310
442
  const terminal = options.terminal
311
443
  ? new TerminalRegistry({
@@ -316,12 +448,38 @@ export function createStudioFetch(
316
448
  launchableAgents: (companionPath) => agentsFor(companionPath),
317
449
  }),
318
450
  mateCommand: process.argv.slice(0, 2),
451
+ sessions,
452
+ ...(process.env[FACTORY_BROKER_ENV]
453
+ ? {
454
+ resolveWorkset: createWorksetResolver({
455
+ collectInventory: inventory,
456
+ launchCompanion,
457
+ mateCommand: process.argv.slice(0, 2),
458
+ env: process.env,
459
+ noGit: options.noGit === true,
460
+ // A person in control continues the factory's own conversation.
461
+ takenOver: async (id) => (outcomes ? outcomes.takenOver(id) : null),
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
+ },
476
+ }
477
+ : {}),
319
478
  noGit: options.noGit === true,
320
479
  reportUrl: options.reportOrigin,
321
480
  ...deps.terminal,
322
481
  })
323
482
  : null;
324
-
325
483
  /** Stores a report for the live terminal session holding the bearer credential. */
326
484
  const publishReport = async (request: Request): Promise<Response> => {
327
485
  const token = readBearer(request);
@@ -350,13 +508,7 @@ export function createStudioFetch(
350
508
  html: body.html,
351
509
  });
352
510
  for (const notify of reportListeners.get(digest) ?? []) {
353
- notify({
354
- type: "report-published",
355
- companion: digest,
356
- id: stored.id,
357
- title: stored.title,
358
- createdAt: stored.createdAt,
359
- });
511
+ notify({ id: stored.id, title: stored.title });
360
512
  }
361
513
  const path = `${REPORT_VIEW_PREFIX}${stored.id}`;
362
514
  return json({
@@ -366,7 +518,203 @@ export function createStudioFetch(
366
518
  });
367
519
  };
368
520
 
369
- const handler = async (
521
+ /** One document's model, with the factory and terminal state its address needs. */
522
+ const collectPage = async (url: URL): Promise<StudioPage> => {
523
+ const page = await collectStudioPage(url, policy, inventory, snapshots, writable);
524
+ page.renderedAt = Date.now();
525
+ page.factoryRuns = page.companion ? await outcomesFor(page.companion.path).runs() : null;
526
+ if (terminal) {
527
+ const target = await effectiveLaunchCompanion(
528
+ page.inventory,
529
+ launchCompanion,
530
+ page.selection.companionDigest,
531
+ );
532
+ page.worksetSessions = process.env[FACTORY_BROKER_ENV]
533
+ ? Object.fromEntries(
534
+ terminal
535
+ .list()
536
+ .flatMap((session) => (session.workset ? [[session.workset.id, session.id]] : [])),
537
+ )
538
+ : null;
539
+ page.terminal = {
540
+ pinned: launchCompanion !== null,
541
+ target: target ? { path: target.path, digest: companionDigest(target.path) } : null,
542
+ agents: target ? await agentsFor(target.path) : [],
543
+ };
544
+ }
545
+ return page;
546
+ };
547
+
548
+ /** A registered companion by digest, or a refusal the caller reports. */
549
+ const companionPathOf = async (digest: string): Promise<string> => {
550
+ const selected = await selectedCompanion(digest || null, inventory);
551
+ if (!selected) throw new WorksetError(NO_COMPANION);
552
+ return selected.path;
553
+ };
554
+
555
+ /** Viewers of a companion's board, by digest; told when an Outcome or run changes. */
556
+ const boardListeners = new Map<string, Set<() => void>>();
557
+ const boardChanged = (digest: string) => {
558
+ for (const notify of boardListeners.get(digest) ?? []) notify();
559
+ };
560
+ if (outcomes) {
561
+ const digest = companionDigest(outcomes.companionPath);
562
+ outcomes.onChanged(() => boardChanged(digest));
563
+ }
564
+
565
+ let usage: Promise<UsageCache> | undefined = deps.usage && Promise.resolve(deps.usage);
566
+ const services: StudioServices = {
567
+ writable,
568
+ factoryMode: broker !== null,
569
+ keepsFolder: (companionPath) =>
570
+ broker !== null && !deletableWithin(companionPath, companionsDir),
571
+ modePolicy: policy,
572
+ page: collectPage,
573
+ worksetAction: async (digest, id, action, field: StudioFormField) => {
574
+ if (!writable) throw new WorksetError(NOT_WRITABLE);
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);
578
+ boardChanged(digest);
579
+ },
580
+ createOutcome: async (digest, field) => {
581
+ if (!writable) throw new WorksetError(NOT_WRITABLE);
582
+ await outcomesFor(await companionPathOf(digest)).create(field);
583
+ boardChanged(digest);
584
+ },
585
+ vault: async (digest, request) => {
586
+ const { vaultView } = await import("./views/vault/view");
587
+ return vaultView(vault, await companionPathOf(digest), request);
588
+ },
589
+ vaultChildren: async (digest, dir) => {
590
+ const { vaultChildren } = await import("./views/vault/view");
591
+ return vaultChildren(vault, await companionPathOf(digest), dir);
592
+ },
593
+ vaultMatches: async (digest, query) => {
594
+ const { vaultMatches } = await import("./views/vault/view");
595
+ return vaultMatches(vault, await companionPathOf(digest), query);
596
+ },
597
+ vaultPreview: async (digest, path, content) => {
598
+ await companionPathOf(digest);
599
+ const { markdownTree } = await import("./views/vault/markdown-tree");
600
+ return markdownTree(content, path);
601
+ },
602
+ vaultSave: async (digest, path, content, token) => {
603
+ if (!writable) throw new VaultPathError("start Studio with --writable to enable saving");
604
+ return vault.save(await companionPathOf(digest), path, content, token);
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
+ },
611
+ reports: async (digest) => {
612
+ await companionPathOf(digest);
613
+ return reports.list(digest);
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
+ },
626
+ skillPreview: async (digest, agent, name, file) => {
627
+ const { readSkillPreview } = await import("./skill-files");
628
+ return readSkillPreview(await companionPathOf(digest), agent, name, file);
629
+ },
630
+ deleteCompanion: async (digest) => {
631
+ if (!writable) {
632
+ throw new CompanionRemovalError("start Studio with --writable to delete companions");
633
+ }
634
+ const companionPath = await companionPathOf(digest);
635
+ const pinned = [launchCompanion, outcomes?.companionPath].filter(
636
+ (entry): entry is string => typeof entry === "string" && entry !== "",
637
+ );
638
+ // Real paths, so a symlinked start path still protects its folder.
639
+ const real = (entry: string) => realpath(entry).catch(() => path.resolve(entry));
640
+ const target = await real(companionPath);
641
+ const pinnedReal = await Promise.all(pinned.map(real));
642
+ if (pinnedReal.includes(target)) {
643
+ throw new CompanionRemovalError(
644
+ "Studio was started for this companion; it is not deleted.",
645
+ );
646
+ }
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
+ );
652
+ return { deletedFolder };
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
+ },
683
+ };
684
+ const app = options.app ?? null;
685
+
686
+ /** The route's refusal under its kind, decided once before it acts (design D4); `null` lets it act. */
687
+ const refusalFor = (
688
+ route: Exclude<RouteKind, { kind: "session" }>,
689
+ request: Request,
690
+ url: URL,
691
+ acceptedOrigin: string,
692
+ ): Response | null => {
693
+ if (access.requires("read") && !access.hasToken(request)) {
694
+ if (url.pathname !== "/") return refused(TOKEN_REASON, 401);
695
+ return html(TOKEN_REQUIRED_PAGE, 401);
696
+ }
697
+ if (route.kind === "read") return null;
698
+ if (route.kind === "terminal" && !terminal) {
699
+ return refused("start Studio with --writable --terminal to enable the terminal", 404);
700
+ }
701
+ const privileged = route.kind === "write" || route.privileged;
702
+ if (privileged && !access.originMatches(request, acceptedOrigin)) {
703
+ return refused(ORIGIN_REASON[route.kind], 403);
704
+ }
705
+ if (
706
+ access.requires(route.kind === "write" ? "save" : "terminal") &&
707
+ !access.hasToken(request)
708
+ ) {
709
+ return refused(TOKEN_REASON, 401);
710
+ }
711
+ if (route.kind === "write" && route.writable && !writable) {
712
+ return refused(route.writable, 403);
713
+ }
714
+ return null;
715
+ };
716
+
717
+ const dispatch = async (
370
718
  request: Request,
371
719
  server?: StudioUpgrader,
372
720
  ): Promise<Response | undefined> => {
@@ -377,23 +725,11 @@ export function createStudioFetch(
377
725
  const exchanged = exchangeStudioToken(request, access, acceptedOrigin);
378
726
  if (exchanged) return exchanged;
379
727
 
380
- if (url.pathname === REPORTS_ROUTE && request.method === "POST") {
381
- return publishReport(request);
382
- }
383
-
384
- const isSave = url.pathname === "/api/vault/save";
385
- const isEnd = url.pathname === "/api/terminal/sessions/end";
386
- const isPost = isSave || isEnd;
387
- if (isPost && request.method !== "POST") {
388
- return new Response(`${isSave ? "vault save" : "ending a session"} requires POST`, {
389
- status: 405,
390
- headers: { allow: "POST" },
391
- });
392
- }
393
- if (!READ_METHODS.has(request.method) && !(isPost && request.method === "POST")) {
394
- return new Response("studio serves read requests only", {
728
+ const route = routeOf(url, request.method, app !== null);
729
+ if (!route.methods.includes(request.method)) {
730
+ return new Response(`${request.method} is not served here`, {
395
731
  status: 405,
396
- headers: { allow: isPost ? "POST" : "GET, HEAD" },
732
+ headers: { allow: route.methods.join(", ") },
397
733
  });
398
734
  }
399
735
 
@@ -402,18 +738,14 @@ export function createStudioFetch(
402
738
  ? new Response(null, { status: response.status, headers: response.headers })
403
739
  : response;
404
740
 
405
- if (access.requires("read") && !access.hasToken(request)) {
406
- if (url.pathname === "/") {
407
- const page = html(TOKEN_REQUIRED_PAGE);
408
- return respond(new Response(page.body, { status: 401, headers: page.headers }));
409
- }
410
- return respond(refused(TOKEN_REASON, 401));
411
- }
741
+ if (route.kind === "session") return publishReport(request);
742
+ const refusal = refusalFor(route, request, url, acceptedOrigin);
743
+ if (refusal) return respond(refusal);
412
744
 
413
745
  if (url.pathname === REPORTS_ROUTE) {
414
746
  const digest = url.searchParams.get(COMPANION_PARAM) ?? "";
415
747
  if (!COMPANION_DIGEST_PATTERN.test(digest)) {
416
- return respond(json({ reason: "no registered companion was selected" }, 400));
748
+ return respond(json({ reason: NO_COMPANION }, 400));
417
749
  }
418
750
  return respond(json({ reports: await reports.list(digest) }));
419
751
  }
@@ -421,7 +753,7 @@ export function createStudioFetch(
421
753
  if (url.pathname.startsWith(REPORT_VIEW_PREFIX)) {
422
754
  const id = url.pathname.slice(REPORT_VIEW_PREFIX.length);
423
755
  const stored = isReportId(id) ? await reports.read(id) : null;
424
- if (stored === null) return respond(new Response("not found", { status: 404 }));
756
+ if (stored === null) return respond(notFound());
425
757
  return respond(
426
758
  new Response(stored, {
427
759
  headers: {
@@ -435,32 +767,36 @@ export function createStudioFetch(
435
767
  );
436
768
  }
437
769
 
438
- if (url.pathname.startsWith("/studio/terminal/") && terminal) {
439
- const asset = await terminalAsset(url.pathname);
770
+ if (url.pathname === FACTORY_CREDENTIAL_ROUTE) {
771
+ if (broker === null) return respond(notFound());
772
+ return respond(await factoryCredentialResponse(broker, request));
773
+ }
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
+
780
+ if (app) {
781
+ const asset = await studioAppAsset(app, url.pathname);
440
782
  if (asset) return respond(asset);
441
783
  }
442
784
 
443
- if (url.pathname === "/api/terminal" || url.pathname.startsWith("/api/terminal/")) {
444
- if (!terminal) {
445
- return respond(
446
- refused("start Studio with --writable --terminal to enable the terminal", 404),
447
- );
448
- }
449
- const privileged = url.pathname === "/api/terminal" || isEnd;
450
- if (privileged && !access.originMatches(request, acceptedOrigin)) {
451
- return respond(refused("the terminal is reachable only from Studio's own page", 403));
452
- }
453
- if (access.requires("terminal") && !access.hasToken(request)) {
454
- return respond(refused(TOKEN_REASON, 401));
455
- }
456
- if (url.pathname === "/api/terminal") {
785
+ // The terminal's asset prefix is core's own, with or without the terminal.
786
+ if (url.pathname.startsWith(TERMINAL_ASSET_PREFIX)) {
787
+ const asset = terminal ? await terminalAsset(url.pathname) : null;
788
+ return respond(asset ?? notFound());
789
+ }
790
+
791
+ if (route.kind === "terminal" && terminal) {
792
+ if (url.pathname === TERMINAL_SOCKET_ROUTE) {
457
793
  if (request.headers.get("upgrade")?.toLowerCase() !== "websocket" || !server) {
458
794
  return respond(refused("the terminal is a WebSocket endpoint", 426));
459
795
  }
460
796
  if (server.upgrade(request, { data: {} })) return undefined;
461
797
  return respond(refused("the terminal connection could not be upgraded", 400));
462
798
  }
463
- if (url.pathname === "/api/terminal/sessions") {
799
+ if (url.pathname === TERMINAL_SESSIONS_ROUTE) {
464
800
  const now = Date.now();
465
801
  return respond(
466
802
  json({
@@ -470,12 +806,13 @@ export function createStudioFetch(
470
806
  companion: companionDigest(session.companionPath),
471
807
  companionPath: session.companionPath,
472
808
  attached: session.attached,
809
+ ...(session.workset ? { workset: session.workset } : {}),
473
810
  ageSeconds: Math.max(0, Math.round((now - session.startedAt) / 1000)),
474
811
  })),
475
812
  }),
476
813
  );
477
814
  }
478
- if (isEnd) {
815
+ if (url.pathname === TERMINAL_SESSIONS_END_ROUTE) {
479
816
  let body: { id?: unknown };
480
817
  try {
481
818
  body = (await request.json()) as typeof body;
@@ -487,198 +824,60 @@ export function createStudioFetch(
487
824
  }
488
825
  return respond(json({ ended: body.id }));
489
826
  }
490
- return respond(new Response("not found", { status: 404 }));
491
- }
492
-
493
- if (url.pathname === "/api/vault/tree") {
494
- const selection = parseVaultSelection(url);
495
- const selected = await selectedCompanion(selection.companionDigest, inventory);
496
- if (!selected) return respond(json({ reason: "no registered companion was selected" }, 400));
497
- try {
498
- return respond(json(await vault.tree(selected.path, selection.refresh)));
499
- } catch (error) {
500
- return respond(
501
- json({ reason: error instanceof Error ? error.message : String(error) }, 400),
502
- );
503
- }
827
+ return respond(notFound());
504
828
  }
505
829
 
506
- if (url.pathname === "/api/vault/view") {
507
- const collected = await inventory();
508
- const selection = parseVaultSelection(url);
509
- const companion = resolveCompanion(collected, selection.companionDigest);
510
- if (!companion) return respond(json({ reason: "no registered companion was selected" }, 400));
511
- const state = await collectVaultState(vault, companion.path, selection, { tree: "await" });
512
- return respond(
513
- new Response(
514
- await renderVaultView({
515
- inventory: collected,
516
- selection,
517
- companion,
518
- payload: null,
519
- error: null,
520
- collectedAt: null,
521
- writable,
522
- vault: state,
523
- terminal: null,
524
- }),
525
- { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } },
526
- ),
527
- );
528
- }
529
-
530
- if (url.pathname === VAULT_DIR_ROUTE || url.pathname === VAULT_FILTER_ROUTE) {
531
- const selection = parseVaultSelection(url);
532
- const selected = await selectedCompanion(selection.companionDigest, inventory);
533
- if (!selected) return respond(json({ reason: "no registered companion was selected" }, 400));
534
- let listed;
535
- try {
536
- listed = await vault.tree(selected.path);
537
- } catch (error) {
538
- return respond(
539
- json({ reason: error instanceof Error ? error.message : String(error) }, 400),
540
- );
541
- }
542
- const page: StudioPage = {
543
- inventory: await inventory(),
544
- selection,
545
- companion: selected,
546
- payload: null,
547
- error: null,
548
- collectedAt: null,
549
- writable,
550
- vault: {
551
- tree: listed.tree,
552
- open: null,
553
- refusal: null,
554
- incoming: null,
555
- overwritten: null,
556
- watching: listed.watching,
557
- warning: listed.warning,
558
- generation: listed.generation,
559
- },
560
- terminal: null,
561
- };
562
- const headers = {
563
- "content-type": "text/html; charset=utf-8",
564
- "cache-control": "no-store",
565
- "x-vault-generation": String(listed.generation),
566
- };
567
- if (url.pathname === VAULT_FILTER_ROUTE) {
568
- const matches = await renderVaultMatches(page, url.searchParams.get("q") ?? "");
569
- return respond(new Response(matches, { headers }));
570
- }
571
- const children = await renderVaultChildren(page);
572
- if (children === null) {
573
- return respond(json({ reason: "that folder is not in the listed tree" }, 404));
574
- }
575
- return respond(new Response(children, { headers }));
576
- }
577
-
578
- if (url.pathname === VAULT_CHANGES_ROUTE) {
579
- const selection = parseVaultSelection(url);
580
- const selected = await selectedCompanion(selection.companionDigest, inventory);
581
- if (!selected) return respond(json({ reason: "no registered companion was selected" }, 400));
830
+ if (url.pathname === STUDIO_EVENTS_ROUTE) {
831
+ const digest = url.searchParams.get(COMPANION_PARAM) ?? "";
832
+ const selected = await selectedCompanion(digest || null, inventory);
833
+ if (!selected) return respond(json({ reason: NO_COMPANION }, 400));
582
834
  server?.timeout?.(request, 0);
583
- const reportsOnly = url.searchParams.get("scope") === "reports";
584
- return respond(
585
- changeStream(vault, selected.path, reportsOnly, (notify) => {
586
- const digest = companionDigest(selected.path);
587
- const set = reportListeners.get(digest) ?? new Set();
588
- set.add(notify);
589
- reportListeners.set(digest, set);
590
- return () => {
591
- set.delete(notify);
592
- if (set.size === 0) reportListeners.delete(digest);
593
- };
594
- }),
595
- );
596
- }
597
-
598
- if (url.pathname === "/api/vault/file") {
599
- const selection = parseVaultSelection(url);
600
- const selected = await selectedCompanion(selection.companionDigest, inventory);
601
- if (!selected) return respond(json({ reason: "no registered companion was selected" }, 400));
602
- try {
603
- return respond(json(await vault.open(selected.path, selection.openPath ?? "")));
604
- } catch (error) {
605
- return respond(
606
- json({ reason: error instanceof Error ? error.message : String(error) }, 400),
607
- );
608
- }
835
+ return respond(studioEvents(vault, selected.path, boardListeners, reportListeners));
609
836
  }
610
837
 
611
- if (url.pathname === "/api/vault/events") {
612
- const selection = parseVaultSelection(url);
838
+ if (url.pathname === VAULT_EVENTS_ROUTE) {
839
+ const selection = parseVaultSelection(url, policy);
613
840
  const selected = await selectedCompanion(selection.companionDigest, inventory);
614
- if (!selected) return respond(json({ reason: "no registered companion was selected" }, 400));
841
+ if (!selected) return respond(json({ reason: NO_COMPANION }, 400));
615
842
  try {
616
843
  const opened = await resolveVaultPath(selected.path, selection.openPath ?? "");
617
844
  server?.timeout?.(request, 0);
618
845
  return respond(vaultEvents(vault, selected.path, opened.relative));
619
846
  } catch (error) {
620
- return respond(
621
- json({ reason: error instanceof Error ? error.message : String(error) }, 400),
622
- );
847
+ return respond(json({ reason: errorMessage(error) }, 400));
623
848
  }
624
849
  }
625
850
 
626
- if (isSave) {
627
- if (!access.originMatches(request, acceptedOrigin)) {
628
- return respond(refused("a save must come from Studio's own page", 403));
629
- }
630
- if (access.requires("save") && !access.hasToken(request)) {
631
- return respond(refused(TOKEN_REASON, 401));
632
- }
633
- if (!writable)
634
- return respond(json({ reason: "start Studio with --writable to enable saving" }, 403));
635
- let body: { companion?: string; path?: string; content?: string; token?: string };
636
- try {
637
- body = (await request.json()) as typeof body;
638
- } catch {
639
- return respond(json({ reason: "save requires a JSON body" }, 400));
640
- }
641
- const selected = await selectedCompanion(
642
- typeof body.companion === "string" ? body.companion : null,
643
- inventory,
851
+ const logMatch = FACTORY_LOG.exec(url.pathname);
852
+ if (logMatch) {
853
+ const id = decodeURIComponent(logMatch[1]!);
854
+ if (!outcomes || !isWorksetId(id)) return respond(notFound());
855
+ if (logMatch[2]) return respond(logStream(outcomes, id));
856
+ return respond(
857
+ new Response(await outcomes.log(id), {
858
+ headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" },
859
+ }),
644
860
  );
645
- if (!selected || typeof body.path !== "string" || typeof body.content !== "string") {
646
- return respond(
647
- json({ reason: "save requires a registered companion, path, and content" }, 400),
648
- );
649
- }
650
- try {
651
- const result = await vault.save(selected.path, body.path, body.content, body.token);
652
- return respond(json(result, result.kind === "conflict" ? 409 : 200));
653
- } catch (error) {
654
- return respond(
655
- json(
656
- { reason: error instanceof Error ? error.message : String(error) },
657
- error instanceof VaultPathError ? 400 : 500,
658
- ),
659
- );
660
- }
661
861
  }
662
862
 
663
- if (url.pathname !== "/") return respond(new Response("not found", { status: 404 }));
863
+ // Everything else is the application's: its documents, views and server functions.
864
+ if (app) return respond(await app.fetch(request, { context: { studio: services } }));
865
+ if (url.pathname === "/") return respond(html(MISSING_BUILD_PAGE));
866
+ return respond(notFound());
867
+ };
664
868
 
665
- const page = await collectStudioPage(url, inventory, snapshots, vault, writable);
666
- if (terminal) {
667
- const target = await effectiveLaunchCompanion(
668
- page.inventory,
669
- launchCompanion,
670
- page.selection.companionDigest,
671
- );
672
- page.terminal = {
673
- pinned: launchCompanion !== null,
674
- target: target ? { path: target.path, digest: companionDigest(target.path) } : null,
675
- agents: target ? await agentsFor(target.path) : [],
676
- };
677
- }
678
- return respond(html(await render(page)));
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);
679
877
  };
680
878
 
681
879
  handler.terminal = terminal;
880
+ handler.services = services;
682
881
  handler.close = async () => {
683
882
  vault.stop();
684
883
  await terminal?.stopAll();
@@ -686,6 +885,22 @@ export function createStudioFetch(
686
885
  return handler;
687
886
  }
688
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
+
689
904
  async function selectedCompanion(
690
905
  digest: string | null,
691
906
  collectInventory: () => Promise<StudioInventory>,
@@ -724,49 +939,73 @@ function eventStream(
724
939
  });
725
940
  }
726
941
 
727
- function vaultEvents(vault: VaultManager, companionPath: string, requestedPath: string): Response {
728
- return eventStream("studio vault events", (send) =>
729
- vault.subscribe(companionPath, requestedPath, send),
730
- );
731
- }
732
-
733
942
  /**
734
- * Typed events for one companion: `vault-tree-changed` (a generation) and
735
- * `report-published`. No paths and no file content leave through this stream.
736
- * `reportsOnly` skips the vault subscription, which starts a watcher and listing.
943
+ * A Workset's run log as it grows: one `replay` (the stored log and the text still
944
+ * streaming), then the live events. Read-only; leaving never touches the run.
737
945
  */
738
- function changeStream(
946
+ function logStream(live: { watch(id: string): LiveViewer }, id: string): Response {
947
+ return eventStream("studio factory log", (send) => {
948
+ const viewer = live.watch(id);
949
+ void (async () => {
950
+ send({ type: "replay", ...(await viewer.replay) });
951
+ // oxlint-disable-next-line no-await-in-loop -- events arrive one at a time, in order
952
+ for (let event = await viewer.next(); event; event = await viewer.next()) send(event);
953
+ })().catch(() => viewer.close());
954
+ return () => viewer.close();
955
+ });
956
+ }
957
+
958
+ /** One stream per page, so a view updates in place instead of reloading (design D7). */
959
+ function studioEvents(
739
960
  vault: VaultManager,
740
961
  companionPath: string,
741
- reportsOnly: boolean,
742
- subscribeReports: (notify: (event: ReportPublishedEvent) => void) => () => void,
962
+ boards: Map<string, Set<() => void>>,
963
+ reports: Map<string, Set<(event: PublishedReport) => void>>,
743
964
  ): Response {
744
- return eventStream("studio changes", (send) => {
745
- const stopReports = subscribeReports(send);
746
- const stopTree = reportsOnly
747
- ? () => {}
748
- : vault.subscribeTree(companionPath, (generation) =>
749
- send({ type: "vault-tree-changed", generation }),
750
- );
965
+ const digest = companionDigest(companionPath);
966
+ const join = <T>(map: Map<string, Set<T>>, listener: T) => {
967
+ const set = map.get(digest) ?? new Set<T>();
968
+ set.add(listener);
969
+ map.set(digest, set);
970
+ return () => {
971
+ set.delete(listener);
972
+ if (set.size === 0) map.delete(digest);
973
+ };
974
+ };
975
+ return eventStream("studio events", (send: (event: StudioEvent) => void) => {
976
+ const leaveBoard = join(boards, () => send({ type: "board" }));
977
+ const leaveReports = join(reports, (report) =>
978
+ send({ type: "reports", id: report.id, title: report.title }),
979
+ );
980
+ const stopTree = vault.subscribeTree(companionPath, (generation) =>
981
+ send({ type: "vault-tree", generation }),
982
+ );
751
983
  return () => {
752
- stopReports();
984
+ leaveBoard();
985
+ leaveReports();
753
986
  stopTree();
754
987
  };
755
988
  });
756
989
  }
757
990
 
991
+ function vaultEvents(vault: VaultManager, companionPath: string, requestedPath: string): Response {
992
+ return eventStream("studio vault events", (send) =>
993
+ vault.subscribe(companionPath, requestedPath, send),
994
+ );
995
+ }
996
+
758
997
  /**
759
998
  * One rendered document's worth of state. An absent or unresolvable companion
760
999
  * is not a failure: the page renders the selector and the server keeps serving.
761
1000
  */
762
1001
  async function collectStudioPage(
763
1002
  url: URL,
1003
+ policy: StudioModePolicy,
764
1004
  collectInventory: () => Promise<StudioInventory>,
765
1005
  snapshots: StudioSnapshotCache,
766
- vault: VaultManager,
767
1006
  writable: boolean,
768
1007
  ): Promise<StudioPage> {
769
- const selection = parse(url);
1008
+ const selection = parse(url, policy);
770
1009
  const inventory = await collectInventory();
771
1010
  const companion = resolveCompanion(inventory, selection.companionDigest);
772
1011
  const page: StudioPage = {
@@ -781,19 +1020,7 @@ async function collectStudioPage(
781
1020
  terminal: null,
782
1021
  };
783
1022
 
784
- if (!companion) {
785
- vault.deactivate();
786
- return page;
787
- }
788
-
789
- if (selection.view === "vault") {
790
- return {
791
- ...page,
792
- vault: await collectVaultState(vault, companion.path, selection, { tree: "prefetch" }),
793
- };
794
- }
795
-
796
- vault.deactivate();
1023
+ if (!companion) return page;
797
1024
 
798
1025
  try {
799
1026
  const snapshot = await snapshots.read(companion.path, selection.refresh);
@@ -805,7 +1032,7 @@ async function collectStudioPage(
805
1032
  ...page,
806
1033
  error: {
807
1034
  companionPath: companion.path,
808
- reason: error instanceof Error ? error.message : String(error),
1035
+ reason: errorMessage(error),
809
1036
  },
810
1037
  };
811
1038
  }
@@ -826,15 +1053,15 @@ function bunServe(options: StudioServeOptions): StudioBoundServer {
826
1053
  return runtime.serve(options);
827
1054
  }
828
1055
 
1056
+ /** An IPv6 literal in brackets, as a URL needs it; any other host as it is. */
1057
+ function urlHost(hostname: string): string {
1058
+ return hostname.includes(":") && !hostname.startsWith("[") ? `[${hostname}]` : hostname;
1059
+ }
1060
+
829
1061
  /** Where a process on this host reaches the server: loopback for wildcard binds. */
830
1062
  function reportOrigin(hostname: string, port: number): string {
831
1063
  const wildcard = hostname === "0.0.0.0" || hostname === "::" || hostname === "[::]";
832
- const host = wildcard
833
- ? "127.0.0.1"
834
- : hostname.includes(":") && !hostname.startsWith("[")
835
- ? `[${hostname}]`
836
- : hostname;
837
- return `http://${host}:${port}`;
1064
+ return `http://${wildcard ? "127.0.0.1" : urlHost(hostname)}:${port}`;
838
1065
  }
839
1066
 
840
1067
  /**
@@ -867,6 +1094,8 @@ export function startStudioServer(
867
1094
  detachMinutes: options.detachMinutes,
868
1095
  launchCompanion: options.launchCompanion,
869
1096
  noGit: options.noGit,
1097
+ profile: options.profile,
1098
+ app: options.app,
870
1099
  });
871
1100
  const registry = fetchHandler.terminal;
872
1101
  const server = serve({
@@ -903,12 +1132,8 @@ export function startStudioServer(
903
1132
  : {}),
904
1133
  });
905
1134
  boundPort = server.port;
906
- const urlHostname =
907
- hostname === STUDIO_HOSTNAME || hostname === "localhost" || hostname === "::1"
908
- ? "localhost"
909
- : hostname.includes(":") && !hostname.startsWith("[")
910
- ? `[${hostname}]`
911
- : hostname;
1135
+ const loopback = hostname === STUDIO_HOSTNAME || hostname === "localhost" || hostname === "::1";
1136
+ const urlHostname = loopback ? "localhost" : urlHost(hostname);
912
1137
 
913
1138
  return {
914
1139
  url: `http://${urlHostname}:${server.port}`,