@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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mate-companion-mentions",
3
- "version": "1.0.0-canary.2",
3
+ "version": "1.0.0-canary.5",
4
4
  "description": "@mate:<path> mentions: find and attach files from the mate companion repo in the @ menu.",
5
5
  "author": {
6
6
  "name": "Kevin Tornquist"
@@ -1,5 +1,5 @@
1
1
  {
2
- "description": "Mate hooks \u2014 PreToolUse artifact-path and secret guardrail, PreToolUse tokensave worktree routing, SessionStart banner, companion guidance, session prepare then companion instructions, SubagentStart companion instructions",
2
+ "description": "Mate hooks \u2014 PreToolUse artifact-path and secret guardrail, PreToolUse tokensave worktree routing, SessionStart banner, companion guidance, session prepare then companion instructions, SubagentStart companion instructions, SessionEnd and Notification session registry",
3
3
  "hooks": {
4
4
  "PreToolUse": [
5
5
  {
@@ -57,6 +57,26 @@
57
57
  }
58
58
  ]
59
59
  }
60
+ ],
61
+ "SessionEnd": [
62
+ {
63
+ "hooks": [
64
+ {
65
+ "type": "command",
66
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-end.mjs\""
67
+ }
68
+ ]
69
+ }
70
+ ],
71
+ "Notification": [
72
+ {
73
+ "hooks": [
74
+ {
75
+ "type": "command",
76
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-attention.mjs\""
77
+ }
78
+ ]
79
+ }
60
80
  ]
61
81
  }
62
82
  }
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Thin shim for the `Notification` entry of src/hooks/session-end.ts, loaded through
4
+ * ts-loader.mjs: the installed plugin sits inside node_modules, where node's native type
5
+ * stripping is off.
6
+ */
7
+ import "./ts-loader.mjs";
8
+
9
+ const { runAttention } = await import("../../src/hooks/session-end.ts");
10
+ process.exitCode = await runAttention();
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Thin shim for src/hooks/session-end.ts, loaded through ts-loader.mjs: the installed
4
+ * plugin sits inside node_modules, where node's native type stripping is off.
5
+ */
6
+ import "./ts-loader.mjs";
7
+
8
+ const { run } = await import("../../src/hooks/session-end.ts");
9
+ process.exitCode = await run();
@@ -5,4 +5,4 @@
5
5
  import "./ts-loader.mjs";
6
6
 
7
7
  const { run } = await import("../../src/hooks/session-guidance.ts");
8
- process.exitCode = run();
8
+ process.exitCode = await run();
@@ -5,10 +5,13 @@ import {
5
5
  registerTokensaveRouting,
6
6
  repositoryWrappedForOpenCode,
7
7
  } from "../../src/opencode/companion-hooks";
8
+ import { registerMateServer } from "../../src/opencode/background-server";
8
9
  import { readContext } from "../../src/opencode/companion-policy";
9
10
  import { registerEnterWorktree } from "../../src/opencode/enter-worktree";
10
11
  import { registerSessionPrepare } from "../../src/opencode/session-prepare";
12
+ import { registerOpenCodeSessions } from "../../src/opencode/session-register";
11
13
  import { hasLaunchEnvironment } from "../../src/runtime/env";
14
+ import { guardLaunchEnvironment } from "../../src/runtime/launch-env-guard";
12
15
  import { spawnPrepareRunner } from "../../src/runtime/session-prepare-runner";
13
16
  import { readWrapStateSync } from "../../src/runtime/wrap-state";
14
17
 
@@ -49,18 +52,26 @@ async function registerPrepare(api: Context, companionPath: string, env: LaunchE
49
52
  export const MateOpenCodePlugin = Plugin.define({
50
53
  id: "mate-opencode-plugin",
51
54
  async setup(api) {
52
- const env = pluginLaunchEnvironment(process.env, process.argv);
55
+ /** First: drops the server password from `process.env` before any shell can start. */
56
+ const server = await registerMateServer(api);
57
+ const env = { ...pluginLaunchEnvironment(process.env, process.argv) };
58
+ guardLaunchEnvironment(env, api.location.directory);
53
59
  const context = readContext(env, api.location.directory);
54
- if (!context.companionPath) return;
60
+ if (!context.companionPath) return server ? async () => server.dispose() : undefined;
55
61
 
56
62
  await registerCompanionAccess(api, context.companionPath);
57
63
  await registerCompanionHooks(api, context, env);
58
64
  await registerTokensaveRouting(api);
59
65
  await registerCompanion(api, context, env);
60
66
  await registerEnterWorktree(api, context);
67
+ const sessionsCleanup = await registerOpenCodeSessions(api).catch(() => undefined);
68
+ if (sessionsCleanup) server?.onStop(() => sessionsCleanup());
61
69
  /** Last: the guardrails above are live while the local phase holds `setup`. */
62
70
  const prepareCleanup = await registerPrepare(api, context.companionPath, env);
63
71
  return async () => {
72
+ server?.dispose();
73
+ /** A Mate OpenCode server's sessions outlive a location; its idle stop ends them. */
74
+ await sessionsCleanup?.({ keepSessions: Boolean(server) });
64
75
  await prepareCleanup?.();
65
76
  };
66
77
  },
@@ -1,3 +1,3 @@
1
1
  /** @jsxRuntime automatic */
2
2
  /** @jsxImportSource @opentui/solid */
3
- export { default } from "../../src/opencode/tui";
3
+ export { default } from "../../src/opencode/tui.tsx";
@@ -1,4 +1,5 @@
1
1
  /** @jsxRuntime automatic */
2
2
  /** @jsxImportSource @opentui/solid */
3
3
  /** Root entry for a plugin bound by directory path; see `server.ts`. */
4
- export { default } from "./src/tui";
4
+ // Explicit extensions let OpenTUI prescan the re-export chain in node_modules.
5
+ export { default } from "./src/tui.tsx";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uniqbit/mate-core",
3
- "version": "1.0.0-canary.2",
3
+ "version": "1.0.0-canary.5",
4
4
  "description": "Core framework and plugin APIs for Mate.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -59,8 +59,8 @@ function renderHuman(result: ArchiveResult): string[] {
59
59
  * to the Working Repository.
60
60
  * - `--branch <branch>` / `--direct` — record the delivery branch first, as `artifact link`.
61
61
  * - `--not-applicable <reason>` — record that no branch delivers this change.
62
- * - `--skip-branch` — archive with an unlinked record marked `skipped` when the user skips the
63
- * question, so publication asks again even when the record holds a ticket.
62
+ * - `--skip-branch` — archive with an unlinked record when the user skips the question, so
63
+ * publication asks again.
64
64
  * - `--fetch` — fetch the default and delivery branches before the merge check even when the
65
65
  * companion's Git mode is not `auto`.
66
66
  * - `--json` — emit an {@link ArchiveResult}.
@@ -5,7 +5,8 @@ import {
5
5
  type RecordDeliveryDeps,
6
6
  } from "../../../../lib/delivery/record-delivery";
7
7
  import { applyWarnings, type DependencyWarning } from "../../../../lib/delivery/overlap";
8
- import { isJiraKey, type MergeState } from "../../../../lib/delivery/record";
8
+ import { isJiraKey, normalizeJiraKey, type MergeState } from "../../../../lib/delivery/record";
9
+ import { attributeCurrentSession } from "../../../../lib/session-attribution";
9
10
  import { type BooleanFlagSet, parseFlags, positionalArgs, stringFlag } from "../../../parse-flags";
10
11
  import {
11
12
  branchFlagsFrom,
@@ -27,6 +28,9 @@ import {
27
28
  export interface LinkCommandDeps extends DeliveryEnvironmentDeps, RecordDeliveryDeps {
28
29
  stdout?: (line: string) => void;
29
30
  stderr?: (line: string) => void;
31
+ /** Records the change on the agent session this runs in. */
32
+ attribute?: typeof attributeCurrentSession;
33
+ sessionEnv?: Record<string, string | undefined>;
30
34
  }
31
35
 
32
36
  const BOOLEAN_FLAGS: BooleanFlagSet = new Set([
@@ -57,7 +61,6 @@ function refusalMessage(refusal: DeliveryRefusal): string {
57
61
 
58
62
  function renderHuman(result: LinkResult): string[] {
59
63
  const lines = [`${result.change}: ${result.settlement.status}`];
60
- if (result.record.ticket) lines.push(` ticket: ${result.record.ticket}`);
61
64
  lines.push(...result.record.deliveries.map(renderDelivery));
62
65
  for (const repository of result.settlement.missing) {
63
66
  lines.push(` ${repository}: no delivery recorded (named in the change's scopes)`);
@@ -79,8 +82,10 @@ function renderHuman(result: LinkResult): string[] {
79
82
  * - `--direct` — with `--branch`, record a direct delivery, settled only by the user's answer; required for a protected branch.
80
83
  * - `--not-applicable <reason>` — no branch delivers this change in the repository.
81
84
  * - `--pr <url>` — record the PR URL; with `--refresh`, picks that PR among several.
82
- * - `--ticket <KEY>` — record the change's Jira ticket (`ABC-123`), alone or with other edits;
83
- * refused unless the companion's openspec capability sets `ticket: jira`.
85
+ * - `--ticket <KEY>` — record the Delivery Branch resolved with this Jira key (`ABC-123`, any
86
+ * case): a new branch is named `workset/<TICKET>-<workset-id>`, while a recorded, inherited,
87
+ * or existing branch is kept. The key is not stored. Excludes `--branch` and
88
+ * `--not-applicable`; refused unless the openspec capability sets `ticket: jira`.
84
89
  * - `--refresh` — ask the forge (with `MATE_GIT_TOKEN`), then a local checkout, for the merge
85
90
  * state of each recorded branch; a direct delivery is reported as needing the user's answer.
86
91
  * - `--fetch` — with `--refresh`, fetch the default and delivery branches first even when the
@@ -132,6 +137,11 @@ export async function runArtifactLinkCommand(
132
137
  if (ticket !== undefined && !isJiraKey(ticket)) {
133
138
  return refuse("mate: --ticket expects a Jira key such as ABC-123.");
134
139
  }
140
+ if (ticket !== undefined && (branch !== undefined || notApplicable !== undefined)) {
141
+ return refuse(
142
+ "mate: --ticket names the resolved branch; it excludes --branch and --not-applicable.",
143
+ );
144
+ }
135
145
  const requested = repositoryFlag(flags);
136
146
  if ("error" in requested) return refuse(requested.error);
137
147
 
@@ -150,7 +160,7 @@ export async function runArtifactLinkCommand(
150
160
  ...(delivery ? { delivery } : {}),
151
161
  ...(pr !== undefined ? { pr } : {}),
152
162
  ...(confirm ? { confirm } : {}),
153
- ...(ticket !== undefined ? { ticket } : {}),
163
+ ...(ticket !== undefined ? { ticket: normalizeJiraKey(ticket) } : {}),
154
164
  },
155
165
  refresh: flags.refresh === true,
156
166
  fetch: flags.fetch === true,
@@ -159,6 +169,13 @@ export async function runArtifactLinkCommand(
159
169
  deps,
160
170
  );
161
171
  if ("refusal" in outcome) return refuse(refusalMessage(outcome.refusal));
172
+ // One change names the session's work; a batch link names none.
173
+ if (changes.length === 1) {
174
+ await (deps.attribute ?? attributeCurrentSession)(
175
+ { change: changes[0]! },
176
+ deps.sessionEnv ?? process.env,
177
+ );
178
+ }
162
179
  const results: LinkResult[] = [];
163
180
  for (const result of "results" in outcome ? outcome.results : []) {
164
181
  for (const diagnostic of result.diagnostics) emitErr(`warning: ${diagnostic}`);
@@ -1,3 +1,4 @@
1
+ import { TICKETS_OFF } from "../../../../lib/delivery/branches";
1
2
  import type { Delivery, UnscopedDelivery } from "../../../../lib/delivery/record";
2
3
  import type { BranchOutcome } from "../../../../lib/delivery/refresh";
3
4
  import type { DeliveryRefusal } from "../../../../lib/delivery/record-delivery";
@@ -73,7 +74,14 @@ export function sharedRefusalMessage(
73
74
  return "mate: the Working Repository has no origin remote to identify it; pass --repository <org/repo>.";
74
75
  }
75
76
  if (refusal.reason === "tickets-off") {
76
- return "mate: tickets are off for this companion; set `ticket: jira` on the openspec capability (mate setup --ticket jira) to record one.";
77
+ return `mate: ${TICKETS_OFF}`;
78
+ }
79
+ if (refusal.reason === "no-resolved-branch") {
80
+ const reasons = refusal.diagnostics.length > 0 ? ` (${refusal.diagnostics.join(" ")})` : "";
81
+ return `mate: ${refusal.change} has no Delivery Branch to name with a ticket${reasons}; pass --branch instead.`;
82
+ }
83
+ if (refusal.reason === "settled-delivery") {
84
+ return `mate: ${refusal.change} records ${refusal.delivery} for ${refusal.repository}; a ticket does not replace it, pass --branch to relink.`;
77
85
  }
78
86
  if (refusal.reason === "protected-branch") {
79
87
  return `mate: ${refusal.branch} is a protected branch (${refusal.protection}); record it only as an explicit direct delivery with --direct.`;
@@ -342,9 +342,7 @@ async function resolved(
342
342
  resolved: {
343
343
  anchorName,
344
344
  commitPaths,
345
- ...(delivery.status === "legacy"
346
- ? { warning: legacyDeliveryWarning(anchorName, delivery.record) }
347
- : {}),
345
+ ...(delivery.status === "legacy" ? { warning: legacyDeliveryWarning(anchorName) } : {}),
348
346
  },
349
347
  };
350
348
  }
@@ -36,7 +36,7 @@ export async function runCompanionCommand(
36
36
  await runCompanionUpdateCommand(argv);
37
37
  return;
38
38
  case "open":
39
- await runWorkspaceOpenCommand();
39
+ await runWorkspaceOpenCommand(argv);
40
40
  return;
41
41
  case "tui":
42
42
  await runCompanionTuiCommand();
@@ -10,11 +10,15 @@ import {
10
10
  } from "../../companion-link-wizard";
11
11
  import { extractRepoName } from "../artifact/extract-repo-name";
12
12
  import { GlobalConfigStore } from "../../../lib/orchestrator/global-config-store";
13
+ import { linkIdFor } from "../../../lib/orchestrator/registry-checkouts";
14
+ import { RepoLocalRegistryStore } from "../../../lib/orchestrator/repo-local-store";
13
15
  import {
14
16
  CompanionResolver,
15
17
  companionRootedStore,
16
18
  findDescendantRepoLocalRegistries,
17
19
  } from "../../../lib/orchestrator/repository-link";
20
+ import { namesOtherCheckout } from "../../../runtime/git-layout";
21
+ import { repoLocalRegistryPath } from "../../../runtime/repo-local";
18
22
  import { inspectSetupPreflight } from "../../../lib/orchestrator/setup-preflight";
19
23
  import { runSetupFlowAtPath } from "../setup";
20
24
  import { runInstallCommand } from "../install";
@@ -46,6 +50,24 @@ interface CompanionLinkCommandDeps {
46
50
  createProgress?: typeof createStartupProgress;
47
51
  }
48
52
 
53
+ /**
54
+ * A registry in another Checkout of this clone that names a companion just
55
+ * linked is that Checkout's Adoption, not a shadow: resolution from inside a
56
+ * linked worktree never reaches this folder's link (design Decisions 3 and 14).
57
+ */
58
+ async function adoptedCheckout(
59
+ cwd: string,
60
+ shadowedPath: string,
61
+ companionPaths: readonly string[],
62
+ ): Promise<boolean> {
63
+ if (!namesOtherCheckout(cwd, shadowedPath)) return false;
64
+ const linked = new Set(companionPaths.map((companionPath) => path.resolve(companionPath)));
65
+ const local = await new RepoLocalRegistryStore(repoLocalRegistryPath(shadowedPath))
66
+ .load()
67
+ .catch(() => null);
68
+ return (local?.companions ?? []).some((pointer) => linked.has(path.resolve(pointer.path)));
69
+ }
70
+
49
71
  /** All companions surfaced by the "existing companion" picker live under this directory. */
50
72
  function companionsHomeDir(): string {
51
73
  return path.join(os.homedir(), `.${FRAMEWORK_NAME}`, "companions");
@@ -203,8 +225,9 @@ export async function runCompanionLinkCommandWithDeps(
203
225
  companionPaths = [resolvedCompanionPath];
204
226
  }
205
227
 
228
+ /** The registry keeps the ID of an entry the clone already has, and the link names the kept one. */
206
229
  const repository: LinkedRepository = {
207
- id: path.basename(cwd),
230
+ id: linkIdFor(cwd),
208
231
  path: cwd,
209
232
  };
210
233
 
@@ -221,6 +244,7 @@ export async function runCompanionLinkCommandWithDeps(
221
244
  // Managed companions are git-backed; explicitly pasted paths retain local provenance.
222
245
  const persistedSource: CompanionSource = companionSource === "local" ? "local" : "git";
223
246
 
247
+ let keptId: string | undefined;
224
248
  /* oxlint-disable no-await-in-loop -- each companion is set up, linked and installed in turn; a declined install stops the rest */
225
249
  for (const companionPath of companionPaths) {
226
250
  const preflight = await inspectPreflight(companionPath);
@@ -228,7 +252,11 @@ export async function runCompanionLinkCommandWithDeps(
228
252
  await runSetup(companionPath);
229
253
  }
230
254
 
231
- await registerRepository(repository, { companionPath, companionSource: persistedSource });
255
+ const kept = await registerRepository(repository, {
256
+ companionPath,
257
+ companionSource: persistedSource,
258
+ });
259
+ keptId ??= kept.id;
232
260
  await registerCompanion(companionPath);
233
261
  await invalidateInstallState({ kind: "companion", companionPath });
234
262
  if ((await installCompanion(companionPath)) === false) return;
@@ -237,7 +265,11 @@ export async function runCompanionLinkCommandWithDeps(
237
265
 
238
266
  let shadowedPaths: string[] = [];
239
267
  try {
240
- shadowedPaths = await findShadowedRegistries(cwd);
268
+ const found = await findShadowedRegistries(cwd);
269
+ const adopted = await Promise.all(
270
+ found.map((shadowedPath) => adoptedCheckout(cwd, shadowedPath, companionPaths)),
271
+ );
272
+ shadowedPaths = found.filter((_shadowedPath, index) => !adopted[index]);
241
273
  } catch {
242
274
  // A diagnostic scan must never fail an otherwise successful link.
243
275
  }
@@ -251,7 +283,7 @@ export async function runCompanionLinkCommandWithDeps(
251
283
  );
252
284
  }
253
285
 
254
- console.log(`Successfully linked companion for ${repository.id}`);
286
+ console.log(`Successfully linked companion for ${keptId ?? repository.id}`);
255
287
  for (const companionPath of companionPaths) {
256
288
  console.log(` Companion: ${companionPath}`);
257
289
  }
@@ -10,9 +10,11 @@ import {
10
10
  editorWorkspacePath,
11
11
  getPreferredEditorCli,
12
12
  openEditorWorkspace,
13
+ prepareEditorWorkspace,
13
14
  } from "../../../lib/orchestrator/editor";
14
15
  import { WorkingRepoRequiredError } from "../../../lib/orchestrator/types";
15
16
  import { resolveProjection } from "../../../runtime/projection";
17
+ import { writeJsonStdout } from "../../write-json-stdout";
16
18
 
17
19
  export const workspaceOpenCommandDeps = {
18
20
  cwd: () => process.cwd(),
@@ -37,6 +39,7 @@ export const workspaceOpenCommandDeps = {
37
39
  resolveProjection,
38
40
  getPreferredEditorCli: () => getPreferredEditorCli(),
39
41
  openEditorWorkspace,
42
+ prepareEditorWorkspace,
40
43
  };
41
44
 
42
45
  /**
@@ -57,6 +60,9 @@ function orderCompanionPaths(cwd: string, matches: CompanionMatch[]): string[] {
57
60
  * and the worktree-detection settings into `.mate/<repo>.mate.code-workspace`,
58
61
  * keeping developer edits, then opens that file in the editor. A legacy
59
62
  * `.mate/workspace.code-workspace` is renamed to it once.
63
+ * @flags
64
+ * - `--no-open` — prepare the workspace without requiring or starting an editor.
65
+ * - `--json` — print the absolute workspacePath as JSON instead of human output.
60
66
  * @remarks Never selects a companion: no picker, no `MATE_ARTIFACT_PATH`
61
67
  * narrowing, and the companion recorded at the Projection Root is left as it
62
68
  * was. Stale companion pointers are skipped with a stderr warning. Throws
@@ -64,23 +70,45 @@ function orderCompanionPaths(cwd: string, matches: CompanionMatch[]): string[] {
64
70
  * sets a non-zero exit code if the editor CLI is unavailable or the workspace
65
71
  * file cannot be read, leaving that file unchanged.
66
72
  */
67
- export async function runWorkspaceOpenCommand(): Promise<void> {
73
+ export async function runWorkspaceOpenCommand(argv: string[] = []): Promise<void> {
68
74
  const cwd = workspaceOpenCommandDeps.cwd();
69
75
  const matches = await workspaceOpenCommandDeps.resolveCompanions(cwd);
70
76
  if (matches.length === 0) throw new WorkingRepoRequiredError("companion open");
71
77
 
72
78
  const repoPath = await workspaceOpenCommandDeps.findRepoRoot(cwd);
73
- const opened = await workspaceOpenCommandDeps.openEditorWorkspace(
74
- orderCompanionPaths(cwd, matches),
75
- repoPath,
76
- workspaceOpenCommandDeps.getPreferredEditorCli(),
77
- );
78
-
79
- if (!opened) {
80
- process.exitCode = 1;
81
- return;
79
+ const companionPaths = orderCompanionPaths(cwd, matches);
80
+ const noOpen = argv.includes("--no-open");
81
+ if (noOpen) {
82
+ const { workspacePath, error } = await workspaceOpenCommandDeps.prepareEditorWorkspace(
83
+ companionPaths,
84
+ repoPath,
85
+ );
86
+ if (error) {
87
+ console.error(`mate: warning: ${workspacePath}: ${error.message}`);
88
+ process.exitCode = 1;
89
+ return;
90
+ }
91
+ } else {
92
+ const opened = await workspaceOpenCommandDeps.openEditorWorkspace(
93
+ companionPaths,
94
+ repoPath,
95
+ workspaceOpenCommandDeps.getPreferredEditorCli(),
96
+ );
97
+ if (!opened) {
98
+ process.exitCode = 1;
99
+ return;
100
+ }
82
101
  }
83
102
 
84
- const documentPath = path.relative(repoPath, editorWorkspacePath(repoPath));
85
- console.log(`Workspace: opened ${documentPath} in the editor`);
103
+ const workspacePath = editorWorkspacePath(repoPath);
104
+ if (argv.includes("--json")) {
105
+ await writeJsonStdout({ workspacePath });
106
+ } else {
107
+ const documentPath = path.relative(repoPath, workspacePath);
108
+ console.log(
109
+ noOpen
110
+ ? `Workspace: prepared ${documentPath}`
111
+ : `Workspace: opened ${documentPath} in the editor`,
112
+ );
113
+ }
86
114
  }
@@ -6,9 +6,17 @@ import { parse as parseYaml } from "yaml";
6
6
 
7
7
  import { FRAMEWORK_NAME } from "../../framework";
8
8
  import { gitEnvironment } from "../../runtime/companion-git";
9
+ import { checkoutCommonDir, checkoutAt, sameClone } from "../../runtime/git-layout";
10
+ import { physicalPath } from "../../runtime/physical-path";
11
+ import { otherServingClaudeWrapRoot } from "../../runtime/serving-claude-wrap";
12
+ import { readWrapStateSync } from "../../runtime/wrap-state";
9
13
  import { companionClaudeMdHasOwnText } from "../../runtime/companion-instructions";
10
14
  import { getActiveDistribution } from "../../distribution";
11
15
  import { hasOpenspecCapability } from "../../lib/orchestrator/capabilities";
16
+ import {
17
+ inheritedWrapRuntimes,
18
+ registeredCheckout,
19
+ } from "../../lib/orchestrator/checkout-adoption";
12
20
  import { checkEngineRequirement } from "../../lib/orchestrator/engine-guard";
13
21
  import type { GlobalConfigStore } from "../../lib/orchestrator/global-config-store";
14
22
  import { pathIsDirectory } from "../../lib/fs-utils";
@@ -40,6 +48,7 @@ import {
40
48
  type ClaudePluginDirectoryReport,
41
49
  type ClaudePluginUnpublishedReason,
42
50
  } from "../../tools/setup/providers/claude-plugin-folders";
51
+ import { isMateSessionPrepareHookGroup } from "../../tools/setup/providers/claude-plugin-hooks";
43
52
  import { resolveCommandOnPath } from "../../tools/setup/utils";
44
53
  import { isUvNeeded } from "../../tools/setup/package-managers/uv";
45
54
  import { writeJsonStdout } from "../write-json-stdout";
@@ -119,6 +128,25 @@ export interface DoctorReport {
119
128
  claudePluginFailures?: ClaudePluginContributionFailure[];
120
129
  hub?: { members: DoctorHubMember[] };
121
130
  resolutionFailures: Array<{ companionPath: string; message: string }>;
131
+ /** Present inside a Git Checkout of a linked clone, or a worktree Git no longer recognizes. */
132
+ checkout?: DoctorCheckout;
133
+ }
134
+
135
+ export interface DoctorCheckout {
136
+ /** The root of the Checkout holding the current directory. */
137
+ root: string;
138
+ /**
139
+ * `registered`: the clone's Registered Checkout. `other`: another Checkout of
140
+ * the clone. `not-recognized`: a linked worktree whose record in the shared
141
+ * Git folder names another folder, which `git worktree repair` fixes.
142
+ */
143
+ role: "registered" | "other" | "not-recognized";
144
+ repositoryId: string | null;
145
+ registeredCheckout: string | null;
146
+ /** The Checkout whose Claude wrap serves this one. */
147
+ servingClaudeWrap: string;
148
+ /** Set when plain `claude` sessions here start without Mate's session prepare. */
149
+ servingWrapWarning?: string;
122
150
  }
123
151
 
124
152
  interface ToolCheck {
@@ -383,6 +411,70 @@ function collectCompanionInstructionWarnings(
383
411
  ];
384
412
  }
385
413
 
414
+ /** The Checkout's own wraps, or those Adoption would give it (design Decision 8). */
415
+ async function wrappedForClaude(
416
+ companionPath: string,
417
+ repository: { id: string; path: string },
418
+ ): Promise<boolean> {
419
+ return (
420
+ readWrapStateSync(repository.path).runtimes.has("claude") ||
421
+ (await inheritedWrapRuntimes(companionPath, repository)).includes("claude")
422
+ );
423
+ }
424
+
425
+ function carriesPrepareHook(checkoutRoot: string): boolean {
426
+ return readWrapStateSync(checkoutRoot).carriedClaudeHookGroups.some(
427
+ isMateSessionPrepareHookGroup,
428
+ );
429
+ }
430
+
431
+ /**
432
+ * The Checkout section (design Decision 15): how the Checkout holding `cwd`
433
+ * relates to its linked clone, and whether plain `claude` sessions there
434
+ * still reach a session-prepare hook.
435
+ */
436
+ async function collectCheckout(
437
+ cwd: string,
438
+ report: DoctorReport,
439
+ ): Promise<DoctorCheckout | undefined> {
440
+ const found = checkoutAt(cwd);
441
+ if (!found) return undefined;
442
+ const { root } = found;
443
+ const otherServing = otherServingClaudeWrapRoot(root);
444
+ if (found.layout.kind === "linked" && checkoutCommonDir(root) === null) {
445
+ return {
446
+ root,
447
+ role: "not-recognized",
448
+ repositoryId: null,
449
+ registeredCheckout: null,
450
+ servingClaudeWrap: root,
451
+ };
452
+ }
453
+ const { companionPath, repositoryId } = report;
454
+ if (!companionPath || !repositoryId) return undefined;
455
+ const registered = await registeredCheckout(companionPath, repositoryId);
456
+ if (!registered || !(physicalPath(registered) === root || sameClone(registered, root))) {
457
+ return undefined;
458
+ }
459
+ const checkout: DoctorCheckout = {
460
+ root,
461
+ role: physicalPath(registered) === root ? "registered" : "other",
462
+ repositoryId,
463
+ registeredCheckout: registered,
464
+ servingClaudeWrap: otherServing ?? root,
465
+ };
466
+ if (
467
+ otherServing &&
468
+ (await wrappedForClaude(companionPath, { id: repositoryId, path: root })) &&
469
+ !carriesPrepareHook(otherServing) &&
470
+ !carriesPrepareHook(root)
471
+ ) {
472
+ const settings = path.join(otherServing, ".claude", "settings.local.json");
473
+ checkout.servingWrapWarning = `Plain \`claude\` sessions in ${root} start without Mate: Claude Code reads its hooks from ${settings}, which carries no ${FRAMEWORK_NAME} session-prepare hook. Run \`${FRAMEWORK_NAME} wrap\` here or in ${otherServing}.`;
474
+ }
475
+ return checkout;
476
+ }
477
+
386
478
  export async function collectDoctorReport(deps: DoctorDeps = {}): Promise<DoctorReport> {
387
479
  const cwd = path.resolve(deps.cwd ?? process.cwd());
388
480
  const pathValue = deps.pathValue ?? process.env.PATH ?? "";
@@ -400,6 +492,9 @@ export async function collectDoctorReport(deps: DoctorDeps = {}): Promise<Doctor
400
492
  resolutionFailures: root.resolution.failures,
401
493
  };
402
494
 
495
+ const checkout = await collectCheckout(cwd, report);
496
+ if (checkout) report.checkout = checkout;
497
+
403
498
  if (kind === "working") {
404
499
  await collectWorkingSections(report, root, pathValue);
405
500
  } else if (kind === "companion" && root.config) {
@@ -559,6 +654,31 @@ function renderClaudePlugins(
559
654
  ].join("\n");
560
655
  }
561
656
 
657
+ const CHECKOUT_ROLES: Record<DoctorCheckout["role"], (checkout: DoctorCheckout) => string> = {
658
+ registered: ({ repositoryId }) => `the Registered Checkout of ${repositoryId}`,
659
+ other: ({ repositoryId }) => `another Checkout of ${repositoryId}, adopted from its entry`,
660
+ "not-recognized": () => "a linked worktree its clone no longer recognizes",
661
+ };
662
+
663
+ function renderCheckout(checkout: DoctorCheckout): string {
664
+ const lines = [
665
+ renderKeyValueTable([
666
+ ["Checkout", checkout.root],
667
+ ["Role", CHECKOUT_ROLES[checkout.role](checkout)],
668
+ ["Registered Checkout", checkout.registeredCheckout ?? "none"],
669
+ ["Serving Claude Wrap", checkout.servingClaudeWrap],
670
+ ]),
671
+ ];
672
+ if (checkout.role === "not-recognized") {
673
+ lines.push(
674
+ "",
675
+ `Its record in the shared Git folder names another folder, so ${FRAMEWORK_NAME} treats it as no Checkout of the clone. Run \`git worktree repair\` in ${checkout.root}.`,
676
+ );
677
+ }
678
+ if (checkout.servingWrapWarning) lines.push("", `Warning: ${checkout.servingWrapWarning}`);
679
+ return lines.join("\n");
680
+ }
681
+
562
682
  function renderHumanReport(report: DoctorReport): void {
563
683
  console.log("Mate Doctor");
564
684
  console.log("");
@@ -657,6 +777,8 @@ function renderHumanReport(report: DoctorReport): void {
657
777
  );
658
778
  }
659
779
 
780
+ if (report.checkout) printSection("Checkout", renderCheckout(report.checkout));
781
+
660
782
  printSection(
661
783
  "Resolution Failures",
662
784
  report.resolutionFailures.length > 0