@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
@@ -10,8 +10,12 @@ import type { WrapRuntime } from "../../runtime/runtime-document-manifest";
10
10
  import { readWrapState, WRAP_RUNTIMES } from "../../runtime/wrap-state";
11
11
  import { cleanupWorkingRepository } from "../../tools/setup/working-repo-cleanup";
12
12
  import { locateChange } from "../change-layout";
13
+ import { workingRepoGit } from "../delivery/branches";
14
+ import { mergeGit } from "../delivery/merge-git";
13
15
  import { type DeliveryRecord, readDeliveryRecord } from "../delivery/record";
14
16
  import {
17
+ listRefsWith,
18
+ mergeProbeWith,
15
19
  newBranchBase,
16
20
  resolveDeliveryBranch,
17
21
  worktreeAddArgs,
@@ -20,6 +24,7 @@ import {
20
24
  import { scopedRepositories } from "../openspec-scopes";
21
25
  import { attendedLockOptions } from "../orchestrator/companion-git-sync";
22
26
  import {
27
+ findRepoLocalLinkTo,
23
28
  readCompanionRegistry,
24
29
  writeRepoLocalRegistryEntry,
25
30
  } from "../orchestrator/repository-link";
@@ -266,21 +271,34 @@ async function listWorktrees(git: GitRunner, repo: string): Promise<WorktreeEntr
266
271
  );
267
272
  }
268
273
 
269
- /** The first existing checkout linked to the companion whose `origin` is the repository. */
274
+ interface LinkedLookup {
275
+ linked: LinkedRepository | null;
276
+ /** Registered paths that no longer exist. */
277
+ missing: string[];
278
+ }
279
+
280
+ /**
281
+ * The first checkout linked to the companion whose `origin` is the repository: an
282
+ * existing registered one, else the checkout holding `cwd` when its repo-local link
283
+ * names the companion, so an entry left naming a removed folder does not hide it.
284
+ */
270
285
  async function linkedCheckout(
271
286
  companionPath: string,
272
287
  repository: string,
273
288
  git: GitRunner,
274
- ): Promise<LinkedRepository | null> {
289
+ cwd: string,
290
+ ): Promise<LinkedLookup> {
275
291
  let repos: LinkedRepository[] = [];
276
292
  try {
277
293
  repos = (await readCompanionRegistry(companionPath)).repos;
278
294
  } catch (error) {
279
295
  if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
280
296
  }
297
+ const present = await Promise.all(repos.map((repo) => exists(repo.path)));
298
+ const current = await findRepoLocalLinkTo(cwd, companionPath);
299
+ const candidates = [...repos.filter((_, index) => present[index]), ...(current ? [current] : [])];
281
300
  const identities = await Promise.all(
282
- repos.map(async (repo) => {
283
- if (!(await exists(repo.path))) return null;
301
+ candidates.map(async (repo) => {
284
302
  // Raw config, not `remote get-url`, so `insteadOf` rewrites do not change the identity.
285
303
  const remote = await git(repo.path, ["config", "--get", "remote.origin.url"]);
286
304
  return remote.code === 0 ? identityOf(remote.stdout.trim()) : null;
@@ -290,7 +308,10 @@ async function linkedCheckout(
290
308
  const index = identities.findIndex(
291
309
  (identity) => identity?.toLowerCase() === repository.toLowerCase(),
292
310
  );
293
- return index === -1 ? null : repos[index]!;
311
+ return {
312
+ linked: index === -1 ? null : candidates[index]!,
313
+ missing: repos.filter((_, at) => !present[at]).map((repo) => repo.path),
314
+ };
294
315
  }
295
316
 
296
317
  interface Plan {
@@ -346,11 +367,13 @@ async function planWorktrees(
346
367
  companionPath: string,
347
368
  target: Target,
348
369
  git: GitRunner,
370
+ cwd: string,
371
+ ticket?: string,
349
372
  ): Promise<{ plans: Plan[]; diagnostics: string[]; warnings: string[] }> {
350
373
  const warnings: string[] = [];
351
374
  const checked = await Promise.all(
352
375
  target.repositories.map((repository) =>
353
- planRepository(companionPath, target.id, repository, git, warnings),
376
+ planRepository(companionPath, target.id, repository, git, cwd, warnings, ticket),
354
377
  ),
355
378
  );
356
379
  return {
@@ -366,14 +389,19 @@ async function planRepository(
366
389
  worksetId: string,
367
390
  repository: string,
368
391
  git: GitRunner,
392
+ cwd: string,
369
393
  warnings: string[],
394
+ ticket?: string,
370
395
  ): Promise<Plan | string[]> {
371
- const linked = await linkedCheckout(companionPath, repository, git);
396
+ const { linked, missing } = await linkedCheckout(companionPath, repository, git, cwd);
372
397
  if (!linked) {
373
398
  // An identity problem outranks the missing link.
374
399
  const identity = await resolveWorksetBranch(companionPath, worksetId, repository);
375
400
  if (identity.id === null) return identity.diagnostics.map((line) => `${repository}: ${line}`);
376
- return [`${repository}: not linked to ${companionPath} on this machine`];
401
+ const why = missing.map((entry) => `registered path ${entry} does not exist`).join("; ");
402
+ return [
403
+ `${repository}: not linked to ${companionPath} on this machine${why ? ` (${why})` : ""}`,
404
+ ];
377
405
  }
378
406
  // Resolved after the fetch, so a branch pushed elsewhere counts as existing.
379
407
  const fetched = await fetchOrigin(git, linked.path);
@@ -384,11 +412,27 @@ async function planRepository(
384
412
  }
385
413
  const hasRef = async (ref: string) =>
386
414
  (await git(linked.path, ["rev-parse", "--verify", "--quiet", ref])).code === 0;
387
- const resolution = await resolveDeliveryBranch({ companionPath, repository, hasRef, worksetId });
415
+ const resolution = await resolveDeliveryBranch({
416
+ companionPath,
417
+ repository,
418
+ hasRef,
419
+ listRefs: listRefsWith(async (args) => {
420
+ const listed = await git(linked.path, args);
421
+ return listed.code === 0 ? listed.stdout : null;
422
+ }),
423
+ mergeProbe: mergeProbeWith(
424
+ mergeGit(linked.path),
425
+ await workingRepoGit(linked.path).defaultBranch(),
426
+ ),
427
+ worksetId,
428
+ ...(ticket ? { ticket } : {}),
429
+ });
388
430
  const { branch, source } = resolution;
389
431
  if (branch === null || source === null) {
390
432
  return resolution.diagnostics.map((line) => `${repository}: ${line}`);
391
433
  }
434
+ // A resolved branch's diagnostics only inform, e.g. a ticket that names nothing.
435
+ warnings.push(...resolution.diagnostics.map((line) => `${repository}: ${line}`));
392
436
  const entries = await listWorktrees(git, linked.path);
393
437
  const main = entries?.[0];
394
438
  if (!main) return [`${repository}: cannot list the worktrees of ${linked.path}`];
@@ -403,19 +447,29 @@ async function planRepository(
403
447
  `${repository}: ${stale.path} is a stale worktree entry (${stale.stale}); remove any folder left there, run \`git worktree prune\` in ${main.path}, then retry`,
404
448
  ];
405
449
  }
450
+ const plan = { repository, repositoryId: linked.id, checkout: main.path, branch, source };
451
+ const elsewhere = entries.find((entry) => entry.branch === branch && entry.path !== target);
452
+ const inherited = resolution.inheritedFrom.join(", ");
453
+ // An inherited branch is the dependency's worktree; one branch has one worktree.
454
+ if (elsewhere && inherited && !atTarget) {
455
+ if (elsewhere.path === main.path) {
456
+ return [
457
+ `${repository}: ${branch}, inherited from ${inherited}, is checked out in ${main.path}; work there or switch it to another branch`,
458
+ ];
459
+ }
460
+ warnings.push(
461
+ `${repository}: ${branch} is inherited from ${inherited}; reusing its worktree at ${elsewhere.path}`,
462
+ );
463
+ return { ...plan, target: elsewhere.path, reuse: true };
464
+ }
406
465
  const reuse = atTarget?.branch === branch;
407
466
  if (!reuse && (atTarget || (await exists(target)))) {
408
467
  return [`${repository}: ${target} exists and is not a worktree of ${repository} on ${branch}`];
409
468
  }
410
- const elsewhere = entries.find((entry) => entry.branch === branch && entry.path !== target);
411
469
  if (elsewhere) return [`${repository}: ${branch} is already checked out at ${elsewhere.path}`];
412
470
  return {
413
- repository,
414
- repositoryId: linked.id,
415
- checkout: main.path,
471
+ ...plan,
416
472
  target,
417
- branch,
418
- source,
419
473
  base: source === "new" ? await newBranchBase(hasRef) : undefined,
420
474
  reuse,
421
475
  };
@@ -502,6 +556,8 @@ async function missingEnvFiles(
502
556
 
503
557
  export interface CreateWorktreesOptions {
504
558
  install: boolean;
559
+ /** Names a new Delivery Branch `workset/<TICKET>-<id>`; an existing or recorded one wins. */
560
+ ticket?: string;
505
561
  /** Pass the installer's output through; false discards it, as `--json` needs. */
506
562
  streamInstall: boolean;
507
563
  }
@@ -548,7 +604,14 @@ async function createTargetWorktrees(
548
604
  }
549
605
  const worksetId = target.id;
550
606
  const git = deps.git ?? runGit;
551
- const { plans, diagnostics, warnings } = await planWorktrees(companionPath, target, git);
607
+ const cwd = (deps.cwd ?? process.cwd)();
608
+ const { plans, diagnostics, warnings } = await planWorktrees(
609
+ companionPath,
610
+ target,
611
+ git,
612
+ cwd,
613
+ options.ticket,
614
+ );
552
615
  if (diagnostics.length > 0) {
553
616
  return { workset: worksetId, ok: false, repositories: [], diagnostics, warnings };
554
617
  }
@@ -731,7 +794,12 @@ async function pruneRepository(
731
794
  deps: WorktreeDeps,
732
795
  result: PruneResult,
733
796
  ): Promise<void> {
734
- const linked = await linkedCheckout(companionPath, repository, git);
797
+ const { linked } = await linkedCheckout(
798
+ companionPath,
799
+ repository,
800
+ git,
801
+ (deps.cwd ?? process.cwd)(),
802
+ );
735
803
  if (!linked) return;
736
804
  const entries = await listWorktrees(git, linked.path);
737
805
  const main = entries?.[0];
@@ -0,0 +1,145 @@
1
+ import type { Context } from "@opencode/plugin/promise/plugin";
2
+
3
+ import {
4
+ MATE_OPENCODE_SERVER,
5
+ OPENCODE_PASSWORD,
6
+ OPENCODE_SERVER_PASSWORD,
7
+ removeServerRecordOf,
8
+ } from "../runtime/opencode-server-record";
9
+
10
+ /**
11
+ * The plugin's share of a Mate OpenCode server (`MATE_OPENCODE_SERVER=1`):
12
+ * keep the server password out of every shell, and stop the server after an
13
+ * hour without a running step. Inert in any other OpenCode process.
14
+ */
15
+
16
+ const IDLE_MS = 60 * 60 * 1000;
17
+ const CHECK_MS = 60 * 1000;
18
+
19
+ export interface MateServerDeps {
20
+ now: () => number;
21
+ exit: (code: number) => void;
22
+ /** Runs `check` every `ms` without keeping the process alive. */
23
+ every: (check: () => void, ms: number) => void;
24
+ removeRecord: (pid: number) => Promise<unknown>;
25
+ pid: number;
26
+ }
27
+
28
+ const defaultDeps: MateServerDeps = {
29
+ now: Date.now,
30
+ exit: (code) => process.exit(code),
31
+ every: (check, ms) => setInterval(check, ms).unref(),
32
+ removeRecord: (pid) => removeServerRecordOf(pid),
33
+ pid: process.pid,
34
+ };
35
+
36
+ function runsInMateServer(env: NodeJS.ProcessEnv = process.env): boolean {
37
+ return env[MATE_OPENCODE_SERVER] === "1";
38
+ }
39
+
40
+ /** `opencode serve` reads its password once at start; nothing after needs it. */
41
+ function dropPasswords(env: Record<string, string | undefined>): void {
42
+ delete env[OPENCODE_SERVER_PASSWORD];
43
+ delete env[OPENCODE_PASSWORD];
44
+ }
45
+
46
+ interface StepEvent {
47
+ type?: string;
48
+ data?: { sessionID?: string; finish?: string };
49
+ }
50
+
51
+ /** One per process: plugins set up per location, the server stops as a whole. */
52
+ class IdleStop {
53
+ private readonly running = new Set<string>();
54
+ private lastStep: number;
55
+ private started = false;
56
+ private stopping = false;
57
+ readonly onStop = new Set<() => Promise<unknown>>();
58
+
59
+ constructor(private readonly deps: MateServerDeps) {
60
+ this.lastStep = deps.now();
61
+ }
62
+
63
+ start(): void {
64
+ if (this.started) return;
65
+ this.started = true;
66
+ this.deps.every(() => void this.check(), CHECK_MS);
67
+ }
68
+
69
+ /** A step ending in `tool-calls` is followed by the next one: the turn still runs. */
70
+ observe(event: StepEvent): void {
71
+ const id = event.data?.sessionID;
72
+ if (!id || !event.type) return;
73
+ if (event.type === "session.deleted") {
74
+ this.running.delete(id);
75
+ return;
76
+ }
77
+ if (!event.type.startsWith("session.step.")) return;
78
+ this.lastStep = this.deps.now();
79
+ if (event.type === "session.step.started") this.running.add(id);
80
+ const finished =
81
+ event.type === "session.step.failed" ||
82
+ (event.type === "session.step.ended" && event.data?.finish !== "tool-calls");
83
+ if (finished) this.running.delete(id);
84
+ }
85
+
86
+ async check(): Promise<void> {
87
+ if (this.stopping || this.running.size > 0) return;
88
+ if (this.deps.now() - this.lastStep < IDLE_MS) return;
89
+ this.stopping = true;
90
+ await Promise.all([...this.onStop].map((stop) => stop().catch(() => {})));
91
+ await this.deps.removeRecord(this.deps.pid).catch(() => {});
92
+ this.deps.exit(0);
93
+ }
94
+ }
95
+
96
+ let idleStop: IdleStop | undefined;
97
+
98
+ /** Test seam: forget the process-wide idle state. */
99
+ export function resetMateServer(): void {
100
+ idleStop = undefined;
101
+ }
102
+
103
+ export interface MateServerLocation {
104
+ /** Runs before an idle stop exits the process, e.g. to end registered sessions. */
105
+ onStop: (stop: () => Promise<unknown>) => void;
106
+ dispose: () => void;
107
+ }
108
+
109
+ /** Undefined outside a Mate OpenCode server. */
110
+ export async function registerMateServer(
111
+ api: Context,
112
+ env: NodeJS.ProcessEnv = process.env,
113
+ deps: MateServerDeps = defaultDeps,
114
+ ): Promise<MateServerLocation | undefined> {
115
+ if (!runsInMateServer(env)) return undefined;
116
+ dropPasswords(env);
117
+ await api.shell.hook("create.before", (event) => dropPasswords(event.env));
118
+
119
+ idleStop ??= new IdleStop(deps);
120
+ const idle = idleStop;
121
+ idle.start();
122
+ const stops: Array<() => Promise<unknown>> = [];
123
+
124
+ const controller = new AbortController();
125
+ void (async () => {
126
+ try {
127
+ for await (const event of api.event.subscribe({ signal: controller.signal })) {
128
+ idle.observe(event as StepEvent);
129
+ }
130
+ } catch {
131
+ /* subscription closed: the location is shutting down */
132
+ }
133
+ })();
134
+
135
+ return {
136
+ onStop: (stop) => {
137
+ stops.push(stop);
138
+ idle.onStop.add(stop);
139
+ },
140
+ dispose: () => {
141
+ controller.abort();
142
+ for (const stop of stops) idle.onStop.delete(stop);
143
+ },
144
+ };
145
+ }
@@ -216,7 +216,8 @@ interface ToolCallEvent {
216
216
  /**
217
217
  * Points a tokensave call at the linked worktree the calling session works in.
218
218
  * The session's directory is read per call: `mate_enter_worktree` moves a
219
- * session after the plugin, and `api.location`, were set up.
219
+ * session after the plugin, and `api.location`, were set up. `api.location`
220
+ * is the checkout the MCP server serves, which is never routed.
220
221
  */
221
222
  async function routeTokensaveCall(api: Context, event: ToolCallEvent): Promise<void> {
222
223
  if (!TOKENSAVE_TOOL.test(event.tool)) return;
@@ -224,6 +225,7 @@ async function routeTokensaveCall(api: Context, event: ToolCallEvent): Promise<v
224
225
  event.tool,
225
226
  await sessionDirectory(api, event.sessionID),
226
227
  event.input,
228
+ { servedDirectory: api.location.directory },
227
229
  );
228
230
  if (routed) event.input = routed;
229
231
  }
@@ -195,7 +195,7 @@ export function readContext(
195
195
  env: Record<string, string | undefined> = process.env,
196
196
  cwd: string = process.cwd(),
197
197
  ): CompanionContext {
198
- const { context, projection } = resolveCompanionRuntime(env, cwd);
198
+ const { context, projection } = resolveCompanionRuntime(env, cwd, { borrow: false });
199
199
 
200
200
  let agentsMd = "";
201
201
  if (context.companionPath) {
@@ -232,6 +232,6 @@ export function readStalenessLines(
232
232
  env: Record<string, string | undefined> = process.env,
233
233
  cwd: string = process.cwd(),
234
234
  ): string[] {
235
- const { context, projection } = resolveCompanionRuntime(env, cwd);
235
+ const { context, projection } = resolveCompanionRuntime(env, cwd, { borrow: false });
236
236
  return stalenessLinesFor(context, projection);
237
237
  }
@@ -41,7 +41,8 @@ export function resolveOpenCodeGuidance(
41
41
  }
42
42
 
43
43
  const projection = resolveProjection(cwd);
44
- if (!projection) return { guidance: null, errors: [] };
44
+ // Plain `opencode` in a worktree Mate never ran in stays out of scope.
45
+ if (!projection || projection.borrowedFrom) return { guidance: null, errors: [] };
45
46
 
46
47
  const policy = readCompanionPolicy(projection.companionPath);
47
48
  const guidance = buildOpenCodeGuidance(
@@ -0,0 +1,176 @@
1
+ import type { Context } from "@opencode/plugin/promise/plugin";
2
+
3
+ import {
4
+ endSession,
5
+ isEnded,
6
+ isRegistered,
7
+ patchSession,
8
+ refreshSession,
9
+ type SessionActivity,
10
+ type SessionInput,
11
+ type WriteOptions,
12
+ } from "../runtime/session-registry";
13
+ import { currentBranch } from "../runtime/current-branch";
14
+
15
+ /**
16
+ * Keeps the OpenCode sessions an editor plugin registered (it does so before
17
+ * launching them) current in the Mate session registry: on creation, on the
18
+ * first prompt of a resumed session, on rename (label), on step and permission
19
+ * events (activity, attention), and on deletion or plugin shutdown (end). Any
20
+ * other session writes nothing. Every write is best-effort; a failure never
21
+ * reaches OpenCode.
22
+ */
23
+
24
+ export interface OpenCodeRegisterDeps {
25
+ /** Refreshes a registered session; null when it is not registered. */
26
+ register: (input: SessionInput) => Promise<unknown | null>;
27
+ registered: (id: string) => Promise<boolean>;
28
+ /** Registered and marked ended, e.g. by `mate session stop` while this server ran on. */
29
+ ended: (id: string) => Promise<boolean>;
30
+ label: (id: string, label: string) => Promise<unknown>;
31
+ activity: (id: string, activity: SessionActivity, attentionAt?: string) => Promise<unknown>;
32
+ end: (id: string) => Promise<unknown>;
33
+ branch: (dir: string) => Promise<string | null>;
34
+ pid: number;
35
+ now: () => Date;
36
+ }
37
+
38
+ const ignore = (): void => {};
39
+
40
+ /** Hooks skip a write they cannot lock within 2 s. */
41
+ const PLUGIN_WRITE: WriteOptions = { lock: { waitMs: 2000 } };
42
+
43
+ export const openCodeRegisterDeps: OpenCodeRegisterDeps = {
44
+ register: (input) => refreshSession(input, PLUGIN_WRITE),
45
+ registered: (id) => isRegistered(id, PLUGIN_WRITE),
46
+ ended: (id) => isEnded(id, PLUGIN_WRITE),
47
+ label: (id, label) => patchSession(id, { label }, PLUGIN_WRITE),
48
+ activity: (id, activity, attentionAt) =>
49
+ patchSession(id, { activity, attentionAt }, PLUGIN_WRITE),
50
+ end: (id) => endSession(id, PLUGIN_WRITE),
51
+ branch: currentBranch,
52
+ pid: process.pid,
53
+ now: () => new Date(),
54
+ };
55
+
56
+ interface SessionEvent {
57
+ type?: string;
58
+ location?: { directory?: string };
59
+ data?: {
60
+ sessionID?: string;
61
+ parentID?: string;
62
+ title?: string;
63
+ finish?: string;
64
+ location?: { directory?: string };
65
+ };
66
+ }
67
+
68
+ /**
69
+ * The activity an event moves a session to. A step ending in `tool-calls` is
70
+ * followed by the next step of the same turn, so the session stays working.
71
+ */
72
+ function activityAfter(event: SessionEvent): SessionActivity | undefined {
73
+ switch (event.type) {
74
+ case "session.step.started":
75
+ case "permission.replied":
76
+ return "working";
77
+ case "session.step.ended":
78
+ return event.data?.finish === "tool-calls" ? undefined : "idle";
79
+ case "session.step.failed":
80
+ return "idle";
81
+ case "permission.asked":
82
+ return "waiting";
83
+ default:
84
+ return undefined;
85
+ }
86
+ }
87
+
88
+ function eventDirectory(event: SessionEvent): string | undefined {
89
+ return event.location?.directory ?? event.data?.location?.directory;
90
+ }
91
+
92
+ /**
93
+ * Subscribes to session events; returns the cleanup that ends what it
94
+ * registered, unless `keepSessions`: a Mate OpenCode server keeps them running.
95
+ */
96
+ export async function registerOpenCodeSessions(
97
+ api: Context,
98
+ deps: OpenCodeRegisterDeps = openCodeRegisterDeps,
99
+ ): Promise<(options?: { keepSessions?: boolean }) => Promise<void>> {
100
+ const directory = api.location.directory;
101
+ const seen = new Set<string>();
102
+ const registered = new Set<string>();
103
+ const activities = new Map<string, SessionActivity>();
104
+
105
+ /** Writes only a change; every permission request is one (its time). */
106
+ const track = async (id: string, event: SessionEvent) => {
107
+ const activity = activityAfter(event);
108
+ if (!activity) return;
109
+ const asked = event.type === "permission.asked";
110
+ if (!asked && activities.get(id) === activity) return;
111
+ activities.set(id, activity);
112
+ const attentionAt = asked ? deps.now().toISOString() : undefined;
113
+ await deps.activity(id, activity, attentionAt).catch(ignore);
114
+ };
115
+
116
+ const register = async (id: string, prompted = false) => {
117
+ if (seen.has(id)) {
118
+ // A session stopped and resumed on this server: clear its end.
119
+ if (!prompted || !registered.has(id)) return;
120
+ if (!(await deps.ended(id).catch(() => false))) return;
121
+ }
122
+ seen.add(id);
123
+ // Any other session costs one registry read, no Git call.
124
+ if (!(await deps.registered(id).catch(() => false))) return;
125
+ const branch = await deps.branch(directory).catch(() => null);
126
+ const refreshed = await deps
127
+ .register({
128
+ id,
129
+ runtime: "opencode",
130
+ cwd: directory,
131
+ pid: deps.pid,
132
+ ...(branch ? { branch } : {}),
133
+ })
134
+ .catch(() => null);
135
+ if (refreshed) registered.add(id);
136
+ };
137
+
138
+ /** A resumed session (`--session <id>`) emits no `session.created`. */
139
+ await api.session.hook("prompt", (event) => {
140
+ void register(event.sessionID, true);
141
+ });
142
+
143
+ const controller = new AbortController();
144
+ void (async () => {
145
+ try {
146
+ for await (const raw of api.event.subscribe({ signal: controller.signal })) {
147
+ const event = raw as SessionEvent;
148
+ const id = event.data?.sessionID;
149
+ if (!id) continue;
150
+ if (event.type === "session.created") {
151
+ if (event.data?.parentID) continue;
152
+ if (eventDirectory(event) !== directory) continue;
153
+ await register(id);
154
+ } else if (event.type === "session.renamed" && registered.has(id) && event.data?.title) {
155
+ await deps.label(id, event.data.title).catch(ignore);
156
+ } else if (event.type === "session.deleted" && registered.has(id)) {
157
+ registered.delete(id);
158
+ seen.delete(id);
159
+ activities.delete(id);
160
+ await deps.end(id).catch(ignore);
161
+ } else if (registered.has(id)) {
162
+ await track(id, event);
163
+ }
164
+ }
165
+ } catch {
166
+ /* subscription closed: the location is shutting down */
167
+ }
168
+ })();
169
+
170
+ return async ({ keepSessions = false } = {}) => {
171
+ controller.abort();
172
+ if (!keepSessions) await Promise.all([...registered].map((id) => deps.end(id).catch(ignore)));
173
+ registered.clear();
174
+ seen.clear();
175
+ };
176
+ }
@@ -1,13 +1,7 @@
1
1
  /** @jsxRuntime automatic */
2
2
  /** @jsxImportSource @opentui/solid */
3
- /* oxlint-disable react/no-unknown-property, react/react-in-jsx-scope, react/jsx-key, react-doctor/jsx-key */
4
- /**
5
- * OpenCode V2 TUI plugin module (`{ id, setup }`), OpenCode 2.x only.
6
- * Solid JSX, not React: `key` is not a reconciliation prop here and `TextProps`
7
- * does not accept it, so the jsx-key rules cannot be satisfied — only suppressed.
8
- * The line list is a function child: Solid re-runs its `.map` whole on a store change, fine for a few lines.
9
- */
10
- import type { JSX } from "@opentui/solid";
3
+ // OpenCode scans source imports to bind host modules; implicit JSX imports are missed in node_modules.
4
+ import { jsx } from "@opentui/solid/jsx-runtime";
11
5
 
12
6
  import { BRAND_ACCENT } from "../brand/palette";
13
7
  import { mateVersion } from "../runtime/install";
@@ -68,25 +62,21 @@ function SessionContext({
68
62
  const text = api.theme.text;
69
63
  const warning = text.feedback?.warning?.base ?? text.muted;
70
64
 
71
- return (
72
- <box
73
- width="100%"
74
- maxWidth={sidebar ? undefined : 75}
75
- paddingLeft={sidebar ? 0 : 2}
76
- paddingRight={sidebar ? 0 : 2}
77
- paddingBottom={sidebar ? 1 : 0}
78
- flexShrink={0}
79
- >
80
- <text fg={MATE_VERSION_COLOR}>mate v{MATE_VERSION}</text>
81
- <text fg={text.muted}>repo: {context.repositoryPath}</text>
82
- <text fg={text.muted}>mate: {context.companionPath}</text>
83
- {/* OpenTUI's Solid transform skips node_modules, so only a function child stays reactive; its children types omit functions. */}
84
- {
85
- (() =>
86
- notes.lines.map((note) => <text fg={warning}>{note}</text>)) as unknown as JSX.Element
87
- }
88
- </box>
89
- );
65
+ return jsx("box", {
66
+ width: "100%",
67
+ maxWidth: sidebar ? undefined : 75,
68
+ paddingLeft: sidebar ? 0 : 2,
69
+ paddingRight: sidebar ? 0 : 2,
70
+ paddingBottom: sidebar ? 1 : 0,
71
+ flexShrink: 0,
72
+ children: [
73
+ jsx("text", { fg: MATE_VERSION_COLOR, children: `mate v${MATE_VERSION}` }),
74
+ jsx("text", { fg: text.muted, children: `repo: ${context.repositoryPath}` }),
75
+ jsx("text", { fg: text.muted, children: `mate: ${context.companionPath}` }),
76
+ // A function child keeps late staleness updates reactive without the Solid transform.
77
+ () => notes.lines.map((note) => jsx("text", { fg: warning, children: note })),
78
+ ],
79
+ });
90
80
  }
91
81
 
92
82
  /** Polls the session lines; a line that appears after startup is also raised as a toast. */
@@ -116,11 +106,11 @@ function setup(api: MateTuiApi): (() => void) | undefined {
116
106
 
117
107
  api.ui.slot({
118
108
  prepend: "home.footer",
119
- render: () => <SessionContext api={api} notes={notes} />,
109
+ render: () => SessionContext({ api, notes }),
120
110
  });
121
111
  api.ui.slot({
122
112
  append: "sidebar.content",
123
- render: () => <SessionContext api={api} notes={notes} sidebar />,
113
+ render: () => SessionContext({ api, notes, sidebar: true }),
124
114
  });
125
115
  return () => clearInterval(timer);
126
116
  }
@@ -1,6 +1,7 @@
1
1
  import path from "node:path";
2
2
 
3
3
  import type { ClaudeHookGroup } from "./claude-hook-group";
4
+ import { otherServingClaudeWrapRoot } from "./serving-claude-wrap";
4
5
  import type { SessionKind } from "./session-kind";
5
6
  import { NOT_WRAPPED, readWrapStateSync, type WrapState } from "./wrap-state";
6
7
 
@@ -166,7 +167,17 @@ function planChannels(
166
167
  }
167
168
  }
168
169
 
169
- /** For session-start hooks: a plain session's plan from a lenient read; no root, not wrapped. */
170
- export function unmanagedClaudeDelivery(repoRoot: string | undefined): ClaudeDeliveryPlan {
171
- return planClaudeDelivery("unmanaged", repoRoot ? readWrapStateSync(repoRoot) : NOT_WRAPPED);
170
+ /**
171
+ * For session-start hooks: the plan of a plain session in the Checkout at
172
+ * `checkoutRoot`, from a lenient read; no root, not wrapped. Planned from the
173
+ * wrap serving it while that one is wrapped for Claude, else from its own:
174
+ * Claude Code loads both settings files there, and each hook group runs from
175
+ * the one that carries it (design Decisions 1 and 12).
176
+ */
177
+ export function unmanagedClaudeDelivery(checkoutRoot: string | undefined): ClaudeDeliveryPlan {
178
+ if (!checkoutRoot) return planClaudeDelivery("unmanaged", NOT_WRAPPED);
179
+ const other = otherServingClaudeWrapRoot(checkoutRoot);
180
+ const serving = other ? readWrapStateSync(other) : null;
181
+ const wrap = serving?.runtimes.has("claude") ? serving : readWrapStateSync(checkoutRoot);
182
+ return planClaudeDelivery("unmanaged", wrap);
172
183
  }