@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,238 @@
1
+ // oxlint-disable no-await-in-loop
2
+ import { execFileSync, spawn } from "node:child_process";
3
+ import crypto from "node:crypto";
4
+ import fsSync from "node:fs";
5
+ import fs from "node:fs/promises";
6
+ import net from "node:net";
7
+
8
+ import {
9
+ activeSessions,
10
+ type Fetch,
11
+ MATE_OPENCODE_SERVER,
12
+ OPENCODE_SERVER_PASSWORD,
13
+ type OpenCodeServerRecord,
14
+ openCodeServersDir,
15
+ processAlive,
16
+ readServerPassword,
17
+ readServerRecord,
18
+ serverFileBase,
19
+ } from "../runtime/opencode-server-record";
20
+ import { withLock } from "../runtime/session-registry";
21
+ import { writeAtomic } from "../runtime/write-atomic";
22
+
23
+ /**
24
+ * Starts or reuses the Mate OpenCode server of a Working Repository. The
25
+ * password lives only in `<repo>.key` (0600) and in environment variables:
26
+ * never in argv, the record, or a log line.
27
+ */
28
+
29
+ export interface ServerDeps {
30
+ dir: string;
31
+ /** Starts `opencode serve` detached; returns its pid. */
32
+ start: (options: { cwd: string; env: NodeJS.ProcessEnv; port: number; log: string }) => number;
33
+ freePort: () => Promise<number>;
34
+ fetch: Fetch;
35
+ alive: (pid: number) => boolean;
36
+ /** The process's command line, or null when it cannot be read. */
37
+ command: (pid: number) => string | null;
38
+ kill: (pid: number, signal: NodeJS.Signals) => void;
39
+ sleep: (ms: number) => Promise<void>;
40
+ now: () => Date;
41
+ password: () => string;
42
+ }
43
+
44
+ const READY_TIMEOUT_MS = 15_000;
45
+ const STOP_TIMEOUT_MS = 5000;
46
+ const POLL_MS = 200;
47
+
48
+ function startServe({ cwd, env, port, log }: Parameters<ServerDeps["start"]>[0]): number {
49
+ const fd = fsSync.openSync(log, "a", 0o600);
50
+ try {
51
+ const child = spawn("opencode", ["serve", "--hostname", "127.0.0.1", "--port", String(port)], {
52
+ cwd,
53
+ env,
54
+ detached: true,
55
+ stdio: ["ignore", fd, fd],
56
+ });
57
+ child.unref();
58
+ if (child.pid === undefined) throw new Error("opencode serve did not start");
59
+ return child.pid;
60
+ } finally {
61
+ fsSync.closeSync(fd);
62
+ }
63
+ }
64
+
65
+ function freePort(): Promise<number> {
66
+ return new Promise((resolve, reject) => {
67
+ const probe = net.createServer();
68
+ probe.once("error", reject);
69
+ probe.listen(0, "127.0.0.1", () => {
70
+ const address = probe.address();
71
+ probe.close(() =>
72
+ typeof address === "object" && address
73
+ ? resolve(address.port)
74
+ : reject(new Error("no free port")),
75
+ );
76
+ });
77
+ });
78
+ }
79
+
80
+ function commandOf(pid: number): string | null {
81
+ try {
82
+ return execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" }).trim();
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+
88
+ /** Guards a kill of a pid the record names: the server may be gone and the pid reused. */
89
+ const isOpenCodeServe = (command: string | null) => /\bopencode\b.*\bserve\b/.test(command ?? "");
90
+
91
+ export const defaultServerDeps: ServerDeps = {
92
+ dir: openCodeServersDir(),
93
+ start: startServe,
94
+ freePort,
95
+ fetch,
96
+ alive: processAlive,
97
+ command: commandOf,
98
+ kill: (pid, signal) => process.kill(pid, signal),
99
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
100
+ now: () => new Date(),
101
+ password: () => crypto.randomBytes(32).toString("base64url"),
102
+ };
103
+
104
+ /** SHA-256 over the sorted `MATE_*` variables, the guidance payload included. */
105
+ export function serverStamp(env: NodeJS.ProcessEnv): string {
106
+ const entries = Object.entries(env)
107
+ .filter(([name, value]) => name.startsWith("MATE_") && name !== MATE_OPENCODE_SERVER && value)
108
+ .toSorted(([a], [b]) => a.localeCompare(b));
109
+ return crypto.createHash("sha256").update(JSON.stringify(entries)).digest("hex");
110
+ }
111
+
112
+ export interface EnsureServerInput {
113
+ repositoryId: string;
114
+ /** Directory the server runs in: the repository's main checkout. */
115
+ cwd: string;
116
+ /** The server's launch environment, guidance included, without password or flag. */
117
+ env: NodeJS.ProcessEnv;
118
+ version?: string;
119
+ }
120
+
121
+ export interface EnsuredServer {
122
+ url: string;
123
+ password: string;
124
+ /** Set when a busy server with an older configuration was reused. */
125
+ warning?: string;
126
+ }
127
+
128
+ async function stopServer(pid: number, deps: ServerDeps): Promise<void> {
129
+ try {
130
+ deps.kill(pid, "SIGTERM");
131
+ } catch {
132
+ return;
133
+ }
134
+ for (let waited = 0; waited < STOP_TIMEOUT_MS; waited += POLL_MS) {
135
+ if (!deps.alive(pid)) return;
136
+ await deps.sleep(POLL_MS);
137
+ }
138
+ try {
139
+ deps.kill(pid, "SIGKILL");
140
+ } catch {
141
+ /* already gone */
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Waits by the clock, so a server that accepts connections but never answers
147
+ * (each check waiting out its fetch timeout) still gives up in time; the poll
148
+ * count bounds it where the clock stands still.
149
+ */
150
+ async function waitReady(url: string, password: string, pid: number, deps: ServerDeps) {
151
+ const started = deps.now().getTime();
152
+ for (let polled = 0; ; polled += POLL_MS) {
153
+ if (Math.max(deps.now().getTime() - started, polled) >= READY_TIMEOUT_MS) return false;
154
+ if ((await activeSessions(url, password, deps.fetch)) !== null) return true;
155
+ if (!deps.alive(pid)) return false;
156
+ await deps.sleep(POLL_MS);
157
+ }
158
+ }
159
+
160
+ async function startServer(
161
+ input: EnsureServerInput,
162
+ base: string,
163
+ stamp: string,
164
+ deps: ServerDeps,
165
+ ): Promise<EnsuredServer> {
166
+ const log = `${base}.log`;
167
+ // A port taken between pick and bind fails the start; one retry with a new port.
168
+ for (let attempt = 1; ; attempt += 1) {
169
+ const port = await deps.freePort();
170
+ const password = deps.password();
171
+ await writeAtomic(`${base}.key`, `${password}\n`, 0o600);
172
+ const pid = deps.start({
173
+ cwd: input.cwd,
174
+ env: { ...input.env, [MATE_OPENCODE_SERVER]: "1", [OPENCODE_SERVER_PASSWORD]: password },
175
+ port,
176
+ log,
177
+ });
178
+ const url = `http://127.0.0.1:${port}`;
179
+ if (await waitReady(url, password, pid, deps)) {
180
+ const record: OpenCodeServerRecord = {
181
+ url,
182
+ pid,
183
+ stamp,
184
+ startedAt: deps.now().toISOString(),
185
+ ...(input.version ? { version: input.version } : {}),
186
+ };
187
+ await writeAtomic(`${base}.json`, `${JSON.stringify(record, null, 2)}\n`, 0o600);
188
+ return { url, password };
189
+ }
190
+ await stopServer(pid, deps);
191
+ if (attempt >= 2) {
192
+ await fs.rm(`${base}.key`, { force: true });
193
+ throw new Error(`The Mate OpenCode server did not start; see ${log}`);
194
+ }
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Reuses the repository's server while its process lives and its API answers;
200
+ * replaces a stale one (other stamp) only when no session of it is busy, and
201
+ * stops one that no longer answers before starting the next.
202
+ */
203
+ export async function ensureOpenCodeServer(
204
+ input: EnsureServerInput,
205
+ deps: ServerDeps = defaultServerDeps,
206
+ ): Promise<EnsuredServer> {
207
+ await fs.mkdir(deps.dir, { recursive: true, mode: 0o700 });
208
+ const base = serverFileBase(input.repositoryId, deps.dir);
209
+ const stamp = serverStamp(input.env);
210
+ return withLock(
211
+ `${base}.json`,
212
+ async () => {
213
+ const record = await readServerRecord(base);
214
+ const password = await readServerPassword(base);
215
+ if (record && password && deps.alive(record.pid)) {
216
+ const active = await activeSessions(record.url, password, deps.fetch);
217
+ if (active !== null && record.stamp === stamp) return { url: record.url, password };
218
+ if (active !== null && active.length > 0) {
219
+ return {
220
+ url: record.url,
221
+ password,
222
+ warning: `The Mate OpenCode server of ${input.repositoryId} runs with an older configuration; it restarts on the next launch while no session is busy.`,
223
+ };
224
+ }
225
+ // An idle server with an older configuration, or one that stopped answering.
226
+ if (active !== null || isOpenCodeServe(deps.command(record.pid))) {
227
+ await stopServer(record.pid, deps);
228
+ }
229
+ }
230
+ return startServer(input, base, stamp, deps);
231
+ },
232
+ // A start may take the readiness timeout, one last check, and a stop, twice.
233
+ {
234
+ waitMs: 2 * (READY_TIMEOUT_MS + STOP_TIMEOUT_MS) + 10_000,
235
+ staleMs: 2 * (READY_TIMEOUT_MS + STOP_TIMEOUT_MS) + 15_000,
236
+ },
237
+ );
238
+ }
@@ -1,3 +1,4 @@
1
+ import crypto from "node:crypto";
1
2
  import { existsSync } from "node:fs";
2
3
  import fs from "node:fs/promises";
3
4
  import path from "node:path";
@@ -10,6 +11,8 @@ import {
10
11
  type ClaudeDeliveryPlan,
11
12
  } from "../../../runtime/claude-delivery-plan";
12
13
  import { hookGroupKey, type ClaudeHookGroup } from "../../../runtime/claude-hook-group";
14
+ import { MATE_ENV } from "../../../runtime/env-names";
15
+ import { SESSION_ORIGIN_ENV } from "../../../runtime/session-registry";
13
16
  import { resolveSecretPolicy } from "../../../runtime/policy";
14
17
  import { managedSessionKind } from "../../../runtime/session-kind";
15
18
  import { NOT_WRAPPED } from "../../../runtime/wrap-state";
@@ -20,11 +23,14 @@ import {
20
23
  } from "../../../tools/setup/providers/claude";
21
24
  import { definesUserClaudeAttribution } from "../../../tools/setup/providers/claude-attribution";
22
25
  import { worktreePluginSourceConflicts } from "../../../tools/setup/providers/claude-worktree-plugins";
23
- import type { ClaudeSettings } from "../../../tools/setup/providers/claude-format";
26
+ import {
27
+ mergeClaudeHookGroups,
28
+ type ClaudeSettings,
29
+ } from "../../../tools/setup/providers/claude-format";
24
30
  import { getClaudePluginRoot, validateClaudePluginAssets } from "../../package-paths";
25
31
  import type { PrepareResult } from "../session-prepare";
26
32
  import { LaunchPreflightError } from "../types";
27
- import { type AdapterContext, LaunchAdapter } from "./base";
33
+ import { type AdapterContext, LaunchAdapter, type PreparedLaunch } from "./base";
28
34
  import { APPEND_PROMPT_FLAG, liftAppendedPrompts } from "./claude-args";
29
35
 
30
36
  /** The paths are present only where the plan names that channel and the file exists. */
@@ -97,6 +103,140 @@ async function settingsPathFor(
97
103
  return settingsPath;
98
104
  }
99
105
 
106
+ /** `--bg`/`--background`: Claude runs the session in its own daemon and returns at once. */
107
+ export function isBackgroundLaunch(args: readonly string[]): boolean {
108
+ return args.includes("--bg") || args.includes("--background");
109
+ }
110
+
111
+ const SETTINGS_FLAG = "--settings";
112
+ const BG_SETTINGS_PRUNE_MS = 30 * 24 * 60 * 60 * 1000;
113
+
114
+ /**
115
+ * Where a background launch writes its `--settings`, named by its content: a
116
+ * launch with another environment never overwrites the file a running session
117
+ * reads. Git-ignored.
118
+ */
119
+ export function backgroundLaunchSettingsPath(
120
+ companionPath: string,
121
+ repositoryId: string | undefined,
122
+ content: string,
123
+ ): string {
124
+ const hash = crypto.createHash("sha256").update(content).digest("hex").slice(0, 16);
125
+ return launchSettingsPath(companionPath, repositoryId ?? "companion").replace(
126
+ /\.json$/,
127
+ `.${hash}.bg.json`,
128
+ );
129
+ }
130
+
131
+ /** Every `--settings` value (`--settings <x>` or `--settings=<x>`), and the args without them. */
132
+ function takeSettingsArgs(args: readonly string[]) {
133
+ const values: string[] = [];
134
+ const rest: string[] = [];
135
+ let at = -1;
136
+ for (let index = 0; index < args.length; index += 1) {
137
+ const arg = args[index]!;
138
+ if (arg === SETTINGS_FLAG && index + 1 < args.length) {
139
+ values.push(args[(index += 1)]!);
140
+ } else if (arg.startsWith(`${SETTINGS_FLAG}=`)) {
141
+ values.push(arg.slice(SETTINGS_FLAG.length + 1));
142
+ } else {
143
+ rest.push(arg);
144
+ continue;
145
+ }
146
+ if (at < 0) at = rest.length;
147
+ }
148
+ return { values, rest, at };
149
+ }
150
+
151
+ /** A `--settings` value is a file path or inline JSON, as Claude reads it. */
152
+ async function readSettingsArg(value: string): Promise<ClaudeSettings> {
153
+ const json = value.trimStart().startsWith("{") ? value : await fs.readFile(value, "utf8");
154
+ return JSON.parse(json) as ClaudeSettings;
155
+ }
156
+
157
+ /** The names a background session takes from the launch, not the daemon. */
158
+ const LAUNCH_ENV_NAMES = [...Object.values(MATE_ENV), SESSION_ORIGIN_ENV];
159
+
160
+ const envOf = (settings: ClaudeSettings) => (settings.env ?? {}) as Record<string, string>;
161
+
162
+ /**
163
+ * Merges `next` over `base` as Claude merges settings scopes: `env` per name,
164
+ * hook groups appended per event, permission lists joined; other keys replaced.
165
+ */
166
+ function mergeSettings(base: ClaudeSettings, next: ClaudeSettings): ClaudeSettings {
167
+ const merged: ClaudeSettings = { ...base, ...next, env: { ...envOf(base), ...envOf(next) } };
168
+ if (base.hooks && next.hooks) merged.hooks = mergeClaudeHookGroups(base.hooks, next.hooks);
169
+ if (base.permissions && next.permissions) {
170
+ const permissions: Record<string, unknown> = { ...base.permissions, ...next.permissions };
171
+ for (const [key, value] of Object.entries(next.permissions)) {
172
+ const before = (base.permissions as Record<string, unknown>)[key];
173
+ if (Array.isArray(before) && Array.isArray(value)) {
174
+ permissions[key] = [...new Set([...before, ...value])];
175
+ }
176
+ }
177
+ merged.permissions = permissions as ClaudeSettings["permissions"];
178
+ }
179
+ return merged;
180
+ }
181
+
182
+ /** Drops background settings files no launch wrote for 30 days. */
183
+ async function pruneBackgroundSettings(dir: string, now = Date.now()): Promise<void> {
184
+ const names = await fs.readdir(dir).catch(() => [] as string[]);
185
+ await Promise.all(
186
+ names
187
+ .filter((name) => name.endsWith(".bg.json"))
188
+ .map(async (name) => {
189
+ const file = path.join(dir, name);
190
+ const stat = await fs.stat(file).catch(() => null);
191
+ if (stat && now - stat.mtimeMs > BG_SETTINGS_PRUNE_MS) await fs.rm(file, { force: true });
192
+ }),
193
+ );
194
+ }
195
+
196
+ /**
197
+ * Claude's daemon starts a background session with the daemon's environment,
198
+ * not the launch's, so the launch environment travels in the `--settings`
199
+ * file's `env` instead: every Mate name, empty when the launch leaves it
200
+ * unset, so a value the daemon inherited elsewhere never shows through. The
201
+ * process Mate starts carries no Mate name, so a daemon it starts inherits none.
202
+ * Mate's and the user's `--settings` merge into that one file (`mergeSettings`).
203
+ */
204
+ async function backgroundLaunch(
205
+ context: ClaudeLaunchContext,
206
+ launch: PreparedLaunch,
207
+ ): Promise<PreparedLaunch> {
208
+ const { values, rest, at } = takeSettingsArgs(launch.args);
209
+ let base: ClaudeSettings = {};
210
+ for (const value of values) {
211
+ // oxlint-disable-next-line no-await-in-loop -- later settings win
212
+ const next = await readSettingsArg(value);
213
+ base = mergeSettings(base, next);
214
+ }
215
+ const sessionEnv: Record<string, string> = {};
216
+ for (const name of LAUNCH_ENV_NAMES) {
217
+ sessionEnv[name] = launch.env[name] ?? "";
218
+ }
219
+ if (launch.env.PATH) sessionEnv.PATH = launch.env.PATH;
220
+
221
+ const settings = { ...base, env: { ...envOf(base), ...sessionEnv } };
222
+ const content = `${JSON.stringify(settings, null, 2)}\n`;
223
+ const target = backgroundLaunchSettingsPath(
224
+ context.companionPath,
225
+ context.repository?.id,
226
+ content,
227
+ );
228
+ await fs.mkdir(path.dirname(target), { recursive: true });
229
+ await pruneBackgroundSettings(path.dirname(target));
230
+ await writeAtomic(target, content);
231
+ const args = [...rest];
232
+ args.splice(at < 0 ? 0 : at, 0, SETTINGS_FLAG, target);
233
+
234
+ const env: NodeJS.ProcessEnv = { ...launch.env, PATH: process.env.PATH };
235
+ for (const name of LAUNCH_ENV_NAMES) delete env[name];
236
+ if (!env.PATH) delete env.PATH;
237
+ return { ...launch, args, env };
238
+ }
239
+
100
240
  export class ClaudeAdapter extends LaunchAdapter<ClaudeLaunchContext> {
101
241
  readonly toolName = "claude";
102
242
  readonly interactive = true;
@@ -130,6 +270,11 @@ export class ClaudeAdapter extends LaunchAdapter<ClaudeLaunchContext> {
130
270
  return { ...context, delivery, pluginDirectories: prepared.claudePluginDirectories ?? [] };
131
271
  }
132
272
 
273
+ async prepareLaunch(context: ClaudeLaunchContext, args: string[]): Promise<PreparedLaunch> {
274
+ const launch = await super.prepareLaunch(context, args);
275
+ return isBackgroundLaunch(args) ? backgroundLaunch(context, launch) : launch;
276
+ }
277
+
133
278
  /** A failed Claude wrap pass names the entry that failed. */
134
279
  launchFailure(prepared: PrepareResult): unknown {
135
280
  const failed = prepared.steps.find((step) => step.outcome === "failed");
@@ -5,15 +5,19 @@ const fs = await import("node:fs/promises");
5
5
  const path = await import("node:path");
6
6
 
7
7
  import { MATE_ENV } from "../../../runtime/env";
8
+ import { SESSION_ORIGIN_ENV } from "../../../runtime/session-registry";
9
+ import { mainCheckoutOf } from "../../../runtime/git-layout";
10
+ import { OPENCODE_PASSWORD } from "../../../runtime/opencode-server-record";
8
11
  import { validateGuidanceData, type MateGuidanceFile } from "../../../runtime/guidance";
9
12
  import { resolveSecretPolicy } from "../../../runtime/policy";
10
13
 
14
+ import { ensureOpenCodeServer } from "../../opencode-server";
11
15
  import { validateOpenCodePluginAssets } from "../../package-paths";
12
16
  import { readOpenCodeConfig } from "../../../tools/setup/providers/opencode-format";
13
17
  import { buildOpenCodeGuidance } from "../opencode-guidance";
14
18
  import type { PrepareResult } from "../session-prepare";
15
19
  import { LaunchPreflightError } from "../types";
16
- import { type AdapterContext, LaunchAdapter, prepareFailure } from "./base";
20
+ import { type AdapterContext, LaunchAdapter, type PreparedLaunch, prepareFailure } from "./base";
17
21
 
18
22
  /** The Mate plugin is a V2 plugin; an older host rejects it at load time. */
19
23
  const MIN_OPENCODE_MAJOR = 2;
@@ -24,6 +28,9 @@ const MIN_OPENCODE_MAJOR = 2;
24
28
  */
25
29
  const STANDALONE_FLAG = "--standalone";
26
30
 
31
+ /** Mate's own flag: run the TUI as a client of the repository's Mate OpenCode server. */
32
+ const BACKGROUND_FLAG = "--bg";
33
+
27
34
  /** Raw `opencode --version` output, or `undefined` when the binary cannot run. */
28
35
  export type OpenCodeVersionProbe = () => string | undefined;
29
36
 
@@ -57,15 +64,59 @@ function readInvocation(launchWorkingDirectory: string, args: string[]): OpenCod
57
64
  return { command, rest, hostsPrivateServer: Boolean(hostsServer) && !choosesRemoteServer };
58
65
  }
59
66
 
67
+ /** The server outlives the launch that started it; one launch's origin must not mark its other sessions. */
68
+ function withoutSessionOrigin(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
69
+ const { [SESSION_ORIGIN_ENV]: _origin, ...rest } = env;
70
+ return rest;
71
+ }
72
+
60
73
  export class OpenCodeAdapter extends LaunchAdapter {
61
74
  readonly toolName = "opencode";
62
75
  readonly interactive = true;
63
76
  private readonly requiredRuntimeAssets = [path.join(".opencode", "opencode.json")] as const;
64
77
 
65
- constructor(private readonly probeVersion: OpenCodeVersionProbe = probeOpenCodeVersion) {
78
+ constructor(
79
+ private readonly probeVersion: OpenCodeVersionProbe = probeOpenCodeVersion,
80
+ private readonly ensureServer: typeof ensureOpenCodeServer = ensureOpenCodeServer,
81
+ ) {
66
82
  super();
67
83
  }
68
84
 
85
+ /**
86
+ * `--bg`: ensure the repository's Mate OpenCode server, built from its main
87
+ * checkout so every worktree shares one server and one stamp, then run the
88
+ * TUI as its client. The guidance goes to the server only; `--server` masks
89
+ * it for the client.
90
+ */
91
+ async prepareLaunch(context: AdapterContext, args: string[]): Promise<PreparedLaunch> {
92
+ if (!args.includes(BACKGROUND_FLAG)) return super.prepareLaunch(context, args);
93
+ const { repository } = context;
94
+ if (!repository) {
95
+ throw new LaunchPreflightError(
96
+ `\`${BACKGROUND_FLAG}\` needs a Working Repository; run \`mate opencode -- ${BACKGROUND_FLAG}\` inside one.`,
97
+ );
98
+ }
99
+ const main = mainCheckoutOf(repository.path);
100
+ const serverContext = {
101
+ ...context,
102
+ repository: { ...repository, path: main },
103
+ launchWorkingDirectory: main,
104
+ };
105
+ const server = await this.ensureServer({
106
+ repositoryId: repository.id,
107
+ cwd: main,
108
+ env: withoutSessionOrigin({
109
+ ...this.environment(serverContext),
110
+ ...this.extendEnvironment(serverContext),
111
+ }),
112
+ version: this.probeVersion(),
113
+ });
114
+ if (server.warning) process.stderr.write(`mate: ${server.warning}\n`);
115
+ const clientArgs = [...args.filter((arg) => arg !== BACKGROUND_FLAG), "--server", server.url];
116
+ const launch = await super.prepareLaunch(context, clientArgs);
117
+ return { ...launch, env: { ...launch.env, [OPENCODE_PASSWORD]: server.password } };
118
+ }
119
+
69
120
  private validateOpenCodeVersion(): void {
70
121
  const output = this.probeVersion();
71
122
  const major = parseOpenCodeMajor(output);
@@ -0,0 +1,125 @@
1
+ import path from "node:path";
2
+
3
+ import { checkoutAt } from "../../runtime/git-layout";
4
+ import { physicalPath } from "../../runtime/physical-path";
5
+ import type { WrapRuntime } from "../../runtime/runtime-document-manifest";
6
+ import { readWrapStateSync, WRAP_RUNTIMES } from "../../runtime/wrap-state";
7
+ import { GlobalConfigStore } from "./global-config-store";
8
+ import { registeredCheckoutOf } from "./registry-checkouts";
9
+ import {
10
+ CompanionResolver,
11
+ findRepoLocalLinkedRepository,
12
+ readCompanionRegistry,
13
+ } from "./repository-link";
14
+ import type { LinkedRepository } from "./types";
15
+ import { projectWorkingRepositoryBestEffort } from "./working-repo-projection";
16
+
17
+ /**
18
+ * Adoption as `mate session prepare`, a launch and `mate wrap` run it (design
19
+ * Decisions 7 and 8): a look-up that writes nothing, so a caller can refuse
20
+ * first, then the Checkout's link and Projection Root, each best-effort.
21
+ */
22
+
23
+ export interface AdoptionLookup {
24
+ companionPath: string;
25
+ repositoryId: string;
26
+ /** The runtimes the clone's Registered Checkout is wrapped for, in `WRAP_RUNTIMES` order. */
27
+ runtimes: WrapRuntime[];
28
+ }
29
+
30
+ /** The runtimes the manifest at `checkout` records, in `WRAP_RUNTIMES` order. */
31
+ function wrappedAt(checkout: string): WrapRuntime[] {
32
+ const { runtimes } = readWrapStateSync(checkout);
33
+ return WRAP_RUNTIMES.filter((runtime) => runtimes.has(runtime));
34
+ }
35
+
36
+ /** The Registered Checkout of the entry `repositoryId` names, read without writing. */
37
+ export async function registeredCheckout(
38
+ companionPath: string,
39
+ repositoryId: string,
40
+ ): Promise<string | null> {
41
+ const { repos } = await readCompanionRegistry(companionPath).catch(() => ({ repos: [] }));
42
+ const entry = repos.find((repo) => repo.id === repositoryId);
43
+ return entry ? registeredCheckoutOf(entry) : null;
44
+ }
45
+
46
+ /**
47
+ * The clone's entry for `folder` and its Registered Checkout's runtimes, with
48
+ * no write: neither the resolver's self-heal nor its stale-pointer prune. Null
49
+ * when no companion, or more than one, lists the folder's clone.
50
+ */
51
+ export async function lookUpAdoption(
52
+ folder: string,
53
+ globalConfigStore: GlobalConfigStore = new GlobalConfigStore(),
54
+ ): Promise<AdoptionLookup | null> {
55
+ const { match, ambiguousMatches } = await new CompanionResolver(
56
+ globalConfigStore,
57
+ ).resolveWithDiagnostics(folder, { write: false });
58
+ if (!match || ambiguousMatches.length > 1) return null;
59
+ const registered = await registeredCheckout(match.companionPath, match.repositoryId);
60
+ return { ...match, runtimes: registered ? wrappedAt(registered) : [] };
61
+ }
62
+
63
+ /**
64
+ * Writes the Checkout's link (the resolver's self-heal) and its Projection
65
+ * Root, outside the companion lock. A failed write warns, and the Checkout
66
+ * still comes back as the repository, so the command that adopted it proceeds.
67
+ */
68
+ export async function adoptCheckout(
69
+ folder: string,
70
+ lookup: AdoptionLookup,
71
+ globalConfigStore: GlobalConfigStore = new GlobalConfigStore(),
72
+ ): Promise<LinkedRepository> {
73
+ await new CompanionResolver(globalConfigStore).resolveWithDiagnostics(folder);
74
+ const repository = (await findRepoLocalLinkedRepository(folder)) ?? {
75
+ id: lookup.repositoryId,
76
+ path: checkoutAt(folder)?.root ?? path.resolve(folder),
77
+ };
78
+ await projectWorkingRepositoryBestEffort(lookup.companionPath, repository);
79
+ return repository;
80
+ }
81
+
82
+ /**
83
+ * Looks up and adopts `folder` in one step, for a command that wraps it
84
+ * anyway (`mate wrap`). Null when no single companion lists its clone.
85
+ */
86
+ export async function adoptNewCheckout(
87
+ folder: string,
88
+ globalConfigStore: GlobalConfigStore = new GlobalConfigStore(),
89
+ ): Promise<LinkedRepository | null> {
90
+ const lookup = await lookUpAdoption(folder, globalConfigStore);
91
+ return lookup && adoptCheckout(folder, lookup, globalConfigStore);
92
+ }
93
+
94
+ export interface RegisteredWraps {
95
+ /** The clone's Registered Checkout. */
96
+ checkout: string;
97
+ runtimes: WrapRuntime[];
98
+ }
99
+
100
+ /**
101
+ * The clone's Registered Checkout and its wrapped runtimes, when that is
102
+ * another Checkout than `repository` and is wrapped for any.
103
+ */
104
+ export async function otherRegisteredWraps(
105
+ companionPath: string,
106
+ repository: LinkedRepository,
107
+ ): Promise<RegisteredWraps | null> {
108
+ const checkout = await registeredCheckout(companionPath, repository.id);
109
+ if (!checkout || physicalPath(checkout) === physicalPath(repository.path)) return null;
110
+ const runtimes = wrappedAt(checkout);
111
+ return runtimes.length > 0 ? { checkout, runtimes } : null;
112
+ }
113
+
114
+ /**
115
+ * The runtimes a prepare wraps `repository` for besides its own: none while
116
+ * its manifest records a wrapped runtime, else those its Registered Checkout
117
+ * is wrapped for (Decision 8). The Registered Checkout itself takes none.
118
+ */
119
+ export async function inheritedWrapRuntimes(
120
+ companionPath: string,
121
+ repository: LinkedRepository,
122
+ ): Promise<WrapRuntime[]> {
123
+ if (wrappedAt(repository.path).length > 0) return [];
124
+ return (await otherRegisteredWraps(companionPath, repository))?.runtimes ?? [];
125
+ }
@@ -25,10 +25,14 @@ export class CompanionRegistryStore extends YamlFileStore<CompanionRegistryConfi
25
25
  await migrateRegistryData(this.configPath);
26
26
  const config = await super.load();
27
27
  // Silently drop legacy per-repo policy fields (profile/overrides); the
28
- // clean shape persists on the next save.
28
+ // clean shape persists on the next save. The shared Git folder stays.
29
29
  return {
30
30
  ...config,
31
- repos: (config.repos ?? []).map(({ id, path: repoPath }) => ({ id, path: repoPath })),
31
+ repos: (config.repos ?? []).map(({ id, path: repoPath, gitCommonDir }) => ({
32
+ id,
33
+ path: repoPath,
34
+ ...(typeof gitCommonDir === "string" ? { gitCommonDir } : {}),
35
+ })),
32
36
  };
33
37
  }
34
38
 
@@ -76,7 +76,7 @@ export const editorWorkspacePath = workspaceDocumentPath;
76
76
  * `.mate/<repo>.mate.code-workspace` and returns its path, or the error that
77
77
  * left the document unchanged. Backs `openEditorWorkspace`.
78
78
  */
79
- async function writeWorkspaceDocument(
79
+ export async function prepareEditorWorkspace(
80
80
  companionPaths: string[],
81
81
  repoPath: string,
82
82
  ): Promise<{ workspacePath: string; error?: Error }> {
@@ -113,7 +113,7 @@ export async function openEditorWorkspace(
113
113
  return false;
114
114
  }
115
115
 
116
- const { workspacePath, error } = await writeWorkspaceDocument(companionPaths, repoPath);
116
+ const { workspacePath, error } = await prepareEditorWorkspace(companionPaths, repoPath);
117
117
  if (error) {
118
118
  process.stderr.write(`mate: warning: ${workspacePath}: ${error.message}\n`);
119
119
  return false;