@uniqbit/mate-core 1.0.0-canary.2 → 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 (189) 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/opencode-plugin/src/tui.tsx +1 -1
  8. package/opencode-plugin/tui.tsx +2 -1
  9. package/package.json +1 -1
  10. package/src/cli/commands/artifact/delivery/archive.ts +2 -2
  11. package/src/cli/commands/artifact/delivery/link.ts +22 -5
  12. package/src/cli/commands/artifact/delivery/output.ts +9 -1
  13. package/src/cli/commands/artifact/finish/openspec.ts +1 -3
  14. package/src/cli/commands/companion/companion.ts +1 -1
  15. package/src/cli/commands/companion/link.ts +36 -4
  16. package/src/cli/commands/companion/open.ts +40 -12
  17. package/src/cli/commands/doctor.ts +122 -0
  18. package/src/cli/commands/session/prepare.ts +32 -4
  19. package/src/cli/commands/session/registry.ts +90 -0
  20. package/src/cli/commands/studio/companion-removal.ts +79 -0
  21. package/src/cli/commands/studio/mate-inventory.ts +1 -1
  22. package/src/cli/commands/studio/payload.ts +12 -1
  23. package/src/cli/commands/studio/server.ts +39 -16
  24. package/src/cli/commands/studio/services.ts +20 -0
  25. package/src/cli/commands/studio/skill-files.ts +133 -0
  26. package/src/cli/commands/studio/vault.ts +218 -44
  27. package/src/cli/commands/studio/views/model.ts +0 -5
  28. package/src/cli/commands/studio/views/vault/markdown-tree.ts +255 -4
  29. package/src/cli/commands/unwrap.ts +8 -0
  30. package/src/cli/commands/update.ts +26 -8
  31. package/src/cli/commands/vscode/setup.ts +155 -0
  32. package/src/cli/commands/vscode/vsix.ts +73 -0
  33. package/src/cli/commands/working/cleanup.ts +34 -10
  34. package/src/cli/commands/working/worktree.ts +58 -8
  35. package/src/cli/commands/wrap.ts +33 -7
  36. package/src/cli/main.ts +9 -2
  37. package/src/cli/usage.ts +6 -1
  38. package/src/hooks/companion-instructions.ts +19 -11
  39. package/src/hooks/hook-io.ts +15 -0
  40. package/src/hooks/session-banner.ts +5 -3
  41. package/src/hooks/session-end.ts +10 -0
  42. package/src/hooks/session-guidance.ts +10 -6
  43. package/src/hooks/session-prepare.ts +47 -31
  44. package/src/hooks/session-register.ts +199 -0
  45. package/src/hooks/tokensave-route.ts +7 -3
  46. package/src/hooks/validate-artifact-path.ts +9 -2
  47. package/src/lib/delivery/archive-change.ts +0 -1
  48. package/src/lib/delivery/branches.ts +15 -0
  49. package/src/lib/delivery/record-delivery.ts +94 -39
  50. package/src/lib/delivery/record.ts +30 -28
  51. package/src/lib/delivery/refresh.ts +37 -17
  52. package/src/lib/delivery/resolve-branch.ts +258 -37
  53. package/src/lib/factory/outcomes/index.ts +11 -1
  54. package/src/lib/factory/runtime.ts +10 -1
  55. package/src/lib/opencode-server.ts +238 -0
  56. package/src/lib/orchestrator/adapters/claude.ts +147 -2
  57. package/src/lib/orchestrator/adapters/opencode.ts +53 -2
  58. package/src/lib/orchestrator/checkout-adoption.ts +125 -0
  59. package/src/lib/orchestrator/companion-registry-store.ts +6 -2
  60. package/src/lib/orchestrator/editor.ts +2 -2
  61. package/src/lib/orchestrator/framework-context.ts +26 -14
  62. package/src/lib/orchestrator/global-config-store.ts +11 -0
  63. package/src/lib/orchestrator/launcher.ts +15 -2
  64. package/src/lib/orchestrator/projection-claude-links.ts +52 -5
  65. package/src/lib/orchestrator/projection-claude-skills.ts +28 -2
  66. package/src/lib/orchestrator/projection-companion-link.ts +12 -1
  67. package/src/lib/orchestrator/registry-checkouts.ts +177 -0
  68. package/src/lib/orchestrator/repository-link.ts +216 -57
  69. package/src/lib/orchestrator/serving-claude-wrap.ts +43 -0
  70. package/src/lib/orchestrator/session-context-link.ts +11 -5
  71. package/src/lib/orchestrator/session-prepare.ts +36 -6
  72. package/src/lib/orchestrator/types.ts +5 -0
  73. package/src/lib/orchestrator/workspace-inventory.ts +5 -1
  74. package/src/lib/public-npm.ts +17 -0
  75. package/src/lib/session-attribution.ts +52 -0
  76. package/src/lib/session-state.ts +285 -0
  77. package/src/lib/session-stop.ts +64 -0
  78. package/src/lib/workset/record.ts +20 -0
  79. package/src/lib/workset/worktree.ts +85 -17
  80. package/src/opencode/background-server.ts +145 -0
  81. package/src/opencode/companion-hooks.ts +3 -1
  82. package/src/opencode/companion-policy.ts +2 -2
  83. package/src/opencode/projected-guidance.ts +2 -1
  84. package/src/opencode/session-register.ts +176 -0
  85. package/src/opencode/tui.tsx +19 -29
  86. package/src/runtime/claude-delivery-plan.ts +14 -3
  87. package/src/runtime/current-branch.ts +10 -0
  88. package/src/runtime/env.ts +13 -7
  89. package/src/runtime/git-layout.ts +164 -17
  90. package/src/runtime/launch-env-guard.ts +65 -0
  91. package/src/runtime/opencode-server-record.ts +136 -0
  92. package/src/runtime/projection.ts +40 -6
  93. package/src/runtime/repo-local.ts +6 -1
  94. package/src/runtime/serving-claude-wrap.ts +28 -0
  95. package/src/runtime/session-context.ts +4 -3
  96. package/src/runtime/session-registry.ts +434 -0
  97. package/src/runtime/tokensave-route.ts +10 -5
  98. package/src/runtime/wrap-state.ts +31 -0
  99. package/src/studio.ts +2 -0
  100. package/src/templates/mate-skills/agents/mate-apply-change/SKILL.md +49 -21
  101. package/src/templates/mate-skills/agents/mate-archive-change/SKILL.md +0 -5
  102. package/src/templates/mate-skills/agents/mate-propose-change/SKILL.md +2 -8
  103. package/src/templates/mate-skills/agents/mate-propose-change/references/mate-revise.md +1 -3
  104. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +2 -4
  105. package/src/templates/mate-skills/claude/mate-apply-change/SKILL.md +49 -21
  106. package/src/templates/mate-skills/claude/mate-archive-change/SKILL.md +0 -5
  107. package/src/templates/mate-skills/claude/mate-propose-change/SKILL.md +2 -8
  108. package/src/templates/mate-skills/claude/mate-propose-change/references/mate-revise.md +1 -3
  109. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +2 -4
  110. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +404 -30
  111. package/src/tools/setup/dynamic-plugins/hydrate.ts +4 -3
  112. package/src/tools/setup/providers/claude-plugin-hooks.ts +26 -0
  113. package/src/tools/setup/providers/claude.ts +21 -1
  114. package/studio-dist/client/assets/app-CdPiFv59.css +2 -0
  115. package/studio-dist/client/assets/button-BIIHE0EQ.js +3 -0
  116. package/studio-dist/client/assets/companion-view-DM6YyXaR.js +1 -0
  117. package/studio-dist/client/assets/delivery-path-DELxj0Av.js +1 -0
  118. package/studio-dist/client/assets/factory-BZy0E8ty.js +4 -0
  119. package/studio-dist/client/assets/index-B3wkMzjA.js +40 -0
  120. package/studio-dist/client/assets/markdown-view-pQ2Qp_i5.js +1 -0
  121. package/studio-dist/client/assets/panel-CbajlC3p.js +1 -0
  122. package/studio-dist/client/assets/{prepaint-CD5OpmTM.js → prepaint-CwSrpdFA.js} +7 -4
  123. package/studio-dist/client/assets/react-CN2GSx7x.js +1 -0
  124. package/studio-dist/client/assets/reports-DllhYQ5_.js +1 -0
  125. package/studio-dist/client/assets/routes-COm-G3mK.js +1 -0
  126. package/studio-dist/client/assets/skills-DmWAy-jZ.js +1 -0
  127. package/studio-dist/client/assets/specs-BG3Wi3ln.js +1 -0
  128. package/studio-dist/client/assets/steps-DFsH3Neu.js +1 -0
  129. package/studio-dist/client/assets/vault-B2q1nBY5.js +1 -0
  130. package/studio-dist/client/assets/warnings-BSXIyuSQ.js +1 -0
  131. package/studio-dist/client/assets/workflow-DlsQD6Hc.js +1 -0
  132. package/studio-dist/server/assets/{__23tanstack-start-server-fn-resolver-BQKuMdJW.js → __23tanstack-start-server-fn-resolver-M2GBs8s3.js} +179 -9
  133. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +35 -25
  134. package/studio-dist/server/assets/button-CIJqAhni.js +11929 -0
  135. package/studio-dist/server/assets/{companion-view-aBady57v.js → companion-view-DISASvdJ.js} +13 -7
  136. package/studio-dist/server/assets/companions-BYbHWKOZ.js +15 -0
  137. package/studio-dist/server/assets/delivery-path-C29fBynY.js +654 -0
  138. package/studio-dist/server/assets/{factory-DT3UzHlh.js → factory-DGPmNGbo.js} +1 -0
  139. package/studio-dist/server/assets/{factory-D6xnjedJ.js → factory-DUTa0eDs.js} +317 -530
  140. package/studio-dist/server/assets/markdown-view-Bn7xPdks.js +86 -0
  141. package/studio-dist/server/assets/panel-3Jmn4awF.js +169 -0
  142. package/studio-dist/server/assets/{prepaint-BMke0fo1.js → prepaint-DJfTQ_VH.js} +6 -2
  143. package/studio-dist/server/assets/{react-COs0LHn-.js → react-Ce6dj15C.js} +4 -9
  144. package/studio-dist/server/assets/reports-C06RXVE2.js +18 -0
  145. package/studio-dist/server/assets/reports-D6YMqhnO.js +142 -0
  146. package/studio-dist/server/assets/router-C8MGqlAY.js +13713 -0
  147. package/studio-dist/server/assets/routes-BcFgvqf7.js +622 -0
  148. package/studio-dist/server/assets/{shell-CboT2f66.js → shell-DS3wUexh.js} +1 -0
  149. package/studio-dist/server/assets/skills-BEnOxiDl.js +266 -0
  150. package/studio-dist/server/assets/skills-CtrBAtX3.js +28 -0
  151. package/studio-dist/server/assets/specs-C8rv34-5.js +211 -0
  152. package/studio-dist/server/assets/{start-BW5ovN0k.js → start-h3ICWwd2.js} +4 -1
  153. package/studio-dist/server/assets/steps-Dq_CwY_s.js +181 -0
  154. package/studio-dist/server/assets/{vault-BGulVoNh.js → vault-BmWnryh3.js} +16 -1
  155. package/studio-dist/server/assets/vault-Fvxt2Tzl.js +1032 -0
  156. package/studio-dist/server/assets/{views-Bd7cRr27.js → views-BgYa-za2.js} +1 -3
  157. package/studio-dist/server/assets/warnings-DzR6fyZh.js +23 -0
  158. package/studio-dist/server/assets/workflow-liRYecHk.js +73 -0
  159. package/studio-dist/server/server.js +3 -157
  160. package/studio-dist/client/assets/companion-view-Csva26Ir.js +0 -1
  161. package/studio-dist/client/assets/delivery-path-DJMpRmiY.js +0 -1
  162. package/studio-dist/client/assets/factory-B7l9ZQyx.js +0 -4
  163. package/studio-dist/client/assets/index-n6uo_92S.js +0 -40
  164. package/studio-dist/client/assets/queries-CN3JwMBX.js +0 -1
  165. package/studio-dist/client/assets/react-CabXf2Ds.js +0 -1
  166. package/studio-dist/client/assets/report-time-Dc-KOqQu.js +0 -1
  167. package/studio-dist/client/assets/reports-C01RsnMA.js +0 -1
  168. package/studio-dist/client/assets/routes-4pbC-2Hj.js +0 -1
  169. package/studio-dist/client/assets/skills-CihQganl.js +0 -1
  170. package/studio-dist/client/assets/spec-areas-C2L48N4C.js +0 -1
  171. package/studio-dist/client/assets/specs-D24_35_K.js +0 -1
  172. package/studio-dist/client/assets/studio-DKxfi691.css +0 -1
  173. package/studio-dist/client/assets/studio-queries-rvbJupCy.js +0 -3
  174. package/studio-dist/client/assets/vault-Bd4CQiTK.js +0 -1
  175. package/studio-dist/client/assets/warnings-V_Ys51wJ.js +0 -1
  176. package/studio-dist/client/assets/workflow-BJejeVwQ.js +0 -1
  177. package/studio-dist/server/assets/delivery-path-BkKNjgkf.js +0 -778
  178. package/studio-dist/server/assets/queries-Ag2iL8q2.js +0 -107
  179. package/studio-dist/server/assets/report-time-DAfzln-N.js +0 -8
  180. package/studio-dist/server/assets/reports-BnUNJVtx.js +0 -126
  181. package/studio-dist/server/assets/router-BH--drIx.js +0 -4298
  182. package/studio-dist/server/assets/routes-khSDK1bV.js +0 -361
  183. package/studio-dist/server/assets/skills-MWYnWoKs.js +0 -106
  184. package/studio-dist/server/assets/spec-areas-DcnO6vW-.js +0 -16
  185. package/studio-dist/server/assets/specs-DE3w8hZP.js +0 -155
  186. package/studio-dist/server/assets/studio-queries-CLnP9kGu.js +0 -3365
  187. package/studio-dist/server/assets/vault-CuyyhLyB.js +0 -832
  188. package/studio-dist/server/assets/warnings-BH05rOuG.js +0 -15
  189. package/studio-dist/server/assets/workflow-BSuIKWqH.js +0 -42
@@ -0,0 +1,434 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ import { mateHome } from "./runtime-directory";
6
+ import { writeAtomic } from "./write-atomic";
7
+
8
+ /**
9
+ * Machine-local list of the agent sessions an editor plugin started, so it can
10
+ * list, resume, and remove them through one CLI contract. Mate's runtime hooks
11
+ * keep those entries current; they add a session only when its launch carries
12
+ * `MATE_SESSION_ORIGIN=editor`, and write nothing for any other session.
13
+ */
14
+
15
+ /** Set by an editor plugin on the launches it starts; the runtime hooks register only those. */
16
+ export const SESSION_ORIGIN_ENV = "MATE_SESSION_ORIGIN";
17
+
18
+ export function startedByEditor(env: Record<string, string | undefined>): boolean {
19
+ return env[SESSION_ORIGIN_ENV] === "editor";
20
+ }
21
+
22
+ const SESSION_RUNTIMES = ["claude", "opencode"] as const;
23
+ export type SessionRuntime = (typeof SESSION_RUNTIMES)[number];
24
+
25
+ const SESSION_ORIGINS = ["editor", "managed", "unmanaged"] as const;
26
+ /** Who started the session: an editor plugin, a Mate launch, or the runtime on its own. */
27
+ export type SessionOrigin = (typeof SESSION_ORIGINS)[number];
28
+
29
+ const SESSION_ACTIVITIES = ["working", "idle", "waiting"] as const;
30
+ export type SessionActivity = (typeof SESSION_ACTIVITIES)[number];
31
+
32
+ export interface RegisteredSession {
33
+ id: string;
34
+ runtime: SessionRuntime;
35
+ origin: SessionOrigin;
36
+ /** Absolute directory the session runs in. */
37
+ cwd: string;
38
+ /** ISO timestamps. */
39
+ startedAt: string;
40
+ lastSeenAt: string;
41
+ endedAt?: string;
42
+ pid?: number;
43
+ branch?: string;
44
+ /** Absolute path of the runtime's transcript, for the label. */
45
+ transcript?: string;
46
+ /** First user prompt, or the runtime's own title. */
47
+ label?: string;
48
+ /** Change the session works on, recorded by commands run inside it. */
49
+ change?: string;
50
+ /** When the runtime last asked the user for input. */
51
+ attentionAt?: string;
52
+ /** Stored by runtimes that report it themselves (OpenCode); meaningful while running. */
53
+ activity?: SessionActivity;
54
+ }
55
+
56
+ export interface SessionRegistryFile {
57
+ version: 2;
58
+ sessions: RegisteredSession[];
59
+ }
60
+
61
+ export class SessionRegistryError extends Error {}
62
+
63
+ export function sessionRegistryPath(homeDir?: string): string {
64
+ return path.join(mateHome(homeDir), "sessions.json");
65
+ }
66
+
67
+ function isSessionRuntime(value: string): value is SessionRuntime {
68
+ return (SESSION_RUNTIMES as readonly string[]).includes(value);
69
+ }
70
+
71
+ function isSessionOrigin(value: string): value is SessionOrigin {
72
+ return (SESSION_ORIGINS as readonly string[]).includes(value);
73
+ }
74
+
75
+ const OPTIONAL_STRINGS = [
76
+ "endedAt",
77
+ "branch",
78
+ "transcript",
79
+ "label",
80
+ "change",
81
+ "attentionAt",
82
+ ] as const;
83
+
84
+ function isRecord(value: unknown): value is Record<string, unknown> {
85
+ return !!value && typeof value === "object" && !Array.isArray(value);
86
+ }
87
+
88
+ function isV1Session(entry: Record<string, unknown>): boolean {
89
+ return (
90
+ typeof entry.id === "string" &&
91
+ typeof entry.runtime === "string" &&
92
+ isSessionRuntime(entry.runtime) &&
93
+ typeof entry.cwd === "string" &&
94
+ typeof entry.startedAt === "string"
95
+ );
96
+ }
97
+
98
+ function isV2Session(entry: Record<string, unknown>): boolean {
99
+ return (
100
+ isV1Session(entry) &&
101
+ typeof entry.origin === "string" &&
102
+ isSessionOrigin(entry.origin) &&
103
+ typeof entry.lastSeenAt === "string" &&
104
+ (entry.pid === undefined || typeof entry.pid === "number") &&
105
+ OPTIONAL_STRINGS.every((key) => entry[key] === undefined || typeof entry[key] === "string") &&
106
+ (entry.activity === undefined ||
107
+ (SESSION_ACTIVITIES as readonly unknown[]).includes(entry.activity))
108
+ );
109
+ }
110
+
111
+ /** Version 1 entries were all started from an editor plugin. */
112
+ function fromV1(entry: Record<string, unknown>): RegisteredSession {
113
+ const startedAt = entry.startedAt as string;
114
+ return {
115
+ id: entry.id as string,
116
+ runtime: entry.runtime as SessionRuntime,
117
+ origin: "editor",
118
+ cwd: entry.cwd as string,
119
+ startedAt,
120
+ lastSeenAt: startedAt,
121
+ };
122
+ }
123
+
124
+ /** Missing file reads as empty; anything unparseable is refused so it is never overwritten. */
125
+ export async function readSessionRegistry(
126
+ file = sessionRegistryPath(),
127
+ ): Promise<SessionRegistryFile> {
128
+ let text: string;
129
+ try {
130
+ text = await fs.readFile(file, "utf8");
131
+ } catch (error) {
132
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { version: 2, sessions: [] };
133
+ throw error;
134
+ }
135
+ let parsed: unknown;
136
+ try {
137
+ parsed = JSON.parse(text);
138
+ } catch {
139
+ throw new SessionRegistryError(`${file} is not valid JSON`);
140
+ }
141
+ const invalid = new SessionRegistryError(`${file} is not a version 1 or 2 session registry`);
142
+ if (!isRecord(parsed) || !Array.isArray(parsed.sessions)) throw invalid;
143
+ const entries = parsed.sessions as unknown[];
144
+ if (!entries.every(isRecord)) throw invalid;
145
+ if (parsed.version === 1 && entries.every(isV1Session)) {
146
+ return { version: 2, sessions: entries.map(fromV1) };
147
+ }
148
+ if (parsed.version === 2 && entries.every(isV2Session)) {
149
+ return { version: 2, sessions: entries as unknown as RegisteredSession[] };
150
+ }
151
+ throw invalid;
152
+ }
153
+
154
+ async function writeSessionRegistry(file: string, registry: SessionRegistryFile): Promise<void> {
155
+ await fs.mkdir(path.dirname(file), { recursive: true });
156
+ await writeAtomic(file, `${JSON.stringify(registry, null, 2)}\n`);
157
+ }
158
+
159
+ const LOCK_WAIT_MS = 2000;
160
+ const LOCK_STALE_MS = 10_000;
161
+ const LOCK_RETRY_MS = 25;
162
+
163
+ export interface LockOptions {
164
+ waitMs?: number;
165
+ staleMs?: number;
166
+ now?: () => number;
167
+ }
168
+
169
+ const readOwner = (file: string) => fs.readFile(file, "utf8").catch(() => null);
170
+
171
+ /**
172
+ * Takes over a stale lock by moving it aside first: of several writers that
173
+ * found it stale, only one move succeeds. A lock that turns out to be another
174
+ * writer's fresh one is put back.
175
+ */
176
+ async function takeOverStale(lock: string, owner: string, token: string): Promise<void> {
177
+ const aside = `${lock}.${token}`;
178
+ try {
179
+ await fs.rename(lock, aside);
180
+ } catch {
181
+ return;
182
+ }
183
+ if ((await readOwner(aside)) !== owner) await fs.link(aside, lock).catch(() => {});
184
+ await fs.rm(aside, { force: true });
185
+ }
186
+
187
+ /**
188
+ * Exclusive `<file>.lock` around a read-modify-write. Waits up to 2 s and takes
189
+ * over a lock untouched for 10 s (a crashed writer); the holder touches it while
190
+ * it works, so a slow writer is never taken over. Throws when it cannot get it.
191
+ */
192
+ export async function withLock<T>(file: string, fn: () => Promise<T>, options: LockOptions = {}) {
193
+ const lock = `${file}.lock`;
194
+ const now = options.now ?? Date.now;
195
+ const staleMs = options.staleMs ?? LOCK_STALE_MS;
196
+ const deadline = now() + (options.waitMs ?? LOCK_WAIT_MS);
197
+ const token = `${process.pid}.${crypto.randomUUID()}`;
198
+ await fs.mkdir(path.dirname(file), { recursive: true });
199
+ // oxlint-disable no-await-in-loop -- retry loop
200
+ for (;;) {
201
+ try {
202
+ const handle = await fs.open(lock, "wx");
203
+ try {
204
+ await handle.writeFile(token);
205
+ } finally {
206
+ await handle.close();
207
+ }
208
+ break;
209
+ } catch (error) {
210
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
211
+ const owner = await readOwner(lock);
212
+ const stat = await fs.stat(lock).catch(() => null);
213
+ if (owner !== null && stat && now() - stat.mtimeMs > staleMs) {
214
+ await takeOverStale(lock, owner, token);
215
+ continue;
216
+ }
217
+ if (now() >= deadline) {
218
+ throw new SessionRegistryError(`${file} is locked by another writer (${lock})`);
219
+ }
220
+ await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
221
+ }
222
+ }
223
+ // oxlint-enable no-await-in-loop
224
+ const touch = setInterval(() => {
225
+ const at = new Date();
226
+ void fs.utimes(lock, at, at).catch(() => {});
227
+ }, staleMs / 3);
228
+ touch.unref();
229
+ try {
230
+ return await fn();
231
+ } finally {
232
+ clearInterval(touch);
233
+ if ((await readOwner(lock)) === token) await fs.rm(lock, { force: true });
234
+ }
235
+ }
236
+
237
+ export interface WriteOptions {
238
+ file?: string;
239
+ now?: () => Date;
240
+ lock?: LockOptions;
241
+ }
242
+
243
+ /** Read, change, and write the registry under the lock; `change` returns the value to hand back. */
244
+ export async function updateSessionRegistry<T>(
245
+ change: (registry: SessionRegistryFile) => T | Promise<T>,
246
+ options: WriteOptions = {},
247
+ ): Promise<T> {
248
+ const file = options.file ?? sessionRegistryPath();
249
+ return withLock(
250
+ file,
251
+ async () => {
252
+ const registry = await readSessionRegistry(file);
253
+ const before = JSON.stringify(registry);
254
+ const result = await change(registry);
255
+ if (JSON.stringify(registry) !== before) await writeSessionRegistry(file, registry);
256
+ return result;
257
+ },
258
+ options.lock,
259
+ );
260
+ }
261
+
262
+ /** Lock-free first look, so a write for a session nobody registered costs one read. */
263
+ export async function isRegistered(id: string, options: WriteOptions): Promise<boolean> {
264
+ const registry = await readSessionRegistry(options.file ?? sessionRegistryPath());
265
+ return registry.sessions.some((entry) => entry.id === id);
266
+ }
267
+
268
+ /** Lock-free: true when the session is registered and marked ended. */
269
+ export async function isEnded(id: string, options: WriteOptions): Promise<boolean> {
270
+ const registry = await readSessionRegistry(options.file ?? sessionRegistryPath());
271
+ return !!registry.sessions.find((entry) => entry.id === id)?.endedAt;
272
+ }
273
+
274
+ /** Newest `lastSeenAt` first. */
275
+ export function sortSessions(sessions: RegisteredSession[]): RegisteredSession[] {
276
+ return sessions.toSorted((a, b) => b.lastSeenAt.localeCompare(a.lastSeenAt));
277
+ }
278
+
279
+ /** The raw registry, newest first; state and pruning live in `session-state`. */
280
+ export async function listSessions(file = sessionRegistryPath()): Promise<SessionRegistryFile> {
281
+ const registry = await readSessionRegistry(file);
282
+ return { version: 2, sessions: sortSessions(registry.sessions) };
283
+ }
284
+
285
+ export interface SessionInput {
286
+ id: string;
287
+ runtime: string;
288
+ cwd: string;
289
+ origin?: string;
290
+ pid?: number;
291
+ branch?: string;
292
+ transcript?: string;
293
+ label?: string;
294
+ }
295
+
296
+ const PRUNE_ON_ADD_MS = 30 * 24 * 60 * 60 * 1000;
297
+
298
+ /** Ended, or its directory gone, and not seen for 30 days. */
299
+ async function outdated(session: RegisteredSession, now: Date): Promise<boolean> {
300
+ if (now.getTime() - Date.parse(session.lastSeenAt) <= PRUNE_ON_ADD_MS) return false;
301
+ if (session.endedAt) return true;
302
+ return !(await fs.stat(session.cwd).catch(() => null))?.isDirectory();
303
+ }
304
+
305
+ /**
306
+ * Registers a session, or refreshes a registered one: new `cwd`, `lastSeenAt`,
307
+ * and the runtime facts given; `endedAt` cleared; `startedAt`, `origin`,
308
+ * `label`, `change`, and `attentionAt` kept. A new entry drops the sessions
309
+ * that ended, or whose directory is gone, over 30 days ago.
310
+ */
311
+ export function addSession(
312
+ input: SessionInput,
313
+ options: WriteOptions = {},
314
+ ): Promise<RegisteredSession> {
315
+ return upsertSession(input, options, true) as Promise<RegisteredSession>;
316
+ }
317
+
318
+ /** Refreshes a registered session as `addSession` does; null, and no write, when it is not registered. */
319
+ export async function refreshSession(
320
+ input: SessionInput,
321
+ options: WriteOptions = {},
322
+ ): Promise<RegisteredSession | null> {
323
+ if (!(await isRegistered(input.id, options))) return null;
324
+ return upsertSession(input, options, false);
325
+ }
326
+
327
+ async function upsertSession(
328
+ input: SessionInput,
329
+ options: WriteOptions,
330
+ create: boolean,
331
+ ): Promise<RegisteredSession | null> {
332
+ if (!isSessionRuntime(input.runtime)) {
333
+ throw new SessionRegistryError(
334
+ `unknown runtime: ${input.runtime} (expected ${SESSION_RUNTIMES.join(" or ")})`,
335
+ );
336
+ }
337
+ const origin = input.origin ?? "editor";
338
+ if (!isSessionOrigin(origin)) {
339
+ throw new SessionRegistryError(
340
+ `unknown origin: ${origin} (expected ${SESSION_ORIGINS.join(", ")})`,
341
+ );
342
+ }
343
+ if (!input.id) throw new SessionRegistryError("session id must not be empty");
344
+ const requested = path.resolve(input.cwd);
345
+ const stat = await fs.stat(requested).catch(() => null);
346
+ if (!stat?.isDirectory()) {
347
+ throw new SessionRegistryError(`directory does not exist: ${requested}`);
348
+ }
349
+ // Real path, so callers comparing against Git worktree paths match through symlinks.
350
+ const cwd = await fs.realpath(requested);
351
+ const runtime = input.runtime;
352
+ const now = options.now?.() ?? new Date();
353
+ const seenAt = now.toISOString();
354
+
355
+ return updateSessionRegistry(async (registry) => {
356
+ const existing = registry.sessions.find((entry) => entry.id === input.id);
357
+ const facts = {
358
+ ...(input.pid !== undefined ? { pid: input.pid } : {}),
359
+ ...(input.branch !== undefined ? { branch: input.branch } : {}),
360
+ ...(input.transcript !== undefined ? { transcript: input.transcript } : {}),
361
+ };
362
+ if (existing) {
363
+ const { endedAt: _ended, ...rest } = existing;
364
+ const refreshed: RegisteredSession = {
365
+ ...rest,
366
+ ...facts,
367
+ ...(existing.label === undefined && input.label ? { label: input.label } : {}),
368
+ cwd,
369
+ lastSeenAt: seenAt,
370
+ };
371
+ registry.sessions[registry.sessions.indexOf(existing)] = refreshed;
372
+ return refreshed;
373
+ }
374
+ if (!create) return null;
375
+ const stale = await Promise.all(registry.sessions.map((entry) => outdated(entry, now)));
376
+ registry.sessions = registry.sessions.filter((_, index) => !stale[index]);
377
+ const added: RegisteredSession = {
378
+ id: input.id,
379
+ runtime,
380
+ origin,
381
+ cwd,
382
+ startedAt: seenAt,
383
+ lastSeenAt: seenAt,
384
+ ...facts,
385
+ ...(input.label ? { label: input.label } : {}),
386
+ };
387
+ registry.sessions.push(added);
388
+ return added;
389
+ }, options);
390
+ }
391
+
392
+ /**
393
+ * Applies `patch` to a registered session; null when the id is not registered.
394
+ * `undefined` values in the patch are ignored.
395
+ */
396
+ export async function patchSession(
397
+ id: string,
398
+ patch: Partial<Omit<RegisteredSession, "id" | "runtime" | "origin" | "startedAt">>,
399
+ options: WriteOptions = {},
400
+ ): Promise<RegisteredSession | null> {
401
+ if (!(await isRegistered(id, options))) return null;
402
+ return updateSessionRegistry((registry) => {
403
+ const index = registry.sessions.findIndex((entry) => entry.id === id);
404
+ if (index < 0) return null;
405
+ const defined = Object.fromEntries(
406
+ Object.entries(patch).filter(([, value]) => value !== undefined),
407
+ );
408
+ const patched = { ...registry.sessions[index]!, ...defined };
409
+ registry.sessions[index] = patched;
410
+ return patched;
411
+ }, options);
412
+ }
413
+
414
+ /** Marks the session ended now; null when the id is not registered. */
415
+ export function endSession(id: string, options: WriteOptions = {}) {
416
+ const at = (options.now?.() ?? new Date()).toISOString();
417
+ return patchSession(id, { endedAt: at, lastSeenAt: at }, options);
418
+ }
419
+
420
+ /** Deletes the record only; the conversation and any process are untouched. */
421
+ export async function removeSession(
422
+ id: string,
423
+ file = sessionRegistryPath(),
424
+ ): Promise<RegisteredSession> {
425
+ return updateSessionRegistry(
426
+ (registry) => {
427
+ const removed = registry.sessions.find((entry) => entry.id === id);
428
+ if (!removed) throw new SessionRegistryError(`session not registered: ${id}`);
429
+ registry.sessions = registry.sessions.filter((entry) => entry !== removed);
430
+ return removed;
431
+ },
432
+ { file },
433
+ );
434
+ }
@@ -6,8 +6,10 @@ import { checkoutRootOf, isSameClone, readGitLayout } from "./git-layout";
6
6
 
7
7
  /**
8
8
  * Routes tokensave tool calls to a linked worktree's own index. The MCP server
9
- * stays bound to the checkout the session started in; a per-call `graph_root`
10
- * is tokensave's own way to query another initialised project, read-only.
9
+ * stays bound to the checkout the session started in, which may itself be a
10
+ * linked worktree; a per-call `graph_root` is tokensave's own way to query
11
+ * another initialised project, read-only. tokensave rejects a `graph_root`
12
+ * naming the served project, so that checkout is never routed.
11
13
  */
12
14
 
13
15
  /** The tokensave store's database, relative to a checkout root. */
@@ -91,6 +93,8 @@ export function isRoutableTokensaveTool(tool: string): boolean {
91
93
  export interface RouteDeps {
92
94
  /** Brings the worktree's index up to date; the default runs `tokensave sync`, throttled. */
93
95
  refresh?: (root: string) => void;
96
+ /** The session's start directory: its checkout is the one the MCP server serves. */
97
+ servedDirectory?: string;
94
98
  }
95
99
 
96
100
  /**
@@ -109,9 +113,9 @@ export function refreshWorktreeIndex(root: string): void {
109
113
 
110
114
  /**
111
115
  * `input` with `graph_root` set to the linked worktree containing `directory`,
112
- * when `tool` takes `graph_root`, that worktree holds a tokensave index and
113
- * `input` names no `graph_root`; the index is refreshed first. Otherwise, and
114
- * on any error, `undefined`: the call passes unchanged.
116
+ * when `tool` takes `graph_root`, `input` names none, the worktree holds a
117
+ * tokensave index and is not the served checkout; the index is refreshed
118
+ * first. Otherwise, and on any error, `undefined`: the call passes unchanged.
115
119
  */
116
120
  export function routeTokensaveInput(
117
121
  tool: string,
@@ -130,6 +134,7 @@ export function routeTokensaveInput(
130
134
  if (!root || readGitLayout(root)?.kind !== "linked") return undefined;
131
135
  if (!fs.statSync(path.join(root, TOKENSAVE_DB), { throwIfNoEntry: false })?.isFile())
132
136
  return undefined;
137
+ if (deps.servedDirectory && checkoutRootOf(deps.servedDirectory) === root) return undefined;
133
138
  try {
134
139
  (deps.refresh ?? refreshWorktreeIndex)(root);
135
140
  } catch {
@@ -106,6 +106,37 @@ export function wrapStateOf(manifest: Manifest): WrapState {
106
106
  };
107
107
  }
108
108
 
109
+ /**
110
+ * A Checkout's own wrap state joined with the Claude wrap that serves it
111
+ * (design Decision 12): Claude Code loads both settings files, so a launch
112
+ * leaves to them every hook group and plugin either carries. Everything else
113
+ * stays the Checkout's own.
114
+ */
115
+ export function joinedClaudeWrapState(own: WrapState, serving: WrapState): WrapState {
116
+ const groups = [
117
+ ...own.carriedClaudeHookGroups,
118
+ ...serving.carriedClaudeHookGroups.filter((group) => !own.carriesClaudeHookGroup(group)),
119
+ ];
120
+ const keys = new Set(groups.map(hookGroupKey));
121
+ const ownPlugins = new Set(own.carriedClaudePlugins.map((plugin) => plugin.id));
122
+ return {
123
+ ...own,
124
+ runtimes: serving.runtimes.has("claude") ? new Set([...own.runtimes, "claude"]) : own.runtimes,
125
+ carriedClaudeHookGroups: groups,
126
+ carriesClaudeHookGroup: (group) => keys.has(hookGroupKey(group)),
127
+ carriedClaudePlugins: [
128
+ ...own.carriedClaudePlugins,
129
+ ...serving.carriedClaudePlugins.filter((plugin) => !ownPlugins.has(plugin.id)),
130
+ ],
131
+ carriedClaudePluginDirectories: [
132
+ ...new Set([
133
+ ...own.carriedClaudePluginDirectories,
134
+ ...serving.carriedClaudePluginDirectories,
135
+ ]),
136
+ ],
137
+ };
138
+ }
139
+
109
140
  /** Where no Projection Root resolves: nothing is wrapped. */
110
141
  export const NOT_WRAPPED: WrapState = wrapStateOf(EMPTY_MANIFEST);
111
142
 
package/src/studio.ts CHANGED
@@ -97,6 +97,8 @@ export type {
97
97
  export type { VaultConflict, VaultSaved } from "./cli/commands/studio/vault";
98
98
  export type { StudioInventory, StudioInventoryCompanion } from "./cli/commands/studio/inventory";
99
99
  export type { StudioSkillInventory } from "./cli/commands/studio/mate-inventory";
100
+ export type { SkillAgent, SkillFileEntry, SkillPreview } from "./cli/commands/studio/skill-files";
101
+ export type { StoredReport } from "./cli/commands/studio/reports";
100
102
  export {
101
103
  findAction,
102
104
  SUBJECT_PATTERN,
@@ -21,9 +21,12 @@ In the Working Repository, read local Git state only:
21
21
 
22
22
  ```bash
23
23
  git symbolic-ref --quiet --short HEAD # current branch; fails when detached
24
- git symbolic-ref --quiet --short refs/remotes/origin/HEAD # default branch
24
+ git symbolic-ref --quiet --short refs/remotes/origin/HEAD # repository's default branch
25
25
  ```
26
26
 
27
+ The repository's default branch (`origin/HEAD`, e.g. `main`) is not the link result's
28
+ `defaultBranch`, which is the change's resolved delivery branch (e.g. `workset/<id>`).
29
+
27
30
  Read the change's existing record without changing it:
28
31
 
29
32
  ```bash
@@ -32,13 +35,16 @@ mate artifact link "<change-name>" --json
32
35
 
33
36
  ## Step 2: Settle the delivery branch
34
37
 
35
- Read `defaultBranch`, `diagnostics`, `ticketFormat`, `ticketCandidate`, and
36
- `record.ticket` from the link result. Report every diagnostic;
38
+ Read `defaultBranch`, `inheritedFrom`, `diagnostics`, `ticketFormat`, and
39
+ `ticketCandidate` from the link result. `defaultBranch` is the change's resolved
40
+ delivery branch, never the repository's default branch. Report every diagnostic;
37
41
  never derive a default from a change or Workset name. `defaultBranch: null` means ask
38
- for a branch name, not infer one. Preserve recorded branches after membership changes;
42
+ for a branch name, not infer one. When `inheritedFrom` is not empty, `defaultBranch` is
43
+ the open branch of those `dependsOn` changes: say this change continues on it.
44
+ Preserve recorded branches after membership changes;
39
45
  a mismatch is informational, and relinking requires explicit user confirmation.
40
46
 
41
- A branch is **protected** when it is the default branch or matches a configured
47
+ A branch is **protected** when it is the repository's default branch or matches a configured
42
48
  protected pattern; `mate artifact link` refuses a
43
49
  protected branch unless it is recorded as a direct delivery. Mate never asks the forge,
44
50
  so a branch only the forge protects looks unprotected; hence the menu below.
@@ -49,17 +55,29 @@ so a branch only the forge protects looks unprotected; hence the menu below.
49
55
  - **On `defaultBranch`** → record it without asking:
50
56
  `mate artifact link "<change-name>" --branch "<defaultBranch>" --json`.
51
57
  - **Detached HEAD** → ask for the branch name, then record it.
58
+ - **On a fresh ticket branch** (only with `ticketFormat` `jira`): nothing is recorded,
59
+ the current branch is not protected, `ticketCandidate` is set, and
60
+ `git rev-list --count origin/HEAD..HEAD` is `0` → record it without asking
61
+ (`mate artifact link "<change-name>" --branch "<current>" --json`) and say in one line
62
+ that the change uses it with ticket `<ticketCandidate>`.
52
63
  - **On any other branch**, protected or not → do not implement there yet. First name
53
64
  every local commit that is not on the remote (`git log --oneline HEAD --not --remotes`)
54
65
  and leave them where they are; never move, reset, or rebase them. On another
55
- Workset's `workset/<id>` branch, name that Workset. Then offer one menu:
56
- 1. **Create or switch to `defaultBranch`** (recommended): check local and `origin`
66
+ Workset's `workset/<id>` branch, name that Workset. Then offer one menu; option 1 is
67
+ recommended, except option 3 when the current branch is not protected and
68
+ `ticketCandidate` is set:
69
+ 1. **Create or switch to `defaultBranch`**: check local and `origin`
57
70
  refs; `git switch "<defaultBranch>"` when local,
58
- `git switch --track -c "<defaultBranch>" "origin/<defaultBranch>"` when remote-only,
59
- otherwise `git switch -c "<defaultBranch>"`. Uncommitted edits carry over. Record it.
60
- When `defaultBranch` is null, ask for a name instead; do not offer an inferred branch.
71
+ `git switch --track -c "<defaultBranch>" "origin/<defaultBranch>"` when remote-only.
72
+ Otherwise the branch is new: record it first with
73
+ `mate artifact link "<change-name>" --ticket "<KEY>" --json` when a ticket was given
74
+ (below), else with `--branch "<defaultBranch>"`, then `git switch -c` the branch its
75
+ record now names. Uncommitted edits carry over. Record an existing branch after
76
+ switching. When `defaultBranch` is null, ask for a name instead; do not offer an
77
+ inferred branch.
61
78
  2. **Create a worktree** (only when `defaultBranch` is set): say uncommitted edits stay
62
- in this checkout, run `mate working worktree --change "<change-name>" --enter --json`;
79
+ in this checkout, run `mate working worktree --change "<change-name>" --enter --json`,
80
+ adding `--ticket "<KEY>"` when a ticket was given (below);
63
81
  it records the branch. When `enter.action` is `tool`, say an approval prompt may
64
82
  follow (Claude Code asks), call the tool `enter.tool` with `enter.path`, then say
65
83
  `enter.path` is now the Working Repository and continue at Step 3 there. On `handoff`
@@ -67,20 +85,28 @@ so a branch only the forge protects looks unprotected; hence the menu below.
67
85
  stop. `## Next steps`: name each `repositories[].path`, open a new session in this
68
86
  repository's worktree, run `/mate-apply-change <change-name>` there. On failure,
69
87
  report its diagnostics and offer the other options again.
70
- 3. **Use the current branch** (only when it is not protected): record it. When
71
- `ticketCandidate` is set, offer it with and without recording that ticket
72
- (`--ticket "<ticketCandidate>"` on the same link call).
73
- 4. **Use another existing branch**: switch to the branch the user names and record it.
88
+ 3. **Use the current branch** (only when it is not protected): record it.
89
+ 4. **Use or create another branch**: the user names it. Record it first with
90
+ `mate artifact link "<change-name>" --branch "<name>" --json`; only after that
91
+ succeeds, check local and `origin` refs: `git switch "<name>"` when local,
92
+ `git switch --track -c "<name>" "origin/<name>"` when remote-only, otherwise
93
+ `git switch -c "<name>"` from the current `HEAD`, so a refused name leaves no branch.
94
+ Uncommitted edits carry over. With `jira`, the menu hints to put the key in the name
95
+ (`feature/ABC-123-acme-retry`); a named branch carries its ticket only in its name,
96
+ so never pass `--ticket` for it. When the name holds no Jira key, say in one line
97
+ that no ticket is tracked, and continue.
74
98
  5. **Work directly here** (protected branch only) — only when the user explicitly chooses it.
75
99
  Record it as a direct delivery:
76
100
  `mate artifact link "<change-name>" --branch "<branch>" --direct --json`.
77
101
 
78
102
  **Tickets** exist only when `ticketFormat` is `jira`; otherwise never ask for, offer, or
79
- mention one. With `jira` and no `record.ticket`, options 1 and 2 accept an optional Jira
80
- key in the answer (`1 ABC-123`). Record it first with
81
- `mate artifact link "<change-name>" --ticket "<KEY>" --json`, then read `defaultBranch`
82
- again with `mate artifact link "<change-name>" --json` before creating the branch or
83
- running the worktree command. On a refused key, name the expected format and ask once more.
103
+ mention one. A ticket only names a new branch; it is stored nowhere else. With `jira`,
104
+ when nothing is recorded or inherited and `defaultBranch` exists neither locally nor on
105
+ `origin`, options 1 and 2 accept an optional Jira key in the same answer: say so in the
106
+ menu (`1 ABC-123` names the new branch after the ticket; `1` alone creates it without
107
+ one). Option 4 takes no key in the answer; its name carries it. Never ask a separate
108
+ ticket question. An agent without a person to ask passes no
109
+ ticket. On a refused key, name the expected format and ask once more.
84
110
 
85
111
  Record the branch before writing any code. When `mate artifact link` refuses, report
86
112
  its message and ask; never work around it.
@@ -115,7 +141,9 @@ never invokes.
115
141
  - Above the section, label `/mate-show-me` and `/mate-simplify-code` as optional, in
116
142
  any order; they are not prerequisites for archive.
117
143
  - In the section, list `/mate-archive-change <change-name>`, after any required work
118
- still open (a failing check, an unanswered question).
144
+ still open (a failing check, an unanswered question). Name the archive action only
145
+ there: omit the reference's completion sentence that also points to
146
+ `/mate-archive-change`.
119
147
  - Several changes on one branch: list their archives in dependency order, and say above
120
148
  the section that this order avoids an advisory archive warning; it is not a gate.
121
149
 
@@ -38,11 +38,6 @@ merge. Archiving is local and uncommitted; it publishes nothing.
38
38
  - `--not-applicable "<reason>"` — for a specification-only change;
39
39
  - `--skip-branch` — when the user skips the question; publication will ask again.
40
40
 
41
- Before re-running with a named branch, read `mate artifact link "<change-name>" --json`.
42
- Only when it reports `ticketFormat` `jira` and no `record.ticket`, and the branch name
43
- holds exactly one Jira key (`feature/ABC-123-retry`), offer to record that ticket first:
44
- `mate artifact link "<change-name>" --ticket "<KEY>" --json`.
45
-
46
41
  3. **Report.** Relay every entry of `warnings` first: another active change that
47
42
  modifies the same requirement, a declared dependency that is not archived yet, or
48
43
  planning artifacts its schema requires that are missing (`incomplete-planning`).
@@ -55,14 +55,8 @@ propose steps below.
55
55
 
56
56
  3. **Follow the OpenSpec workflow.** Read
57
57
  [references/openspec-propose.md](references/openspec-propose.md) and follow it with the
58
- chosen schema (pass `--schema <schema>` when creating the change).
59
-
60
- Once the run's first change exists, read `ticketFormat` from
61
- `mate artifact link "<change-name>" --json`. Only when it is `jira`, ask once per run
62
- for an optional Jira ticket (`ABC-123`) and record an answer on every change the run
63
- created: `mate artifact link "<change-name>" --ticket "<KEY>" --json`. An empty answer
64
- records nothing; a refused key is asked once more with the expected format. With
65
- `none`, never ask.
58
+ chosen schema (pass `--schema <schema>` when creating the change). Never ask for a
59
+ ticket; apply asks when it creates the branch.
66
60
 
67
61
  4. **Hand off to human review.** Reviews are done by people, not by a skill.
68
62
  End the response with a final `## Next steps` section: numbered required actions in