@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
@@ -6,6 +6,7 @@ import { parse } from "yaml";
6
6
  import { CompanionRegistryStore } from "./companion-registry-store";
7
7
  import { ConfigStore } from "./config-store";
8
8
  import { GlobalConfigStore } from "./global-config-store";
9
+ import { entryAtCheckout } from "./registry-checkouts";
9
10
  import {
10
11
  backfillCompanionRegistration,
11
12
  CompanionResolver,
@@ -36,14 +37,22 @@ export interface LaunchContext extends FrameworkContext {
36
37
  repositoryId: string;
37
38
  }
38
39
 
39
- function repositoryFromEnvironment(): LinkedRepository | undefined {
40
+ /**
41
+ * The launch's repository as `folder` sees it: the launch environment's ID,
42
+ * at the root of the Checkout holding `folder` when that is another Checkout
43
+ * of `MATE_REPO_PATH`'s clone (design Decision 11), else at `MATE_REPO_PATH`.
44
+ */
45
+ export function repositoryFromEnvironment(folder: string): LinkedRepository | undefined {
40
46
  const repositoryPath = process.env.MATE_REPO_PATH;
41
47
  if (!repositoryPath) return undefined;
42
48
 
43
- return {
44
- id: process.env.MATE_REPO_ID ?? path.basename(path.resolve(repositoryPath)),
45
- path: path.resolve(repositoryPath),
46
- };
49
+ return entryAtCheckout(
50
+ {
51
+ id: process.env.MATE_REPO_ID ?? path.basename(path.resolve(repositoryPath)),
52
+ path: path.resolve(repositoryPath),
53
+ },
54
+ folder,
55
+ );
47
56
  }
48
57
 
49
58
  // Builds a FrameworkContext from a known companion path — wires up the config
@@ -156,7 +165,7 @@ export async function resolveFrameworkContext(
156
165
  ): Promise<FrameworkContext> {
157
166
  const envCompanionPath = process.env.MATE_ARTIFACT_PATH;
158
167
  if (envCompanionPath) {
159
- const repository = repositoryFromEnvironment() ?? (await findRepoLocalLinkedRepository(cwd));
168
+ const repository = repositoryFromEnvironment(cwd) ?? (await findRepoLocalLinkedRepository(cwd));
160
169
  return withResolvedHub(
161
170
  makeContext(path.resolve(envCompanionPath), "env", repository ?? undefined),
162
171
  );
@@ -201,7 +210,7 @@ export async function resolveForLaunch(
201
210
  const context = await withResolvedHub(makeContext(path.resolve(envCompanionPath), "env"));
202
211
  return { ...context, repositoryId: "" };
203
212
  }
204
- const repository = repositoryFromEnvironment() ?? (await findRepoLocalLinkedRepository(cwd));
213
+ const repository = repositoryFromEnvironment(cwd) ?? (await findRepoLocalLinkedRepository(cwd));
205
214
  const repositoryId = process.env.MATE_REPO_ID ?? repository?.id ?? "";
206
215
  const context = await withResolvedHub(
207
216
  makeContext(path.resolve(envCompanionPath), "env", repository ?? undefined),
@@ -220,7 +229,8 @@ export async function resolveForLaunch(
220
229
  }
221
230
 
222
231
  if (resolution.match) {
223
- const repository = (await findRepoLocalLinkedRepository(cwd)) ?? undefined;
232
+ let repository = (await findRepoLocalLinkedRepository(cwd)) ?? undefined;
233
+ let repositoryId = resolution.match.repositoryId;
224
234
  if (scope === "companion") {
225
235
  const context = await withResolvedHub(
226
236
  makeContext(resolution.match.companionPath, "working-repo"),
@@ -228,16 +238,18 @@ export async function resolveForLaunch(
228
238
  return { ...context, repositoryId: "" };
229
239
  }
230
240
  if (repository) {
231
- await backfillCompanionRegistration(resolution.match.companionPath, repository);
241
+ /** A merge of hand-linked worktrees gives this Checkout the kept ID (design Decision 5). */
242
+ const kept = await backfillCompanionRegistration(resolution.match.companionPath, repository);
243
+ if (kept !== repository.id) {
244
+ repository = { ...repository, id: kept };
245
+ repositoryId = kept;
246
+ }
232
247
  await projectWorkingRepositoryBestEffort(resolution.match.companionPath, repository);
233
248
  }
234
249
  const context = await withResolvedHub(
235
250
  makeContext(resolution.match.companionPath, "working-repo", repository),
236
251
  );
237
- return {
238
- ...context,
239
- repositoryId: resolution.match.repositoryId,
240
- };
252
+ return { ...context, repositoryId };
241
253
  }
242
254
 
243
255
  if (scope === "companion") {
@@ -268,7 +280,7 @@ export async function resolveForCapability(
268
280
  ): Promise<LaunchContext> {
269
281
  const envCompanionPath = process.env.MATE_ARTIFACT_PATH;
270
282
  if (envCompanionPath) {
271
- const repository = repositoryFromEnvironment() ?? (await findRepoLocalLinkedRepository(cwd));
283
+ const repository = repositoryFromEnvironment(cwd) ?? (await findRepoLocalLinkedRepository(cwd));
272
284
  const ctx = await withResolvedHub(
273
285
  makeContext(path.resolve(envCompanionPath), "env", repository ?? undefined),
274
286
  );
@@ -52,6 +52,17 @@ export class GlobalConfigStore extends YamlFileStore<GlobalConfig> {
52
52
  }
53
53
  }
54
54
 
55
+ /** Drops one entry; `false` when the path was not registered. */
56
+ async unregister(companionPath: string): Promise<boolean> {
57
+ const resolved = path.resolve(companionPath);
58
+ const config = await this.load();
59
+ const kept = config.companions.filter((c) => path.resolve(c.path) !== resolved);
60
+ if (kept.length === config.companions.length) return false;
61
+ config.companions = kept;
62
+ await this.save(config);
63
+ return true;
64
+ }
65
+
55
66
  /**
56
67
  * One-time/idempotent hygiene pass: drops entries whose path is not a
57
68
  * directory on disk (stale test-fixture pollution, removed companions).
@@ -3,6 +3,8 @@ import { FRAMEWORK_NAME } from "../../framework";
3
3
  import type { AdapterContext, LaunchAdapter } from "./adapters/base";
4
4
  import { ClaudeAdapter } from "./adapters/claude";
5
5
  import { OpenCodeAdapter } from "./adapters/opencode";
6
+ import { inheritedWrapRuntimes } from "./checkout-adoption";
7
+ import { entryAtCheckout } from "./registry-checkouts";
6
8
  import { CompanionStore } from "./repository-link";
7
9
  import { resolveForLaunch, type LaunchContext } from "./framework-context";
8
10
  import { prepareSession, type PrepareResult, type PrepareRuntime } from "./session-prepare";
@@ -45,7 +47,8 @@ export const launcherDeps = {
45
47
  function report(result: PrepareResult): void {
46
48
  const wrapped = result.steps.find((step) => step.step === "working-target");
47
49
  if (wrapped?.outcome === "ok" && wrapped.detail !== "current") {
48
- const runtime = wrapped.runtimes?.includes("claude") ? "Claude" : "OpenCode";
50
+ const names = { claude: "Claude", opencode: "OpenCode" } as const;
51
+ const runtime = (wrapped.runtimes ?? [result.runtime]).map((name) => names[name]).join(" and ");
49
52
  process.stderr.write(
50
53
  `${FRAMEWORK_NAME}: wrapped ${result.repositoryId} for ${runtime}: ${wrapped.detail}\n`,
51
54
  );
@@ -55,6 +58,11 @@ function report(result: PrepareResult): void {
55
58
  }
56
59
  }
57
60
 
61
+ /** A registry entry seen from the launch folder: a launch in another Checkout of its clone starts there. */
62
+ function atCheckout(entry: LinkedRepository | undefined): LinkedRepository | undefined {
63
+ return entry && entryAtCheckout(entry, process.cwd());
64
+ }
65
+
58
66
  export class FrameworkLauncher {
59
67
  private readonly adapters = new Map<string, LaunchAdapter>(
60
68
  [new ClaudeAdapter(), new OpenCodeAdapter()].map((adapter) => [adapter.toolName, adapter]),
@@ -81,6 +89,11 @@ export class FrameworkLauncher {
81
89
 
82
90
  const prepared = await launcherDeps.prepareSession({
83
91
  runtime: request.tool as PrepareRuntime,
92
+ ...(state.repository
93
+ ? {
94
+ adoptedRuntimes: await inheritedWrapRuntimes(state.companionPath, state.repository),
95
+ }
96
+ : {}),
84
97
  companionPath: state.companionPath,
85
98
  repository: state.repository,
86
99
  mode: "attended",
@@ -114,7 +127,7 @@ export class FrameworkLauncher {
114
127
  const repository =
115
128
  scope === "companion"
116
129
  ? undefined
117
- : (localRepository ?? (await store.getRepository(repositoryId)));
130
+ : (localRepository ?? atCheckout(await store.getRepository(repositoryId)));
118
131
  if (scope === "working-repo" && !repository) {
119
132
  throw new RepositoryNotSelectedError(`Linked repository not found: ${repositoryId}`);
120
133
  }
@@ -101,11 +101,7 @@ export async function reconcileClaudeLinks(
101
101
  const link = path.join(targetRoot, entry.name);
102
102
  const target = await linkTarget(link);
103
103
  if (target === null) continue;
104
- const record = recorded[recordKey(entry.name)];
105
- const owned = record
106
- ? (await realOrResolved(record.target)) === target
107
- : roots.some((candidate) => path.dirname(target) === candidate);
108
- if (!owned) continue;
104
+ if (!(await ownsLink(target, recorded[recordKey(entry.name)], roots))) continue;
109
105
 
110
106
  const wanted = currentRoot ? path.join(currentRoot, entry.name) : null;
111
107
  if (wanted && sourceNames.has(entry.name) && (await realOrResolved(wanted)) === target) {
@@ -140,6 +136,57 @@ export async function reconcileClaudeLinks(
140
136
  return changed ? "written" : "current";
141
137
  }
142
138
 
139
+ /**
140
+ * Mate owns a link it recorded with this target, or an unrecorded one that
141
+ * resolves into one of `roots`.
142
+ */
143
+ async function ownsLink(
144
+ target: string,
145
+ record: LinkRecord | undefined,
146
+ roots: readonly string[],
147
+ ): Promise<boolean> {
148
+ return record
149
+ ? (await realOrResolved(record.target)) === target
150
+ : roots.some((candidate) => path.dirname(target) === candidate);
151
+ }
152
+
153
+ /** Mate has linked at least one entry of `root` in the Working Repository at `repoPath`. */
154
+ export async function carriesClaudeLinks(root: ClaudeLinkRoot, repoPath: string): Promise<boolean> {
155
+ const manifest = await readManifest(repoPath).catch(() => null);
156
+ return (
157
+ manifest !== null &&
158
+ Object.keys(links(manifest, "claude", { prefix: keyPrefix(root) })).length > 0
159
+ );
160
+ }
161
+
162
+ /**
163
+ * `root`'s folder in the Working Repository is missing or holds only Mate's
164
+ * links: recorded ones, or ones resolving into a registered, current or
165
+ * projected companion.
166
+ */
167
+ export async function holdsOnlyMateLinks(
168
+ root: ClaudeLinkRoot,
169
+ repoPath: string,
170
+ companionPath: string | null,
171
+ registeredCompanionPaths: string[],
172
+ ): Promise<boolean> {
173
+ const targetRoot = path.join(path.resolve(repoPath), rootPath(root));
174
+ const existing = await fs.readdir(targetRoot, { withFileTypes: true }).catch(() => []);
175
+ if (existing.length === 0) return true;
176
+ const roots = await registeredRoots(root, repoPath, companionPath, registeredCompanionPaths);
177
+ const manifest = await readManifest(repoPath).catch(() => null);
178
+ const recorded = manifest ? links(manifest, "claude", { prefix: keyPrefix(root) }) : {};
179
+ const owned = await Promise.all(
180
+ existing.map(async (entry) => {
181
+ if (!entry.isSymbolicLink()) return false;
182
+ const target = await linkTarget(path.join(targetRoot, entry.name));
183
+ if (target === null) return false;
184
+ return ownsLink(target, recorded[`${keyPrefix(root)}${entry.name}`], roots);
185
+ }),
186
+ );
187
+ return owned.every(Boolean);
188
+ }
189
+
143
190
  function sortedEntries(records: Record<string, LinkRecord>): [string, LinkRecord][] {
144
191
  return Object.entries(records)
145
192
  .map(([key, record]): [string, LinkRecord] => [
@@ -1,7 +1,10 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
 
4
+ import { otherServingClaudeWrapRoot } from "../../runtime/serving-claude-wrap";
4
5
  import {
6
+ carriesClaudeLinks,
7
+ holdsOnlyMateLinks,
5
8
  reconcileClaudeLinks,
6
9
  removeClaudeLinks,
7
10
  type ClaudeLinkRoot,
@@ -17,13 +20,36 @@ const SKILLS: ClaudeLinkRoot = {
17
20
  .catch(() => false),
18
21
  };
19
22
 
20
- export function reconcileWorkingRepoClaudeSkillLinks(
23
+ /**
24
+ * A linked worktree served by the main worktree's Claude wrap reads the main
25
+ * worktree's skills unless it has a `.claude/skills` of its own (design
26
+ * Decision 13). While the main worktree carries the links and the worktree's
27
+ * folder is missing or holds only Mate's links, a folder there would hide the
28
+ * main worktree's skills, the operator's untracked ones included.
29
+ */
30
+ async function servedByMainWorktree(
31
+ repoPath: string,
32
+ companionPath: string | null,
33
+ registeredCompanionPaths: string[],
34
+ ): Promise<boolean> {
35
+ const serving = otherServingClaudeWrapRoot(repoPath);
36
+ if (!serving) return false;
37
+ return (
38
+ (await carriesClaudeLinks(SKILLS, serving)) &&
39
+ (await holdsOnlyMateLinks(SKILLS, repoPath, companionPath, registeredCompanionPaths))
40
+ );
41
+ }
42
+
43
+ /** Places none, and withdraws earlier ones, where the main worktree serves them. */
44
+ export async function reconcileWorkingRepoClaudeSkillLinks(
21
45
  repoPath: string,
22
46
  companionPath: string | null,
23
47
  enabled: boolean,
24
48
  registeredCompanionPaths: string[] = [],
25
49
  ): Promise<"written" | "current"> {
26
- return reconcileClaudeLinks(SKILLS, repoPath, companionPath, enabled, registeredCompanionPaths);
50
+ const placed =
51
+ enabled && !(await servedByMainWorktree(repoPath, companionPath, registeredCompanionPaths));
52
+ return reconcileClaudeLinks(SKILLS, repoPath, companionPath, placed, registeredCompanionPaths);
27
53
  }
28
54
 
29
55
  export function removeWorkingRepoClaudeSkillLinks(
@@ -37,7 +37,18 @@ export async function linkCompanion(
37
37
 
38
38
  await fs.mkdir(path.dirname(link), { recursive: true });
39
39
  if (existing !== null) await fs.unlink(link);
40
- await createLink(target, link);
40
+ try {
41
+ await createLink(target, link);
42
+ } catch (error) {
43
+ /** A concurrent Adoption of the same Checkout wrote the same link first. */
44
+ if (
45
+ (error as NodeJS.ErrnoException).code === "EEXIST" &&
46
+ (await currentTarget(link)) === target
47
+ ) {
48
+ return "current";
49
+ }
50
+ throw error;
51
+ }
41
52
  return "written";
42
53
  }
43
54
 
@@ -0,0 +1,177 @@
1
+ import path from "node:path";
2
+
3
+ import {
4
+ checkoutCommonDir,
5
+ checkoutServedFrom,
6
+ cloneAt,
7
+ isDirectory,
8
+ liveCheckouts,
9
+ mainWorktreeOf,
10
+ readGitLayout,
11
+ realPath,
12
+ } from "../../runtime/git-layout";
13
+ import type { LinkedRepository } from "./types";
14
+
15
+ /**
16
+ * The companion registry's rules for Checkouts (ADR-023): one entry per clone,
17
+ * the clone's shared Git folder recorded on it, and a deleted Registered
18
+ * Checkout handed over to another Checkout instead of dropped. File reads only,
19
+ * no `git` process.
20
+ */
21
+
22
+ /**
23
+ * The live Checkout a clone's entry moves to: the main worktree, else the
24
+ * first live linked worktree by record name. A locked worktree whose folder is
25
+ * away is never one.
26
+ */
27
+ function handoverTarget(gitCommonDir: string | undefined): string | null {
28
+ return gitCommonDir ? (liveCheckouts(gitCommonDir).next().value ?? null) : null;
29
+ }
30
+
31
+ /**
32
+ * The entry's Registered Checkout, read without writing: its folder while that
33
+ * exists, else the Checkout a registry write would hand it over to.
34
+ */
35
+ export function registeredCheckoutOf(entry: LinkedRepository): string | null {
36
+ return isDirectory(entry.path) ? entry.path : handoverTarget(entry.gitCommonDir);
37
+ }
38
+
39
+ /**
40
+ * The entry as the Checkout holding `folder` sees it: that Checkout's root as
41
+ * the path when it is another live Checkout of the entry's clone.
42
+ */
43
+ export function entryAtCheckout(entry: LinkedRepository, folder: string): LinkedRepository {
44
+ const checkout = checkoutServedFrom(entry.path, folder);
45
+ return checkout === entry.path ? entry : { ...entry, path: checkout };
46
+ }
47
+
48
+ /**
49
+ * The ID a first link from the Checkout at `root` proposes (design Decision
50
+ * 14): a linked worktree is named after its clone, the main worktree's folder,
51
+ * or a bare clone's folder without `.git`; any other folder after itself. The
52
+ * registry keeps an ID the clone's entry already has.
53
+ */
54
+ export function linkIdFor(root: string): string {
55
+ const layout = readGitLayout(root);
56
+ const clone = layout?.kind === "linked" ? cloneAt(layout.commonDir) : null;
57
+ if (!clone) return path.basename(root);
58
+ return clone.mainWorktree
59
+ ? path.basename(clone.mainWorktree)
60
+ : path.basename(clone.commonDir).replace(/\.git$/, "");
61
+ }
62
+
63
+ /** A hand-linked entry merged into its clone's kept entry. */
64
+ export interface MergedEntry {
65
+ removed: LinkedRepository;
66
+ kept: LinkedRepository;
67
+ }
68
+
69
+ export interface ReconciledRegistry {
70
+ repos: LinkedRepository[];
71
+ /** The entry the registered repository maps to. */
72
+ kept: LinkedRepository;
73
+ merged: MergedEntry[];
74
+ }
75
+
76
+ /** The clone's shared Git folder for an entry that names a live Checkout root. */
77
+ function cloneKey(entry: LinkedRepository): string | null {
78
+ return checkoutCommonDir(entry.path);
79
+ }
80
+
81
+ /** An entry of the clone whose shared Git folder is `clone`: recorded, else read from its live path. */
82
+ export function entryOfClone(entry: LinkedRepository, clone: string): boolean {
83
+ return entry.gitCommonDir === clone || (isDirectory(entry.path) && cloneKey(entry) === clone);
84
+ }
85
+
86
+ /** Entries of one clone keep one: the main worktree's (one it already named first), else the first listed. */
87
+ function mergeClones(
88
+ entries: LinkedRepository[],
89
+ handedOver: ReadonlySet<LinkedRepository>,
90
+ ): { repos: LinkedRepository[]; merged: MergedEntry[] } {
91
+ const groups = new Map<string, LinkedRepository[]>();
92
+ for (const entry of entries) {
93
+ const key = cloneKey(entry);
94
+ if (key) groups.set(key, [...(groups.get(key) ?? []), entry]);
95
+ }
96
+ const merged: MergedEntry[] = [];
97
+ for (const [key, group] of groups) {
98
+ if (group.length < 2) continue;
99
+ const main = mainWorktreeOf(key);
100
+ const atMain = group.filter((entry) => main !== null && realPath(entry.path) === main);
101
+ const kept = atMain.find((entry) => !handedOver.has(entry)) ?? atMain[0] ?? group[0]!;
102
+ for (const entry of group) if (entry !== kept) merged.push({ removed: entry, kept });
103
+ }
104
+ const removed = new Set(merged.map((entry) => entry.removed));
105
+ return { repos: entries.filter((entry) => !removed.has(entry)), merged };
106
+ }
107
+
108
+ /** An entry naming a live Checkout gets its shared Git folder; one naming a non-Git folder records none. */
109
+ function withCommonDir(entry: LinkedRepository): LinkedRepository {
110
+ const commonDir = cloneKey(entry);
111
+ if (commonDir) return { ...entry, gitCommonDir: commonDir };
112
+ const layout = readGitLayout(entry.path);
113
+ if (layout && layout.kind !== "own") return entry;
114
+ const { gitCommonDir: _dropped, ...rest } = entry;
115
+ return rest;
116
+ }
117
+
118
+ /**
119
+ * One registry write's rules, in order: hand over or drop dead entries, merge
120
+ * entries of one clone, reuse the entry of `repository`'s clone or upsert by
121
+ * ID, then fill each live entry's shared Git folder.
122
+ */
123
+ export function reconcileRegistry(
124
+ entries: readonly LinkedRepository[],
125
+ repository: LinkedRepository,
126
+ ): ReconciledRegistry {
127
+ const handedOver = new Set<LinkedRepository>();
128
+ const live = entries.flatMap((entry) => {
129
+ if (isDirectory(entry.path)) return [entry];
130
+ const target = handoverTarget(entry.gitCommonDir);
131
+ if (!target) return [];
132
+ const moved = { ...entry, path: target };
133
+ handedOver.add(moved);
134
+ return [moved];
135
+ });
136
+
137
+ const { repos, merged } = mergeClones(live, handedOver);
138
+ const key = checkoutCommonDir(repository.path);
139
+ let keptIndex = key ? repos.findIndex((entry) => cloneKey(entry) === key) : -1;
140
+ if (keptIndex < 0) {
141
+ const entry = { id: repository.id, path: repository.path };
142
+ keptIndex = repos.findIndex((candidate) => candidate.id === repository.id);
143
+ if (keptIndex >= 0) repos[keptIndex] = entry;
144
+ else keptIndex = repos.push(entry) - 1;
145
+ }
146
+
147
+ const filled = repos.map(withCommonDir);
148
+ const byOriginal = new Map(repos.map((entry, index) => [entry, filled[index]!]));
149
+ return {
150
+ repos: filled,
151
+ kept: filled[keptIndex]!,
152
+ merged: merged.map(({ removed, kept }) => ({ removed, kept: byOriginal.get(kept) ?? kept })),
153
+ };
154
+ }
155
+
156
+ /**
157
+ * The registry already lists `repository` as a write would leave it: for a Git
158
+ * Checkout, exactly one entry of its clone, with its ID, a live path and the
159
+ * clone's shared Git folder; otherwise its ID at its path.
160
+ */
161
+ export function registryListsRepository(
162
+ entries: readonly LinkedRepository[],
163
+ repository: LinkedRepository,
164
+ ): boolean {
165
+ const key = checkoutCommonDir(repository.path);
166
+ if (!key) {
167
+ return entries.some((entry) => entry.id === repository.id && entry.path === repository.path);
168
+ }
169
+ const ofClone = entries.filter((entry) => entryOfClone(entry, key));
170
+ const [only] = ofClone;
171
+ return (
172
+ ofClone.length === 1 &&
173
+ only!.id === repository.id &&
174
+ only!.gitCommonDir === key &&
175
+ isDirectory(only!.path)
176
+ );
177
+ }