@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,10 @@
1
+ import { execFile } from "node:child_process";
2
+
3
+ /** The branch checked out at `dir`; null when detached or outside Git. */
4
+ export function currentBranch(dir: string): Promise<string | null> {
5
+ return new Promise((resolve) => {
6
+ execFile("git", ["symbolic-ref", "--quiet", "--short", "HEAD"], { cwd: dir }, (error, out) =>
7
+ resolve(error ? null : out.trim() || null),
8
+ );
9
+ });
10
+ }
@@ -4,7 +4,7 @@ import { MATE_ENV } from "./env-names";
4
4
  import { FRAMEWORK_NAME } from "./framework";
5
5
  import { checkoutRootOf, isLinkedWorktreeOf } from "./git-layout";
6
6
  import { isCapabilityEnabled, policyDocument, readCompanionPolicy } from "./policy";
7
- import { resolveProjection, type ResolvedProjection } from "./projection";
7
+ import { projectionCheckout, resolveProjection, type ResolvedProjection } from "./projection";
8
8
 
9
9
  export { MATE_ENV, type MateEnvVariable } from "./env-names";
10
10
 
@@ -25,11 +25,12 @@ export type CompanionRuntimeContext = {
25
25
  };
26
26
 
27
27
  /**
28
- * Any `MATE_*` variable present means a Mate launch configured this process,
29
- * so the environment is authoritative and the projection is not read.
28
+ * Any non-empty `MATE_*` variable means a Mate launch configured this process,
29
+ * so the environment is authoritative and the projection is not read. A
30
+ * background launch sets every name, empty when unset.
30
31
  */
31
32
  export function hasLaunchEnvironment(env: Record<string, string | undefined>): boolean {
32
- return Object.values(MATE_ENV).some((name) => env[name] !== undefined);
33
+ return Object.values(MATE_ENV).some((name) => env[name] !== undefined && env[name] !== "");
33
34
  }
34
35
 
35
36
  function fromEnvironment(env: Record<string, string | undefined>): CompanionRuntimeContext {
@@ -60,11 +61,14 @@ export interface CompanionRuntimeResolution {
60
61
  * `MATE_*` variable is set, so a managed session never reads it and no stale
61
62
  * or malformed projection can degrade a session a Mate launch configured.
62
63
  * Only a session moved into a linked worktree of its repository reads that
63
- * worktree's projection, for its repository path alone.
64
+ * worktree's projection, for its repository path alone. `borrow: false` answers
65
+ * no projection for a linked worktree that only borrows one: plain `opencode` in
66
+ * a worktree Mate never ran in stays out of scope.
64
67
  */
65
68
  export function resolveCompanionRuntime(
66
69
  env: Record<string, string | undefined> = process.env,
67
70
  cwd: string = process.cwd(),
71
+ options: { borrow?: boolean } = {},
68
72
  ): CompanionRuntimeResolution {
69
73
  if (hasLaunchEnvironment(env)) {
70
74
  const context = fromEnvironment(env);
@@ -76,7 +80,9 @@ export function resolveCompanionRuntime(
76
80
  }
77
81
 
78
82
  const projection = resolveProjection(cwd);
79
- if (!projection) return { context: fromEnvironment(env), projection: null };
83
+ if (!projection || (options.borrow === false && projection.borrowedFrom)) {
84
+ return { context: fromEnvironment(env), projection: null };
85
+ }
80
86
 
81
87
  const policy = readCompanionPolicy(projection.companionPath);
82
88
  return {
@@ -111,7 +117,7 @@ function linkedWorktreePath(context: CompanionRuntimeContext, cwd: string): stri
111
117
  if (!checkout || checkout === repository) return null;
112
118
  const projection = resolveProjection(cwd);
113
119
  if (!projection) return null;
114
- const worktree = realPath(projection.repoRoot);
120
+ const worktree = realPath(projectionCheckout(projection));
115
121
  if (
116
122
  worktree === repository ||
117
123
  realPath(projection.repositoryPath) !== worktree ||
@@ -26,7 +26,7 @@ export interface GitLayout {
26
26
  commonDir: string;
27
27
  }
28
28
 
29
- function realPath(candidate: string): string {
29
+ export function realPath(candidate: string): string {
30
30
  try {
31
31
  return fs.realpathSync(candidate);
32
32
  } catch {
@@ -42,8 +42,17 @@ function readText(filePath: string): string | null {
42
42
  }
43
43
  }
44
44
 
45
- function isDirectory(candidate: string): boolean {
46
- return fs.statSync(candidate, { throwIfNoEntry: false })?.isDirectory() ?? false;
45
+ /** `stat`, or null for a path that is missing or runs through a file (`ENOTDIR`). */
46
+ function statOf(candidate: string): fs.Stats | null {
47
+ try {
48
+ return fs.statSync(candidate);
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+
54
+ export function isDirectory(candidate: string): boolean {
55
+ return statOf(candidate)?.isDirectory() ?? false;
47
56
  }
48
57
 
49
58
  /** The folder a `.git` file names, resolved against the file's own folder. */
@@ -61,7 +70,7 @@ function readPathFile(filePath: string, base: string): string | null {
61
70
  export function readGitLayout(checkoutPath: string): GitLayout | null {
62
71
  /** Real first: a relative `gitdir:` is relative to where `.git` really is. */
63
72
  const dotGit = path.join(realPath(checkoutPath), ".git");
64
- const stat = fs.statSync(dotGit, { throwIfNoEntry: false });
73
+ const stat = statOf(dotGit);
65
74
  if (stat?.isDirectory()) {
66
75
  const gitDir = realPath(dotGit);
67
76
  return { kind: "main", gitDir, commonDir: gitDir };
@@ -156,8 +165,10 @@ function configTrue(value: string | undefined): boolean {
156
165
  * The worktree whose `.git` is the shared folder itself, else `core.worktree`;
157
166
  * none for a bare repository.
158
167
  */
159
- function mainWorktree(commonDir: string): string | null {
160
- const core = coreConfig(commonDir);
168
+ function mainWorktree(
169
+ commonDir: string,
170
+ core: Map<string, string> = coreConfig(commonDir),
171
+ ): string | null {
161
172
  if (configTrue(core.get("bare"))) return null;
162
173
  const configured = core.get("worktree");
163
174
  if (configured) {
@@ -179,11 +190,11 @@ export function gitExcludePath(checkoutPath: string): string | null {
179
190
  }
180
191
 
181
192
  /**
182
- * Each worktree the shared folder lists whose `.git` file still points back to
183
- * it, and each locked one: Git keeps a locked worktree registered while its
184
- * drive is away, and so does this list.
193
+ * Each record under the shared folder's `worktrees/` whose worktree still
194
+ * points back to it, or that is locked: Git keeps a locked worktree registered
195
+ * while its drive is away. Sorted by record name.
185
196
  */
186
- function linkedWorktrees(commonDir: string): string[] {
197
+ function worktreeRecords(commonDir: string): LinkedWorktree[] {
187
198
  const adminRoot = path.join(commonDir, "worktrees");
188
199
  let names: string[];
189
200
  try {
@@ -191,16 +202,26 @@ function linkedWorktrees(commonDir: string): string[] {
191
202
  } catch {
192
203
  return [];
193
204
  }
194
- const worktrees: string[] = [];
195
- for (const name of names) {
196
- const adminDir = path.join(adminRoot, name);
205
+ return names.flatMap((recordName) => {
206
+ const adminDir = path.join(adminRoot, recordName);
197
207
  const dotGit = readPathFile(path.join(adminDir, "gitdir"), adminDir);
198
- if (!dotGit || path.basename(dotGit) !== ".git") continue;
208
+ if (!dotGit || path.basename(dotGit) !== ".git") return [];
199
209
  const checkout = path.dirname(dotGit);
200
210
  const live = readGitLayout(checkout)?.gitDir === realPath(adminDir);
201
- if (live || fs.existsSync(path.join(adminDir, "locked"))) worktrees.push(realPath(checkout));
202
- }
203
- return worktrees;
211
+ if (!live && !fs.existsSync(path.join(adminDir, "locked"))) return [];
212
+ return [{ recordName, path: realPath(checkout), live }];
213
+ });
214
+ }
215
+
216
+ function linkedWorktrees(commonDir: string): string[] {
217
+ return worktreeRecords(commonDir).map((record) => record.path);
218
+ }
219
+
220
+ /** The main worktree of a linked worktree's clone; any other Checkout is its own. */
221
+ export function mainCheckoutOf(checkoutPath: string): string {
222
+ const layout = readGitLayout(checkoutPath);
223
+ const main = layout?.kind === "linked" ? mainWorktree(layout.commonDir) : null;
224
+ return main ?? realPath(checkoutPath);
204
225
  }
205
226
 
206
227
  /**
@@ -217,3 +238,129 @@ export function otherCheckouts(checkoutPath: string): string[] {
217
238
  (checkout) => checkout !== self,
218
239
  );
219
240
  }
241
+
242
+ /** A Checkout root and its layout. */
243
+ export interface CheckoutRoot {
244
+ root: string;
245
+ layout: GitLayout;
246
+ }
247
+
248
+ /**
249
+ * The nearest folder at or above `folder` whose Git layout reads, as Git finds
250
+ * its repository: a nested worktree or a submodule is its own root. `null`
251
+ * outside Git.
252
+ */
253
+ export function checkoutAt(folder: string): CheckoutRoot | null {
254
+ let dir = realPath(folder);
255
+ for (;;) {
256
+ const layout = readGitLayout(dir);
257
+ if (layout) return { root: dir, layout };
258
+ const parent = path.dirname(dir);
259
+ if (parent === dir) return null;
260
+ dir = parent;
261
+ }
262
+ }
263
+
264
+ /** A linked worktree as its clone lists it. */
265
+ export interface LinkedWorktree {
266
+ recordName: string;
267
+ path: string;
268
+ /** Its `.git` file points back; a locked worktree whose folder is away is listed but not live. */
269
+ live: boolean;
270
+ }
271
+
272
+ /** The Checkouts that share one Git folder. */
273
+ export interface Clone {
274
+ commonDir: string;
275
+ bare: boolean;
276
+ /** `null` for a bare repository. */
277
+ mainWorktree: string | null;
278
+ /** By record name: each live worktree, and each locked one whose folder is away. */
279
+ linkedWorktrees: LinkedWorktree[];
280
+ }
281
+
282
+ function isGitFolder(dir: string): boolean {
283
+ return isDirectory(dir) && fs.existsSync(path.join(dir, "HEAD"));
284
+ }
285
+
286
+ /** The clone whose shared Git folder is `commonDir`; `null` when that is no Git folder. */
287
+ export function cloneAt(commonDir: string): Clone | null {
288
+ const dir = realPath(commonDir);
289
+ if (!isGitFolder(dir)) return null;
290
+ const core = coreConfig(dir);
291
+ const bare = configTrue(core.get("bare"));
292
+ return {
293
+ commonDir: dir,
294
+ bare,
295
+ mainWorktree: bare ? null : mainWorktree(dir, core),
296
+ linkedWorktrees: worktreeRecords(dir),
297
+ };
298
+ }
299
+
300
+ /** The main worktree of the clone at `commonDir`, without listing its worktrees. */
301
+ export function mainWorktreeOf(commonDir: string): string | null {
302
+ const dir = realPath(commonDir);
303
+ return isGitFolder(dir) ? mainWorktree(dir) : null;
304
+ }
305
+
306
+ /**
307
+ * The clone's live Checkouts in the order a handover or a borrow tries them:
308
+ * the main worktree, then each linked worktree that points back, by record
309
+ * name. Lazy, so a caller that takes the main worktree lists no records.
310
+ */
311
+ export function* liveCheckouts(commonDir: string): Generator<string> {
312
+ const dir = realPath(commonDir);
313
+ if (!isGitFolder(dir)) return;
314
+ const main = mainWorktree(dir);
315
+ if (main && isDirectory(main)) yield main;
316
+ for (const record of worktreeRecords(dir)) if (record.live) yield record.path;
317
+ }
318
+
319
+ /**
320
+ * The clone of the Checkout at `root`. `null` for an `own` layout (a submodule,
321
+ * a separate Git folder), which is the Checkout of no shared clone, and outside Git.
322
+ */
323
+ export function cloneOf(root: string): Clone | null {
324
+ const layout = readGitLayout(root);
325
+ if (!layout || layout.kind === "own") return null;
326
+ return cloneAt(layout.commonDir);
327
+ }
328
+
329
+ /**
330
+ * The shared Git folder of the Checkout at `root` when it counts as one of its
331
+ * clone: a main worktree, or a linked worktree whose record points back to it.
332
+ */
333
+ export function checkoutCommonDir(root: string): string | null {
334
+ const layout = readGitLayout(root);
335
+ if (!layout || layout.kind === "own") return null;
336
+ if (layout.kind === "main") return layout.commonDir;
337
+ const dotGit = readPathFile(path.join(layout.gitDir, "gitdir"), layout.gitDir);
338
+ if (!dotGit || path.basename(dotGit) !== ".git") return null;
339
+ return realPath(path.dirname(dotGit)) === realPath(root) ? layout.commonDir : null;
340
+ }
341
+
342
+ /** Two Checkout roots of one clone, compared by the real path of their shared Git folder. */
343
+ export function sameClone(a: string, b: string): boolean {
344
+ const first = checkoutCommonDir(a);
345
+ return first !== null && first === checkoutCommonDir(b);
346
+ }
347
+
348
+ /**
349
+ * The Checkout a session for `repositoryPath` serves from `folder` (design
350
+ * Decision 11): the root of the Checkout holding `folder` when that is another
351
+ * live Checkout of the same clone, else `repositoryPath`.
352
+ */
353
+ export function checkoutServedFrom(repositoryPath: string, folder: string): string {
354
+ const root = checkoutAt(folder)?.root;
355
+ return root && namesOtherCheckout(root, repositoryPath) ? root : repositoryPath;
356
+ }
357
+
358
+ /**
359
+ * `named` is another live Checkout of `root`'s clone, as when a `.mate/` folder
360
+ * was copied from it: such a link or projection belongs to `named`, not `root`.
361
+ */
362
+ export function namesOtherCheckout(root: string, named: string): boolean {
363
+ const self = realPath(root);
364
+ const other = realPath(named);
365
+ return self !== other && isDirectory(other) && sameClone(self, other);
366
+ }
@@ -0,0 +1,65 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ import { MATE_ENV } from "./env-names";
5
+ import { checkoutRootOf, isLinkedWorktreeOf } from "./git-layout";
6
+
7
+ /**
8
+ * A Mate launch environment can reach a process its launch did not start: a
9
+ * Claude background session inherits the environment of the daemon, which
10
+ * holds whichever launch started it. These checks keep such a stray
11
+ * environment from describing another repository.
12
+ */
13
+
14
+ const NAMES: readonly string[] = Object.values(MATE_ENV);
15
+
16
+ function inside(dir: string, root: string): boolean {
17
+ const relative = path.relative(root, dir);
18
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
19
+ }
20
+
21
+ function real(target: string): string {
22
+ try {
23
+ return fs.realpathSync(target);
24
+ } catch {
25
+ return path.resolve(target);
26
+ }
27
+ }
28
+
29
+ /**
30
+ * True when the launch environment describes `cwd`: inside its Working
31
+ * Repository, a linked worktree of it, or its Companion Repository. An
32
+ * environment naming no Working Repository applies everywhere.
33
+ */
34
+ export function launchEnvironmentApplies(
35
+ env: Record<string, string | undefined>,
36
+ cwd: string,
37
+ ): boolean {
38
+ const repository = env[MATE_ENV.repositoryPath];
39
+ if (!repository) return true;
40
+ const companion = env[MATE_ENV.companionPath];
41
+ const dir = real(cwd);
42
+ if (companion && inside(dir, real(companion))) return true;
43
+ const repo = real(repository);
44
+ if (inside(dir, repo)) return true;
45
+ try {
46
+ const checkout = checkoutRootOf(dir);
47
+ return !!checkout && isLinkedWorktreeOf(real(checkout), repo);
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Removes empty `MATE_*` values (a background launch sets every name, empty
55
+ * when unset), then the whole launch environment when it does not apply to
56
+ * `cwd`. Mutates `env`.
57
+ */
58
+ export function guardLaunchEnvironment(
59
+ env: Record<string, string | undefined> = process.env,
60
+ cwd: string = process.cwd(),
61
+ ): void {
62
+ for (const name of NAMES) if (env[name] === "") delete env[name];
63
+ if (launchEnvironmentApplies(env, cwd)) return;
64
+ for (const name of NAMES) delete env[name];
65
+ }
@@ -0,0 +1,136 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ import { mateHome } from "./runtime-directory";
5
+
6
+ /**
7
+ * Record and API access for Mate OpenCode servers: one detached `opencode serve`
8
+ * per Working Repository that keeps `mate opencode -- --bg` sessions running.
9
+ * Shared by the CLI (start, stop) and the plugin inside the server (idle stop).
10
+ */
11
+
12
+ /** Set to `1` in a Mate OpenCode server's environment, never in a TUI or `run`. */
13
+ export const MATE_OPENCODE_SERVER = "MATE_OPENCODE_SERVER";
14
+ /** Read once by `opencode serve` at start. */
15
+ export const OPENCODE_SERVER_PASSWORD = "OPENCODE_SERVER_PASSWORD";
16
+ /** Read by an `opencode --server` client. */
17
+ export const OPENCODE_PASSWORD = "OPENCODE_PASSWORD";
18
+
19
+ export interface OpenCodeServerRecord {
20
+ url: string;
21
+ pid: number;
22
+ /** Identifies the launch environment and guidance the server started with. */
23
+ stamp: string;
24
+ startedAt: string;
25
+ version?: string;
26
+ }
27
+
28
+ export function openCodeServersDir(homeDir?: string): string {
29
+ return path.join(mateHome(homeDir), "opencode-servers");
30
+ }
31
+
32
+ /** `<dir>/<repository id with "/" as "_">`, without extension. */
33
+ export function serverFileBase(repositoryId: string, dir = openCodeServersDir()): string {
34
+ return path.join(dir, repositoryId.replaceAll(/[/\\:]/g, "_"));
35
+ }
36
+
37
+ function isRecord(value: unknown): value is OpenCodeServerRecord {
38
+ if (!value || typeof value !== "object") return false;
39
+ const entry = value as Record<string, unknown>;
40
+ return (
41
+ typeof entry.url === "string" &&
42
+ typeof entry.pid === "number" &&
43
+ typeof entry.stamp === "string" &&
44
+ typeof entry.startedAt === "string"
45
+ );
46
+ }
47
+
48
+ /** Missing or unreadable reads as none. */
49
+ export async function readServerRecord(base: string): Promise<OpenCodeServerRecord | null> {
50
+ try {
51
+ const parsed: unknown = JSON.parse(await fs.readFile(`${base}.json`, "utf8"));
52
+ return isRecord(parsed) ? parsed : null;
53
+ } catch {
54
+ return null;
55
+ }
56
+ }
57
+
58
+ export async function readServerPassword(base: string): Promise<string | null> {
59
+ try {
60
+ return (await fs.readFile(`${base}.key`, "utf8")).trim() || null;
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ /** Removes the record files of the server with `pid`; a newer server's record stays. */
67
+ export async function removeServerRecordOf(pid: number, dir = openCodeServersDir()): Promise<void> {
68
+ const names = await fs.readdir(dir).catch(() => [] as string[]);
69
+ await Promise.all(
70
+ names
71
+ .filter((name) => name.endsWith(".json"))
72
+ .map(async (name) => {
73
+ const base = path.join(dir, name.slice(0, -".json".length));
74
+ if ((await readServerRecord(base))?.pid !== pid) return;
75
+ await Promise.all([".json", ".key"].map((ext) => fs.rm(`${base}${ext}`, { force: true })));
76
+ }),
77
+ );
78
+ }
79
+
80
+ export function processAlive(pid: number): boolean {
81
+ try {
82
+ process.kill(pid, 0);
83
+ return true;
84
+ } catch (error) {
85
+ // EPERM: alive but owned by someone else.
86
+ return (error as NodeJS.ErrnoException).code === "EPERM";
87
+ }
88
+ }
89
+
90
+ export type Fetch = (url: string, init?: RequestInit) => Promise<Response>;
91
+
92
+ function authHeaders(password: string): Record<string, string> {
93
+ return { authorization: `Basic ${Buffer.from(`opencode:${password}`).toString("base64")}` };
94
+ }
95
+
96
+ /**
97
+ * Ids of the sessions with a running execution in this server, or null when
98
+ * it does not answer.
99
+ */
100
+ export async function activeSessions(
101
+ url: string,
102
+ password: string,
103
+ fetcher: Fetch = fetch,
104
+ ): Promise<string[] | null> {
105
+ try {
106
+ const response = await fetcher(`${url}/api/session/active`, {
107
+ headers: authHeaders(password),
108
+ signal: AbortSignal.timeout(2000),
109
+ });
110
+ if (!response.ok) return null;
111
+ const body = (await response.json()) as { data?: Record<string, unknown> };
112
+ return Object.keys(body.data ?? {});
113
+ } catch {
114
+ return null;
115
+ }
116
+ }
117
+
118
+ export type InterruptOutcome = "interrupted" | "idle" | "unknown-session";
119
+
120
+ /** Interrupts the session's running turn; throws when the server does not answer. */
121
+ export async function interruptSession(
122
+ url: string,
123
+ password: string,
124
+ id: string,
125
+ fetcher: Fetch = fetch,
126
+ ): Promise<InterruptOutcome> {
127
+ const response = await fetcher(`${url}/api/session/${encodeURIComponent(id)}/interrupt`, {
128
+ method: "POST",
129
+ headers: authHeaders(password),
130
+ signal: AbortSignal.timeout(5000),
131
+ });
132
+ if (response.status === 404) return "unknown-session";
133
+ if (!response.ok) throw new Error(`OpenCode server answered ${response.status}`);
134
+ const body = (await response.json()) as { interrupted?: boolean };
135
+ return body.interrupted ? "interrupted" : "idle";
136
+ }
@@ -6,6 +6,7 @@ import { parse, stringify } from "yaml";
6
6
 
7
7
  import { MATE_ENV } from "./env-names";
8
8
  import { FRAMEWORK_NAME } from "./framework";
9
+ import { checkoutAt, liveCheckouts, namesOtherCheckout } from "./git-layout";
9
10
  import { findRepoLocalRegistryFileSync, repoLocalDirPath } from "./repo-local";
10
11
 
11
12
  /** Generated projection files, directly under the repo-local `.mate/`. */
@@ -204,21 +205,54 @@ export interface ResolvedProjection extends MateProjection {
204
205
  repoRoot: string;
205
206
  /** Recorded, never judged here: the verdict needs inputs this module lacks. */
206
207
  stamp: string;
208
+ /**
209
+ * Set when a linked worktree borrows another Checkout's projection (design
210
+ * Decision 9): the lender's root, which `repoRoot` also names. `repositoryPath`
211
+ * is then the worktree's root, the Checkout the session serves.
212
+ */
213
+ borrowedFrom?: string;
214
+ }
215
+
216
+ /** The Checkout a projection serves: the borrowing worktree, else the folder it was found in. */
217
+ export function projectionCheckout(projection: ResolvedProjection): string {
218
+ return projection.borrowedFrom ? projection.repositoryPath : projection.repoRoot;
219
+ }
220
+
221
+ function projectionAt(root: string): ResolvedProjection | null {
222
+ const file = readProjectionFile(root);
223
+ return file ? { repoRoot: root, stamp: file.stamp, ...file.projection } : null;
224
+ }
225
+
226
+ /**
227
+ * The projection a linked worktree with none of its own borrows: the main
228
+ * worktree's, else the first live linked worktree's by record name. The
229
+ * lender's companion, ID and Graphify output stay; `repositoryPath` becomes
230
+ * the worktree.
231
+ */
232
+ function borrowedProjection(cwd: string): ResolvedProjection | null {
233
+ const checkout = checkoutAt(cwd);
234
+ if (checkout?.layout.kind !== "linked") return null;
235
+ for (const lender of liveCheckouts(checkout.layout.commonDir)) {
236
+ if (lender === checkout.root) continue;
237
+ const lent = projectionAt(lender);
238
+ if (lent) return { ...lent, repositoryPath: checkout.root, borrowedFrom: lender };
239
+ }
240
+ return null;
207
241
  }
208
242
 
209
243
  /**
210
244
  * Synchronous, paths only, so a hook or shell that cannot await can use it.
211
245
  * Anchored to the directory holding the repo-local `registry.yaml` rather than
212
246
  * walking independently for `projection.yaml`, so it cannot resolve a
213
- * projection belonging to a different ancestor than the registry does. The
247
+ * projection belonging to a different ancestor than the registry does. A
248
+ * projection copied from another Checkout of the clone is that Checkout's, so
249
+ * a linked worktree borrows instead, as it does with none of its own. The
214
250
  * projected `companionPath` is not stat-ed: a reader that needs the companion
215
251
  * to exist fails in its own terms.
216
252
  */
217
253
  export function resolveProjection(cwd: string): ResolvedProjection | null {
218
254
  const found = findRepoLocalRegistryFileSync(cwd);
219
- if (!found) return null;
220
-
221
- const file = readProjectionFile(found.repoRoot);
222
- if (!file) return null;
223
- return { repoRoot: found.repoRoot, stamp: file.stamp, ...file.projection };
255
+ const own = found ? projectionAt(found.repoRoot) : null;
256
+ if (own && !namesOtherCheckout(own.repoRoot, own.repositoryPath)) return own;
257
+ return borrowedProjection(cwd);
224
258
  }
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
 
4
4
  import { FRAMEWORK_NAME } from "./framework";
5
+ import { readGitLayout } from "./git-layout";
5
6
 
6
7
  export const repoLocalDirName = () => `.${FRAMEWORK_NAME}`;
7
8
 
@@ -29,13 +30,17 @@ export function companionLinkPath(repoPath: string): string {
29
30
 
30
31
  /**
31
32
  * `cwd` and each of its ancestors, nearest first, ending at the filesystem
32
- * root. Shared by the async and sync registry walks so the two cannot land on
33
+ * root or after a linked worktree's root, so a worktree nested in the main
34
+ * worktree never reads the main worktree's `.mate/`. A main worktree or a
35
+ * submodule walks on, so a submodule still resolves to the outer repository.
36
+ * Shared by the async and sync registry walks so the two cannot land on
33
37
  * different ancestors.
34
38
  */
35
39
  export function* ancestorDirectories(cwd: string): Generator<string> {
36
40
  let dir = path.resolve(cwd);
37
41
  for (;;) {
38
42
  yield dir;
43
+ if (readGitLayout(dir)?.kind === "linked") return;
39
44
  const parent = path.dirname(dir);
40
45
  if (parent === dir) return;
41
46
  dir = parent;
@@ -0,0 +1,28 @@
1
+ import { isDirectory, mainWorktreeOf, readGitLayout } from "./git-layout";
2
+
3
+ /**
4
+ * The other Checkout whose Claude wrap serves sessions in the Checkout at
5
+ * `root` (design Decisions 1 and 12), or null when it serves itself. Claude
6
+ * Code reads a linked worktree's hooks, skills and MCP servers from its main
7
+ * worktree as well as from the worktree, so a non-bare clone's main worktree
8
+ * serves its linked worktrees. On Windows, in a bare clone's worktrees, in a
9
+ * main worktree and outside Git, the Checkout serves itself. File reads only.
10
+ */
11
+ export function otherServingClaudeWrapRoot(
12
+ root: string,
13
+ platform: NodeJS.Platform = process.platform,
14
+ ): string | null {
15
+ if (platform === "win32") return null;
16
+ const layout = readGitLayout(root);
17
+ if (layout?.kind !== "linked") return null;
18
+ const main = mainWorktreeOf(layout.commonDir);
19
+ return main && isDirectory(main) ? main : null;
20
+ }
21
+
22
+ /** The Checkout whose Claude wrap serves the one at `root`: another, else `root` itself. */
23
+ export function servingClaudeWrapRoot(
24
+ root: string,
25
+ platform: NodeJS.Platform = process.platform,
26
+ ): string {
27
+ return otherServingClaudeWrapRoot(root, platform) ?? root;
28
+ }
@@ -3,7 +3,7 @@ import fs from "node:fs";
3
3
  import { FRAMEWORK_NAME } from "./framework";
4
4
  import { physicalPath } from "./physical-path";
5
5
  import { policyDocument, readCompanionPolicy } from "./policy";
6
- import { resolveProjection } from "./projection";
6
+ import { projectionCheckout, resolveProjection } from "./projection";
7
7
 
8
8
  /** Readers reject any other version, so a changed reply fails closed instead of being misread. */
9
9
  export const SESSION_CONTEXT_PROTOCOL = 1;
@@ -78,12 +78,13 @@ export function resolveSessionContext(dir: string): SessionContextResult {
78
78
  }
79
79
 
80
80
  const policy = readCompanionPolicy(companionPath);
81
+ const checkoutRoot = projectionCheckout(projection);
81
82
  return {
82
83
  ok: true,
83
- checkoutRoot: projection.repoRoot,
84
+ checkoutRoot,
84
85
  context: {
85
86
  companionPath,
86
- repositoryPath: realDirectory(projection.repoRoot) ?? projection.repoRoot,
87
+ repositoryPath: realDirectory(checkoutRoot) ?? checkoutRoot,
87
88
  repositoryId: projection.repositoryId,
88
89
  policyJson: policyDocument(policy),
89
90
  },