@uniqbit/mate-core 1.0.0-canary.3 → 1.0.0-canary.5

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 (186) hide show
  1. package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +1 -1
  2. package/claude-plugin/hooks/hooks.json +21 -1
  3. package/claude-plugin/hooks/session-attention.mjs +10 -0
  4. package/claude-plugin/hooks/session-end.mjs +9 -0
  5. package/claude-plugin/hooks/session-guidance.mjs +1 -1
  6. package/opencode-plugin/src/server.ts +13 -2
  7. package/package.json +1 -1
  8. package/src/cli/commands/artifact/delivery/archive.ts +2 -2
  9. package/src/cli/commands/artifact/delivery/link.ts +22 -5
  10. package/src/cli/commands/artifact/delivery/output.ts +9 -1
  11. package/src/cli/commands/artifact/finish/openspec.ts +1 -3
  12. package/src/cli/commands/companion/companion.ts +1 -1
  13. package/src/cli/commands/companion/link.ts +36 -4
  14. package/src/cli/commands/companion/open.ts +40 -12
  15. package/src/cli/commands/doctor.ts +122 -0
  16. package/src/cli/commands/session/prepare.ts +32 -4
  17. package/src/cli/commands/session/registry.ts +90 -0
  18. package/src/cli/commands/studio/companion-removal.ts +79 -0
  19. package/src/cli/commands/studio/mate-inventory.ts +1 -1
  20. package/src/cli/commands/studio/payload.ts +12 -1
  21. package/src/cli/commands/studio/server.ts +39 -16
  22. package/src/cli/commands/studio/services.ts +20 -0
  23. package/src/cli/commands/studio/skill-files.ts +133 -0
  24. package/src/cli/commands/studio/vault.ts +218 -44
  25. package/src/cli/commands/studio/views/model.ts +0 -5
  26. package/src/cli/commands/studio/views/vault/markdown-tree.ts +255 -4
  27. package/src/cli/commands/unwrap.ts +8 -0
  28. package/src/cli/commands/update.ts +26 -8
  29. package/src/cli/commands/vscode/setup.ts +155 -0
  30. package/src/cli/commands/vscode/vsix.ts +73 -0
  31. package/src/cli/commands/working/cleanup.ts +34 -10
  32. package/src/cli/commands/working/worktree.ts +58 -8
  33. package/src/cli/commands/wrap.ts +33 -7
  34. package/src/cli/main.ts +9 -2
  35. package/src/cli/usage.ts +6 -1
  36. package/src/hooks/companion-instructions.ts +19 -11
  37. package/src/hooks/hook-io.ts +15 -0
  38. package/src/hooks/session-banner.ts +5 -3
  39. package/src/hooks/session-end.ts +10 -0
  40. package/src/hooks/session-guidance.ts +10 -6
  41. package/src/hooks/session-prepare.ts +47 -31
  42. package/src/hooks/session-register.ts +199 -0
  43. package/src/hooks/tokensave-route.ts +7 -3
  44. package/src/hooks/validate-artifact-path.ts +9 -2
  45. package/src/lib/delivery/archive-change.ts +0 -1
  46. package/src/lib/delivery/branches.ts +15 -0
  47. package/src/lib/delivery/record-delivery.ts +94 -39
  48. package/src/lib/delivery/record.ts +30 -28
  49. package/src/lib/delivery/refresh.ts +37 -17
  50. package/src/lib/delivery/resolve-branch.ts +258 -37
  51. package/src/lib/factory/outcomes/index.ts +11 -1
  52. package/src/lib/factory/runtime.ts +10 -1
  53. package/src/lib/opencode-server.ts +238 -0
  54. package/src/lib/orchestrator/adapters/claude.ts +147 -2
  55. package/src/lib/orchestrator/adapters/opencode.ts +53 -2
  56. package/src/lib/orchestrator/checkout-adoption.ts +125 -0
  57. package/src/lib/orchestrator/companion-registry-store.ts +6 -2
  58. package/src/lib/orchestrator/editor.ts +2 -2
  59. package/src/lib/orchestrator/framework-context.ts +26 -14
  60. package/src/lib/orchestrator/global-config-store.ts +11 -0
  61. package/src/lib/orchestrator/launcher.ts +15 -2
  62. package/src/lib/orchestrator/projection-claude-links.ts +52 -5
  63. package/src/lib/orchestrator/projection-claude-skills.ts +28 -2
  64. package/src/lib/orchestrator/projection-companion-link.ts +12 -1
  65. package/src/lib/orchestrator/registry-checkouts.ts +177 -0
  66. package/src/lib/orchestrator/repository-link.ts +216 -57
  67. package/src/lib/orchestrator/serving-claude-wrap.ts +43 -0
  68. package/src/lib/orchestrator/session-context-link.ts +11 -5
  69. package/src/lib/orchestrator/session-prepare.ts +36 -6
  70. package/src/lib/orchestrator/types.ts +5 -0
  71. package/src/lib/orchestrator/workspace-inventory.ts +5 -1
  72. package/src/lib/public-npm.ts +17 -0
  73. package/src/lib/session-attribution.ts +52 -0
  74. package/src/lib/session-state.ts +285 -0
  75. package/src/lib/session-stop.ts +64 -0
  76. package/src/lib/workset/record.ts +20 -0
  77. package/src/lib/workset/worktree.ts +85 -17
  78. package/src/opencode/background-server.ts +145 -0
  79. package/src/opencode/companion-hooks.ts +3 -1
  80. package/src/opencode/companion-policy.ts +2 -2
  81. package/src/opencode/projected-guidance.ts +2 -1
  82. package/src/opencode/session-register.ts +176 -0
  83. package/src/runtime/claude-delivery-plan.ts +14 -3
  84. package/src/runtime/current-branch.ts +10 -0
  85. package/src/runtime/env.ts +13 -7
  86. package/src/runtime/git-layout.ts +164 -17
  87. package/src/runtime/launch-env-guard.ts +65 -0
  88. package/src/runtime/opencode-server-record.ts +136 -0
  89. package/src/runtime/projection.ts +40 -6
  90. package/src/runtime/repo-local.ts +6 -1
  91. package/src/runtime/serving-claude-wrap.ts +28 -0
  92. package/src/runtime/session-context.ts +4 -3
  93. package/src/runtime/session-registry.ts +434 -0
  94. package/src/runtime/tokensave-route.ts +10 -5
  95. package/src/runtime/wrap-state.ts +31 -0
  96. package/src/studio.ts +2 -0
  97. package/src/templates/mate-skills/agents/mate-apply-change/SKILL.md +49 -21
  98. package/src/templates/mate-skills/agents/mate-archive-change/SKILL.md +0 -5
  99. package/src/templates/mate-skills/agents/mate-propose-change/SKILL.md +2 -8
  100. package/src/templates/mate-skills/agents/mate-propose-change/references/mate-revise.md +1 -3
  101. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +2 -4
  102. package/src/templates/mate-skills/claude/mate-apply-change/SKILL.md +49 -21
  103. package/src/templates/mate-skills/claude/mate-archive-change/SKILL.md +0 -5
  104. package/src/templates/mate-skills/claude/mate-propose-change/SKILL.md +2 -8
  105. package/src/templates/mate-skills/claude/mate-propose-change/references/mate-revise.md +1 -3
  106. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +2 -4
  107. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +404 -30
  108. package/src/tools/setup/dynamic-plugins/hydrate.ts +4 -3
  109. package/src/tools/setup/providers/claude-plugin-hooks.ts +26 -0
  110. package/src/tools/setup/providers/claude.ts +21 -1
  111. package/studio-dist/client/assets/app-CdPiFv59.css +2 -0
  112. package/studio-dist/client/assets/button-BIIHE0EQ.js +3 -0
  113. package/studio-dist/client/assets/companion-view-DM6YyXaR.js +1 -0
  114. package/studio-dist/client/assets/delivery-path-DELxj0Av.js +1 -0
  115. package/studio-dist/client/assets/factory-BZy0E8ty.js +4 -0
  116. package/studio-dist/client/assets/index-B3wkMzjA.js +40 -0
  117. package/studio-dist/client/assets/markdown-view-pQ2Qp_i5.js +1 -0
  118. package/studio-dist/client/assets/panel-CbajlC3p.js +1 -0
  119. package/studio-dist/client/assets/{prepaint-CD5OpmTM.js → prepaint-CwSrpdFA.js} +7 -4
  120. package/studio-dist/client/assets/react-CN2GSx7x.js +1 -0
  121. package/studio-dist/client/assets/reports-DllhYQ5_.js +1 -0
  122. package/studio-dist/client/assets/routes-COm-G3mK.js +1 -0
  123. package/studio-dist/client/assets/skills-DmWAy-jZ.js +1 -0
  124. package/studio-dist/client/assets/specs-BG3Wi3ln.js +1 -0
  125. package/studio-dist/client/assets/steps-DFsH3Neu.js +1 -0
  126. package/studio-dist/client/assets/vault-B2q1nBY5.js +1 -0
  127. package/studio-dist/client/assets/warnings-BSXIyuSQ.js +1 -0
  128. package/studio-dist/client/assets/workflow-DlsQD6Hc.js +1 -0
  129. package/studio-dist/server/assets/{__23tanstack-start-server-fn-resolver-BQKuMdJW.js → __23tanstack-start-server-fn-resolver-M2GBs8s3.js} +179 -9
  130. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +35 -25
  131. package/studio-dist/server/assets/button-CIJqAhni.js +11929 -0
  132. package/studio-dist/server/assets/{companion-view-aBady57v.js → companion-view-DISASvdJ.js} +13 -7
  133. package/studio-dist/server/assets/companions-BYbHWKOZ.js +15 -0
  134. package/studio-dist/server/assets/delivery-path-C29fBynY.js +654 -0
  135. package/studio-dist/server/assets/{factory-DT3UzHlh.js → factory-DGPmNGbo.js} +1 -0
  136. package/studio-dist/server/assets/{factory-D6xnjedJ.js → factory-DUTa0eDs.js} +317 -530
  137. package/studio-dist/server/assets/markdown-view-Bn7xPdks.js +86 -0
  138. package/studio-dist/server/assets/panel-3Jmn4awF.js +169 -0
  139. package/studio-dist/server/assets/{prepaint-BMke0fo1.js → prepaint-DJfTQ_VH.js} +6 -2
  140. package/studio-dist/server/assets/{react-COs0LHn-.js → react-Ce6dj15C.js} +4 -9
  141. package/studio-dist/server/assets/reports-C06RXVE2.js +18 -0
  142. package/studio-dist/server/assets/reports-D6YMqhnO.js +142 -0
  143. package/studio-dist/server/assets/router-C8MGqlAY.js +13713 -0
  144. package/studio-dist/server/assets/routes-BcFgvqf7.js +622 -0
  145. package/studio-dist/server/assets/{shell-CboT2f66.js → shell-DS3wUexh.js} +1 -0
  146. package/studio-dist/server/assets/skills-BEnOxiDl.js +266 -0
  147. package/studio-dist/server/assets/skills-CtrBAtX3.js +28 -0
  148. package/studio-dist/server/assets/specs-C8rv34-5.js +211 -0
  149. package/studio-dist/server/assets/{start-BW5ovN0k.js → start-h3ICWwd2.js} +4 -1
  150. package/studio-dist/server/assets/steps-Dq_CwY_s.js +181 -0
  151. package/studio-dist/server/assets/{vault-BGulVoNh.js → vault-BmWnryh3.js} +16 -1
  152. package/studio-dist/server/assets/vault-Fvxt2Tzl.js +1032 -0
  153. package/studio-dist/server/assets/{views-Bd7cRr27.js → views-BgYa-za2.js} +1 -3
  154. package/studio-dist/server/assets/warnings-DzR6fyZh.js +23 -0
  155. package/studio-dist/server/assets/workflow-liRYecHk.js +73 -0
  156. package/studio-dist/server/server.js +3 -157
  157. package/studio-dist/client/assets/companion-view-Csva26Ir.js +0 -1
  158. package/studio-dist/client/assets/delivery-path-DJMpRmiY.js +0 -1
  159. package/studio-dist/client/assets/factory-B7l9ZQyx.js +0 -4
  160. package/studio-dist/client/assets/index-n6uo_92S.js +0 -40
  161. package/studio-dist/client/assets/queries-CN3JwMBX.js +0 -1
  162. package/studio-dist/client/assets/react-CabXf2Ds.js +0 -1
  163. package/studio-dist/client/assets/report-time-Dc-KOqQu.js +0 -1
  164. package/studio-dist/client/assets/reports-C01RsnMA.js +0 -1
  165. package/studio-dist/client/assets/routes-4pbC-2Hj.js +0 -1
  166. package/studio-dist/client/assets/skills-CihQganl.js +0 -1
  167. package/studio-dist/client/assets/spec-areas-C2L48N4C.js +0 -1
  168. package/studio-dist/client/assets/specs-D24_35_K.js +0 -1
  169. package/studio-dist/client/assets/studio-DKxfi691.css +0 -1
  170. package/studio-dist/client/assets/studio-queries-rvbJupCy.js +0 -3
  171. package/studio-dist/client/assets/vault-Bd4CQiTK.js +0 -1
  172. package/studio-dist/client/assets/warnings-V_Ys51wJ.js +0 -1
  173. package/studio-dist/client/assets/workflow-BJejeVwQ.js +0 -1
  174. package/studio-dist/server/assets/delivery-path-BkKNjgkf.js +0 -778
  175. package/studio-dist/server/assets/queries-Ag2iL8q2.js +0 -107
  176. package/studio-dist/server/assets/report-time-DAfzln-N.js +0 -8
  177. package/studio-dist/server/assets/reports-BnUNJVtx.js +0 -126
  178. package/studio-dist/server/assets/router-BH--drIx.js +0 -4298
  179. package/studio-dist/server/assets/routes-khSDK1bV.js +0 -361
  180. package/studio-dist/server/assets/skills-MWYnWoKs.js +0 -106
  181. package/studio-dist/server/assets/spec-areas-DcnO6vW-.js +0 -16
  182. package/studio-dist/server/assets/specs-DE3w8hZP.js +0 -155
  183. package/studio-dist/server/assets/studio-queries-CLnP9kGu.js +0 -3365
  184. package/studio-dist/server/assets/vault-CuyyhLyB.js +0 -832
  185. package/studio-dist/server/assets/warnings-BH05rOuG.js +0 -15
  186. package/studio-dist/server/assets/workflow-BSuIKWqH.js +0 -42
@@ -1,12 +1,14 @@
1
1
  import path from "node:path";
2
2
 
3
3
  import { FRAMEWORK_NAME } from "../../../framework";
4
+ import { adoptCheckout, lookUpAdoption } from "../../../lib/orchestrator/checkout-adoption";
4
5
  import { findRepoLocalLinkedRepository } from "../../../lib/orchestrator/repository-link";
5
6
  import { prepareSession, type PrepareResult } from "../../../lib/orchestrator/session-prepare";
6
7
  import { readProjectionFile } from "../../../runtime/projection";
7
8
  import { readWrapState, WRAP_RUNTIMES } from "../../../runtime/wrap-state";
8
9
  import { writeJsonStdout } from "../../write-json-stdout";
9
10
  import { launchAmbiguityDeps } from "../shared/companion-selection";
11
+ import { runSessionRegistryCommand } from "./registry";
10
12
 
11
13
  export interface SessionPrepareArgs {
12
14
  repo: string;
@@ -49,6 +51,8 @@ export function parseSessionPrepareArgs(
49
51
 
50
52
  export const sessionPrepareCommandDeps = {
51
53
  findRepoLocalLinkedRepository,
54
+ lookUpAdoption,
55
+ adoptCheckout,
52
56
  prepareSession,
53
57
  resolveLinkedCompanions: launchAmbiguityDeps.resolveLinkedCompanions,
54
58
  };
@@ -85,14 +89,29 @@ export async function runSessionPrepareCommand(
85
89
  if ("error" in parsed) return fail(parsed.error, true);
86
90
 
87
91
  const deps = sessionPrepareCommandDeps;
88
- const repository = await deps.findRepoLocalLinkedRepository(parsed.repo);
92
+ let repository = await deps.findRepoLocalLinkedRepository(parsed.repo);
89
93
  const wrapped = repository ? (await readWrapState(repository.path)).runtimes : new Set();
90
- const runtimes = WRAP_RUNTIMES.filter((runtime) => wrapped.has(runtime));
94
+ let runtimes = WRAP_RUNTIMES.filter((runtime) => wrapped.has(runtime));
95
+ let companionPath: string | undefined;
91
96
  if (!repository || runtimes.length === 0) {
92
- return fail(`${parsed.repo} is not wrapped. Run \`${FRAMEWORK_NAME} wrap\` there first.`);
97
+ /**
98
+ * A new Checkout, or one whose manifest records none, takes its Registered
99
+ * Checkout's wraps (design Decision 8). Looked up first, so a refusal writes nothing.
100
+ */
101
+ const adoption = await deps.lookUpAdoption(parsed.repo);
102
+ if (!adoption || adoption.runtimes.length === 0) {
103
+ return fail(`${parsed.repo} is not wrapped. Run \`${FRAMEWORK_NAME} wrap\` there first.`);
104
+ }
105
+ runtimes = adoption.runtimes;
106
+ companionPath = adoption.companionPath;
107
+ /**
108
+ * The link and the projection, outside the companion lock the wrap pass
109
+ * takes; also when an earlier command already wrote the link.
110
+ */
111
+ repository = await deps.adoptCheckout(parsed.repo, adoption);
93
112
  }
94
113
 
95
- const companionPath = await resolveCompanionPath(repository.path);
114
+ companionPath ??= await resolveCompanionPath(repository.path);
96
115
  if (!companionPath) return fail(`no companion is linked to ${repository.id}.`);
97
116
 
98
117
  const result = await deps.prepareSession({
@@ -115,5 +134,14 @@ export async function runSessionCommand(subcommand: string | undefined, rest: st
115
134
  await runSessionPrepareCommand(rest);
116
135
  return;
117
136
  }
137
+ if (
138
+ subcommand === "add" ||
139
+ subcommand === "list" ||
140
+ subcommand === "remove" ||
141
+ subcommand === "stop"
142
+ ) {
143
+ await runSessionRegistryCommand(subcommand, rest);
144
+ return;
145
+ }
118
146
  fail(`unknown session subcommand: ${subcommand ?? ""}`.trimEnd(), true);
119
147
  }
@@ -0,0 +1,90 @@
1
+ import { FRAMEWORK_NAME } from "../../../framework";
2
+ import {
3
+ addSession,
4
+ removeSession,
5
+ SessionRegistryError,
6
+ sessionRegistryPath,
7
+ } from "../../../runtime/session-registry";
8
+ import { listSessionsWithState, type SessionStateDeps } from "../../../lib/session-state";
9
+ import { stopSession, type SessionStopDeps } from "../../../lib/session-stop";
10
+ import { writeJsonStdout } from "../../write-json-stdout";
11
+
12
+ /**
13
+ * `mate session add|list|remove|stop`: Machine Caller contract for editor plugins.
14
+ * Always JSON on stdout; errors on stderr with a non-zero exit.
15
+ */
16
+
17
+ const USAGE = [
18
+ `Usage: ${FRAMEWORK_NAME} session add --runtime <claude|opencode> --id <id> --cwd <dir> [--origin <editor|managed|unmanaged>] --json`,
19
+ ` ${FRAMEWORK_NAME} session list --json`,
20
+ ` ${FRAMEWORK_NAME} session remove <id> --json`,
21
+ ` ${FRAMEWORK_NAME} session stop <id> --json`,
22
+ ].join("\n");
23
+
24
+ function fail(message: string, usage = false): void {
25
+ console.error(`${FRAMEWORK_NAME}: ${message}`);
26
+ if (usage) console.error(USAGE);
27
+ process.exitCode = 1;
28
+ }
29
+
30
+ interface ParsedArgs {
31
+ flags: Record<string, string>;
32
+ positionals: string[];
33
+ }
34
+
35
+ function parseArgs(argv: string[], valueFlags: string[]): ParsedArgs | { error: string } {
36
+ const parsed: ParsedArgs = { flags: {}, positionals: [] };
37
+ for (let index = 0; index < argv.length; index += 1) {
38
+ const arg = argv[index]!;
39
+ if (!arg.startsWith("--")) {
40
+ parsed.positionals.push(arg);
41
+ continue;
42
+ }
43
+ const [flag, inline] = arg.includes("=") ? arg.split(/=(.*)/s) : [arg];
44
+ if (flag === "--json") continue;
45
+ const name = flag!.slice(2);
46
+ if (!valueFlags.includes(name)) return { error: `unknown option: ${arg}` };
47
+ const value = inline ?? argv[++index];
48
+ if (!value) return { error: `${flag} requires a value` };
49
+ parsed.flags[name] = value;
50
+ }
51
+ return parsed;
52
+ }
53
+
54
+ export async function runSessionRegistryCommand(
55
+ subcommand: "add" | "list" | "remove" | "stop",
56
+ argv: string[],
57
+ file: string = sessionRegistryPath(),
58
+ stateDeps: SessionStateDeps = {},
59
+ stopDeps: SessionStopDeps = {},
60
+ ): Promise<void> {
61
+ const parsed = parseArgs(argv, subcommand === "add" ? ["runtime", "id", "cwd", "origin"] : []);
62
+ if ("error" in parsed) return fail(parsed.error, true);
63
+ try {
64
+ if (subcommand === "add") {
65
+ const { runtime, id, cwd, origin } = parsed.flags;
66
+ if (!runtime || !id || !cwd || parsed.positionals.length > 0) {
67
+ return fail("session add needs --runtime, --id, and --cwd", true);
68
+ }
69
+ await writeJsonStdout(await addSession({ runtime, id, cwd, origin }, { file }));
70
+ return;
71
+ }
72
+ if (subcommand === "list") {
73
+ if (parsed.positionals.length > 0) return fail("session list takes no arguments", true);
74
+ await writeJsonStdout(await listSessionsWithState({ file, ...stateDeps }));
75
+ return;
76
+ }
77
+ if (parsed.positionals.length !== 1) {
78
+ return fail(`session ${subcommand} needs one session id`, true);
79
+ }
80
+ const id = parsed.positionals[0]!;
81
+ if (subcommand === "stop") {
82
+ await writeJsonStdout(await stopSession(id, { file, ...stopDeps }));
83
+ return;
84
+ }
85
+ await writeJsonStdout(await removeSession(id, file));
86
+ } catch (error) {
87
+ if (error instanceof SessionRegistryError) return fail(error.message);
88
+ throw error;
89
+ }
90
+ }
@@ -0,0 +1,79 @@
1
+ import fs from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ import { parse } from "yaml";
6
+
7
+ import { FRAMEWORK_NAME } from "../../../framework";
8
+ import { pathIsDirectory } from "../../../lib/fs-utils";
9
+ import { GlobalConfigStore } from "../../../lib/orchestrator/global-config-store";
10
+
11
+ export interface CompanionRemoval {
12
+ companionPath: string;
13
+ /** Whether a folder was deleted; a stale entry only leaves the registry. */
14
+ deletedFolder: boolean;
15
+ }
16
+
17
+ export interface CompanionRemovalDeps {
18
+ store?: Pick<GlobalConfigStore, "list" | "unregister">;
19
+ isDirectory?: (target: string) => Promise<boolean>;
20
+ readFile?: (target: string) => Promise<string>;
21
+ remove?: (target: string) => Promise<void>;
22
+ home?: string;
23
+ }
24
+
25
+ /** A refusal Studio shows as it is; nothing was deleted or unregistered. */
26
+ export class CompanionRemovalError extends Error {}
27
+
28
+ /** True when `target` is `ancestor` or lies inside it. */
29
+ const within = (target: string, ancestor: string): boolean => {
30
+ const relative = path.relative(ancestor, target);
31
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
32
+ };
33
+
34
+ /**
35
+ * Deletes a registered Companion Repository's folder and drops its registry entry; not
36
+ * recoverable. A registered path whose folder is already gone is only unregistered. The
37
+ * folder is deleted only when it carries a companion configuration, and never when it is
38
+ * the filesystem root, the home folder or a folder holding the home folder.
39
+ */
40
+ export async function deleteRegisteredCompanion(
41
+ rawPath: string,
42
+ deps: CompanionRemovalDeps = {},
43
+ ): Promise<CompanionRemoval> {
44
+ const store = deps.store ?? new GlobalConfigStore();
45
+ const isDirectory = deps.isDirectory ?? pathIsDirectory;
46
+ const readFile = deps.readFile ?? ((target: string) => fs.readFile(target, "utf8"));
47
+ const remove =
48
+ deps.remove ?? ((target: string) => fs.rm(target, { recursive: true, force: false }));
49
+ const home = path.resolve(deps.home ?? os.homedir());
50
+ const companionPath = path.resolve(rawPath);
51
+
52
+ const registered = (await store.list()).some((entry) => path.resolve(entry) === companionPath);
53
+ if (!registered)
54
+ throw new CompanionRemovalError(`${companionPath} is not a registered companion.`);
55
+
56
+ if (!(await isDirectory(companionPath))) {
57
+ await store.unregister(companionPath);
58
+ return { companionPath, deletedFolder: false };
59
+ }
60
+ if (companionPath === path.parse(companionPath).root || within(home, companionPath)) {
61
+ throw new CompanionRemovalError(`${companionPath} holds the home folder; it is never deleted.`);
62
+ }
63
+ const config = path.join(companionPath, `.${FRAMEWORK_NAME}`, "config", "framework.yaml");
64
+ let type: unknown;
65
+ try {
66
+ type = (parse(await readFile(config)) as { type?: unknown } | null)?.type;
67
+ } catch {
68
+ throw new CompanionRemovalError(
69
+ `${companionPath} carries no readable companion configuration; it was not deleted.`,
70
+ );
71
+ }
72
+ // A missing type predates the field and is a companion, as registration reads it.
73
+ if (type !== undefined && type !== "companion") {
74
+ throw new CompanionRemovalError(`${companionPath} is not a companion; it was not deleted.`);
75
+ }
76
+ await remove(companionPath);
77
+ await store.unregister(companionPath);
78
+ return { companionPath, deletedFolder: true };
79
+ }
@@ -8,7 +8,7 @@ export interface StudioSkillInventory {
8
8
  agents: string[];
9
9
  }
10
10
 
11
- const SKILL_DIRS = {
11
+ export const SKILL_DIRS = {
12
12
  claude: ".claude",
13
13
  opencode: ".opencode",
14
14
  agents: ".agents",
@@ -7,6 +7,7 @@ import {
7
7
  parseAnchor,
8
8
  SPECS_RELATIVE_DIR,
9
9
  } from "../../../lib/change-layout";
10
+ import { companionTicketFormat, type TicketFormat } from "../../../lib/delivery/branches";
10
11
  import { linkedRepositoryIdentities } from "../../../lib/workset/repositories";
11
12
  import type { readWorksets, WorksetProblem } from "../../../lib/workset/record";
12
13
  import type { WorksetStageId, WorksetTurn } from "../../../lib/workset/stage";
@@ -97,6 +98,8 @@ export interface StudioCompanionPayload {
97
98
  worksets: StudioWorkset[];
98
99
  /** `org/repository` identities linked to the companion: what a new Workset may name. */
99
100
  linkedRepositories: string[];
101
+ /** The companion's ticket setting; the Outcome form offers a Ticket field only for `jira`. */
102
+ ticketFormat: TicketFormat;
100
103
  /** Records that could not be read, by path and reason. */
101
104
  worksetProblems: WorksetProblem[];
102
105
  warnings: string[];
@@ -123,6 +126,7 @@ export interface CompanionPayloadDeps {
123
126
  hasArchivedProposal?: (companionPath: string, anchor: string) => Promise<boolean>;
124
127
  readWorksets?: typeof readWorksets;
125
128
  linkedRepositoryIdentities?: typeof linkedRepositoryIdentities;
129
+ ticketFormat?: typeof companionTicketFormat;
126
130
  archiveAnchors?: typeof archiveAnchors;
127
131
  /** Whether an archive's Publication Merge Gate is open: merged, not applicable, or legacy. */
128
132
  archiveMergeSettled?: (companionPath: string, anchor: string) => Promise<boolean>;
@@ -379,7 +383,7 @@ export async function assembleCompanionPayload(
379
383
  );
380
384
 
381
385
  const shippedChanges = "changes" in shipped ? shipped.changes : [];
382
- const [worksets, linkedRepositories] = await Promise.all([
386
+ const [worksets, linkedRepositories, ticketFormat] = await Promise.all([
383
387
  collectWorksets(companionPath, changes, shippedChanges, deps).catch((error: unknown) => {
384
388
  warnings.push(`worksets: ${errorMessage(error)}`);
385
389
  return { worksets: [], problems: [] };
@@ -390,6 +394,12 @@ export async function assembleCompanionPayload(
390
394
  return [];
391
395
  },
392
396
  ),
397
+ (deps.ticketFormat ?? companionTicketFormat)(companionPath).catch(
398
+ (error: unknown): TicketFormat => {
399
+ warnings.push(`ticket setting: ${errorMessage(error)}`);
400
+ return "none";
401
+ },
402
+ ),
393
403
  ]);
394
404
 
395
405
  return {
@@ -412,6 +422,7 @@ export async function assembleCompanionPayload(
412
422
  topology: topology.ok ? topology.value : null,
413
423
  worksets: worksets.worksets,
414
424
  linkedRepositories,
425
+ ticketFormat,
415
426
  worksetProblems: worksets.problems,
416
427
  warnings,
417
428
  };
@@ -7,7 +7,11 @@ 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 { CompanionRemovalError, deleteRegisteredCompanion } from "./companion-removal";
11
15
  import { collectStudioInventory, type StudioInventory } from "./inventory";
12
16
  import {
13
17
  assembleCompanionPayload,
@@ -53,7 +57,6 @@ import {
53
57
  resolveCompanion,
54
58
  type StudioModePolicy,
55
59
  type StudioProfile,
56
- type StudioSelection,
57
60
  } from "./selection";
58
61
  import { errorMessage } from "../../../runtime/error-message";
59
62
  import { createStudioSnapshotCache, type StudioSnapshotCache } from "./snapshot";
@@ -478,15 +481,9 @@ export function createStudioFetch(
478
481
  });
479
482
  };
480
483
 
481
- /** One document's model, with the factory, report and terminal state its address needs. */
484
+ /** One document's model, with the factory and terminal state its address needs. */
482
485
  const collectPage = async (url: URL): Promise<StudioPage> => {
483
- const page = await collectStudioPage(url, policy, inventory, snapshots, vault, writable);
484
- if (page.payload && page.companion && isAnalystOverview(page.selection)) {
485
- page.reports = await reports.list(companionDigest(page.companion.path)).then(
486
- (listed) => listed.map(({ id, title, createdAt }) => ({ id, title, createdAt })),
487
- () => null,
488
- );
489
- }
486
+ const page = await collectStudioPage(url, policy, inventory, snapshots, writable);
490
487
  page.renderedAt = Date.now();
491
488
  page.factoryRuns = page.companion ? await outcomesFor(page.companion.path).runs() : null;
492
489
  if (terminal) {
@@ -555,10 +552,43 @@ export function createStudioFetch(
555
552
  const { vaultMatches } = await import("./views/vault/view");
556
553
  return vaultMatches(vault, await companionPathOf(digest), query);
557
554
  },
555
+ vaultPreview: async (digest, path, content) => {
556
+ await companionPathOf(digest);
557
+ const { markdownTree } = await import("./views/vault/markdown-tree");
558
+ return markdownTree(content, path);
559
+ },
558
560
  vaultSave: async (digest, path, content, token) => {
559
561
  if (!writable) throw new VaultPathError("start Studio with --writable to enable saving");
560
562
  return vault.save(await companionPathOf(digest), path, content, token);
561
563
  },
564
+ reports: async (digest) => {
565
+ await companionPathOf(digest);
566
+ return reports.list(digest);
567
+ },
568
+ skillPreview: async (digest, agent, name, file) => {
569
+ const { readSkillPreview } = await import("./skill-files");
570
+ return readSkillPreview(await companionPathOf(digest), agent, name, file);
571
+ },
572
+ deleteCompanion: async (digest) => {
573
+ if (!writable) {
574
+ throw new CompanionRemovalError("start Studio with --writable to delete companions");
575
+ }
576
+ const companionPath = await companionPathOf(digest);
577
+ const pinned = [launchCompanion, outcomes?.companionPath].filter(
578
+ (entry): entry is string => typeof entry === "string" && entry !== "",
579
+ );
580
+ // Real paths, so a symlinked start path still protects its folder.
581
+ const real = (entry: string) => realpath(entry).catch(() => path.resolve(entry));
582
+ const target = await real(companionPath);
583
+ const pinnedReal = await Promise.all(pinned.map(real));
584
+ if (pinnedReal.includes(target)) {
585
+ throw new CompanionRemovalError(
586
+ "Studio was started for this companion; it is not deleted.",
587
+ );
588
+ }
589
+ const { deletedFolder } = await deleteRegisteredCompanion(companionPath);
590
+ return { deletedFolder };
591
+ },
562
592
  };
563
593
  const app = options.app ?? null;
564
594
 
@@ -842,11 +872,6 @@ function vaultEvents(vault: VaultManager, companionPath: string, requestedPath:
842
872
  );
843
873
  }
844
874
 
845
- /** Reports are not part of the snapshot: this Overview lists them at render time. */
846
- function isAnalystOverview(selection: StudioSelection): boolean {
847
- return selection.studioMode === "analysis" && selection.view === "dashboard";
848
- }
849
-
850
875
  /**
851
876
  * One rendered document's worth of state. An absent or unresolvable companion
852
877
  * is not a failure: the page renders the selector and the server keeps serving.
@@ -856,7 +881,6 @@ async function collectStudioPage(
856
881
  policy: StudioModePolicy,
857
882
  collectInventory: () => Promise<StudioInventory>,
858
883
  snapshots: StudioSnapshotCache,
859
- vault: VaultManager,
860
884
  writable: boolean,
861
885
  ): Promise<StudioPage> {
862
886
  const selection = parse(url, policy);
@@ -874,7 +898,6 @@ async function collectStudioPage(
874
898
  terminal: null,
875
899
  };
876
900
 
877
- vault.deactivate();
878
901
  if (!companion) return page;
879
902
 
880
903
  try {
@@ -1,7 +1,10 @@
1
1
  import type { OutcomeAction } from "../../../lib/factory/outcomes/actions";
2
+ import type { StoredReport } from "./reports";
3
+ import type { SkillAgent, SkillPreview } from "./skill-files";
2
4
  import type { StudioModePolicy } from "./selection";
3
5
  import type { VaultConflict, VaultSaved } from "./vault";
4
6
  import type { StudioPage } from "./views/model";
7
+ import type { MdNode } from "./views/vault/markdown-tree";
5
8
  import type { VaultEntry, VaultView, VaultViewRequest } from "./views/vault/view";
6
9
 
7
10
  /** The fields of a submitted factory form; an absent field reads as an empty string. */
@@ -45,6 +48,8 @@ export interface StudioServices {
45
48
  companionDigest: string,
46
49
  query: string,
47
50
  ): Promise<{ shown: VaultEntry[]; total: number; generation: number }>;
51
+ /** Unsaved editor text rendered as the file at `path` would be; reads and writes nothing. */
52
+ vaultPreview(companionDigest: string, path: string, content: string): Promise<MdNode[]>;
48
53
  /** Saves (or, without a token, creates) a markdown file; a stale token is a conflict, not an error. */
49
54
  vaultSave(
50
55
  companionDigest: string,
@@ -52,6 +57,21 @@ export interface StudioServices {
52
57
  content: string,
53
58
  token?: string,
54
59
  ): Promise<VaultSaved | VaultConflict>;
60
+ /** A registered companion's published reports, newest first; no paths or content. */
61
+ reports(companionDigest: string): Promise<StoredReport[]>;
62
+ /** One installed skill's files and one of them rendered (SKILL.md by default); read-only. */
63
+ skillPreview(
64
+ companionDigest: string,
65
+ agent: SkillAgent,
66
+ name: string,
67
+ file?: string,
68
+ ): Promise<SkillPreview>;
69
+ /**
70
+ * Deletes a registered companion's folder and unregisters it, or only unregisters a stale
71
+ * one whose folder is gone; not recoverable. Needs `writable`, and refuses the companion
72
+ * Studio was started for.
73
+ */
74
+ deleteCompanion(companionDigest: string): Promise<{ deletedFolder: boolean }>;
55
75
  }
56
76
 
57
77
  /** The request context Studio's application receives from core on every request. */
@@ -0,0 +1,133 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ import { SKILL_DIRS, type StudioSkillInventory } from "./mate-inventory";
5
+ import { codeTree, markdownTree, type MdNode } from "./views/vault/markdown-tree";
6
+
7
+ export type SkillAgent = keyof StudioSkillInventory;
8
+
9
+ export interface SkillFileEntry {
10
+ /** Relative to the skill's folder, `/`-separated. */
11
+ path: string;
12
+ size: number;
13
+ }
14
+
15
+ export interface SkillPreview {
16
+ files: SkillFileEntry[];
17
+ /** More files than listed were found. */
18
+ truncated: boolean;
19
+ /** The file shown: SKILL.md unless another was asked for; `null` when the folder is empty. */
20
+ open: { path: string; nodes: MdNode[] | null; note: string | null } | null;
21
+ }
22
+
23
+ export interface SkillPreviewFs {
24
+ readdir: (dir: string) => Promise<{ name: string; isDirectory(): boolean; isFile(): boolean }[]>;
25
+ realpath: (target: string) => Promise<string>;
26
+ stat: (target: string) => Promise<{ size: number }>;
27
+ readFile: (target: string) => Promise<Buffer>;
28
+ }
29
+
30
+ /** A refusal Studio shows as it is; nothing was read. */
31
+ export class SkillPreviewError extends Error {}
32
+
33
+ const SKILL_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
34
+ const MAX_FILES = 200;
35
+ const MAX_DEPTH = 4;
36
+ const MAX_BYTES = 256 * 1024;
37
+ const SKIPPED = new Set([".git", "node_modules", ".DS_Store"]);
38
+ const MARKDOWN = /\.(md|markdown)$/i;
39
+
40
+ const defaultFs: SkillPreviewFs = {
41
+ readdir: (dir) => fs.readdir(dir, { withFileTypes: true }),
42
+ realpath: (target) => fs.realpath(target),
43
+ stat: (target) => fs.stat(target),
44
+ readFile: (target) => fs.readFile(target),
45
+ };
46
+
47
+ const inside = (root: string, target: string): boolean => {
48
+ const relative = path.relative(root, target);
49
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
50
+ };
51
+
52
+ /** Every file under the skill's folder, bounded, skipping links that leave it. */
53
+ async function listFiles(
54
+ skillFs: SkillPreviewFs,
55
+ root: string,
56
+ ): Promise<{ files: SkillFileEntry[]; truncated: boolean }> {
57
+ const files: SkillFileEntry[] = [];
58
+ let truncated = false;
59
+ const walk = async (dir: string, prefix: string, depth: number): Promise<void> => {
60
+ const entries = await skillFs.readdir(dir).catch(() => []);
61
+ for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
62
+ if (SKIPPED.has(entry.name)) continue;
63
+ if (files.length >= MAX_FILES) {
64
+ truncated = true;
65
+ return;
66
+ }
67
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
68
+ // oxlint-disable-next-line no-await-in-loop -- sorted, bounded walk
69
+ const resolved = await skillFs.realpath(path.join(dir, entry.name)).catch(() => null);
70
+ if (resolved === null || !inside(root, resolved)) continue;
71
+ if (entry.isDirectory()) {
72
+ // oxlint-disable-next-line no-await-in-loop -- sorted, bounded walk
73
+ if (depth < MAX_DEPTH) await walk(resolved, relative, depth + 1);
74
+ } else if (entry.isFile()) {
75
+ // oxlint-disable-next-line no-await-in-loop -- sorted, bounded walk
76
+ const { size } = await skillFs.stat(resolved);
77
+ files.push({ path: relative, size });
78
+ }
79
+ }
80
+ };
81
+ await walk(root, "", 0);
82
+ // SKILL.md first: it is what the agent reads.
83
+ files.sort((a, b) => Number(b.path === "SKILL.md") - Number(a.path === "SKILL.md"));
84
+ return { files, truncated };
85
+ }
86
+
87
+ async function render(
88
+ skillFs: SkillPreviewFs,
89
+ root: string,
90
+ file: SkillFileEntry,
91
+ vaultPath: string,
92
+ ): Promise<{ nodes: MdNode[] | null; note: string | null }> {
93
+ if (file.size > MAX_BYTES) return { nodes: null, note: "Too large to preview." };
94
+ const bytes = await skillFs.readFile(path.join(root, ...file.path.split("/")));
95
+ if (bytes.includes(0)) return { nodes: null, note: "A binary file; not previewed." };
96
+ const text = bytes.toString("utf8");
97
+ if (MARKDOWN.test(file.path)) return { nodes: markdownTree(text, vaultPath), note: null };
98
+ const extension = path.extname(file.path).slice(1).toLowerCase() || undefined;
99
+ return { nodes: codeTree(text, extension), note: null };
100
+ }
101
+
102
+ /**
103
+ * One installed skill's files and one of them rendered, read-only. Only a listed file is read,
104
+ * so a request never names a path outside the skill's own folder.
105
+ */
106
+ export async function readSkillPreview(
107
+ companionPath: string,
108
+ agent: SkillAgent,
109
+ name: string,
110
+ file?: string,
111
+ skillFs: SkillPreviewFs = defaultFs,
112
+ ): Promise<SkillPreview> {
113
+ if (!Object.hasOwn(SKILL_DIRS, agent)) throw new SkillPreviewError("unknown agent");
114
+ if (!SKILL_NAME.test(name)) throw new SkillPreviewError("not a skill name");
115
+ const skillsDir = path.join(companionPath, SKILL_DIRS[agent], "skills");
116
+ const root = await skillFs.realpath(path.join(skillsDir, name)).catch(() => null);
117
+ const companionRoot = await skillFs.realpath(companionPath);
118
+ if (root === null || !inside(companionRoot, root)) {
119
+ throw new SkillPreviewError(`${name} is not installed for this agent`);
120
+ }
121
+ const { files, truncated } = await listFiles(skillFs, root);
122
+ const shown = file === undefined ? files[0] : files.find((entry) => entry.path === file);
123
+ if (file !== undefined && shown === undefined) {
124
+ throw new SkillPreviewError(`${file} is not a file of ${name}`);
125
+ }
126
+ if (!shown) return { files, truncated, open: null };
127
+ const vaultPath = `${SKILL_DIRS[agent]}/skills/${name}/${shown.path}`;
128
+ return {
129
+ files,
130
+ truncated,
131
+ open: { path: shown.path, ...(await render(skillFs, root, shown, vaultPath)) },
132
+ };
133
+ }