@uniqbit/mate-core 1.0.0-canary.2 → 1.0.0-canary.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +1 -1
  2. package/claude-plugin/hooks/hooks.json +21 -1
  3. package/claude-plugin/hooks/session-attention.mjs +10 -0
  4. package/claude-plugin/hooks/session-end.mjs +9 -0
  5. package/claude-plugin/hooks/session-guidance.mjs +1 -1
  6. package/opencode-plugin/src/server.ts +13 -2
  7. package/opencode-plugin/src/tui.tsx +1 -1
  8. package/opencode-plugin/tui.tsx +2 -1
  9. package/package.json +1 -1
  10. package/src/cli/commands/artifact/delivery/archive.ts +2 -2
  11. package/src/cli/commands/artifact/delivery/link.ts +22 -5
  12. package/src/cli/commands/artifact/delivery/output.ts +9 -1
  13. package/src/cli/commands/artifact/finish/openspec.ts +1 -3
  14. package/src/cli/commands/companion/companion.ts +1 -1
  15. package/src/cli/commands/companion/link.ts +36 -4
  16. package/src/cli/commands/companion/open.ts +40 -12
  17. package/src/cli/commands/doctor.ts +122 -0
  18. package/src/cli/commands/session/prepare.ts +32 -4
  19. package/src/cli/commands/session/registry.ts +90 -0
  20. package/src/cli/commands/studio/companion-removal.ts +79 -0
  21. package/src/cli/commands/studio/mate-inventory.ts +1 -1
  22. package/src/cli/commands/studio/payload.ts +12 -1
  23. package/src/cli/commands/studio/server.ts +39 -16
  24. package/src/cli/commands/studio/services.ts +20 -0
  25. package/src/cli/commands/studio/skill-files.ts +133 -0
  26. package/src/cli/commands/studio/vault.ts +218 -44
  27. package/src/cli/commands/studio/views/model.ts +0 -5
  28. package/src/cli/commands/studio/views/vault/markdown-tree.ts +255 -4
  29. package/src/cli/commands/unwrap.ts +8 -0
  30. package/src/cli/commands/update.ts +26 -8
  31. package/src/cli/commands/vscode/setup.ts +155 -0
  32. package/src/cli/commands/vscode/vsix.ts +73 -0
  33. package/src/cli/commands/working/cleanup.ts +34 -10
  34. package/src/cli/commands/working/worktree.ts +58 -8
  35. package/src/cli/commands/wrap.ts +33 -7
  36. package/src/cli/main.ts +9 -2
  37. package/src/cli/usage.ts +6 -1
  38. package/src/hooks/companion-instructions.ts +19 -11
  39. package/src/hooks/hook-io.ts +15 -0
  40. package/src/hooks/session-banner.ts +5 -3
  41. package/src/hooks/session-end.ts +10 -0
  42. package/src/hooks/session-guidance.ts +10 -6
  43. package/src/hooks/session-prepare.ts +47 -31
  44. package/src/hooks/session-register.ts +199 -0
  45. package/src/hooks/tokensave-route.ts +7 -3
  46. package/src/hooks/validate-artifact-path.ts +9 -2
  47. package/src/lib/delivery/archive-change.ts +0 -1
  48. package/src/lib/delivery/branches.ts +15 -0
  49. package/src/lib/delivery/record-delivery.ts +94 -39
  50. package/src/lib/delivery/record.ts +30 -28
  51. package/src/lib/delivery/refresh.ts +37 -17
  52. package/src/lib/delivery/resolve-branch.ts +258 -37
  53. package/src/lib/factory/outcomes/index.ts +11 -1
  54. package/src/lib/factory/runtime.ts +10 -1
  55. package/src/lib/opencode-server.ts +238 -0
  56. package/src/lib/orchestrator/adapters/claude.ts +147 -2
  57. package/src/lib/orchestrator/adapters/opencode.ts +53 -2
  58. package/src/lib/orchestrator/checkout-adoption.ts +125 -0
  59. package/src/lib/orchestrator/companion-registry-store.ts +6 -2
  60. package/src/lib/orchestrator/editor.ts +2 -2
  61. package/src/lib/orchestrator/framework-context.ts +26 -14
  62. package/src/lib/orchestrator/global-config-store.ts +11 -0
  63. package/src/lib/orchestrator/launcher.ts +15 -2
  64. package/src/lib/orchestrator/projection-claude-links.ts +52 -5
  65. package/src/lib/orchestrator/projection-claude-skills.ts +28 -2
  66. package/src/lib/orchestrator/projection-companion-link.ts +12 -1
  67. package/src/lib/orchestrator/registry-checkouts.ts +177 -0
  68. package/src/lib/orchestrator/repository-link.ts +216 -57
  69. package/src/lib/orchestrator/serving-claude-wrap.ts +43 -0
  70. package/src/lib/orchestrator/session-context-link.ts +11 -5
  71. package/src/lib/orchestrator/session-prepare.ts +36 -6
  72. package/src/lib/orchestrator/types.ts +5 -0
  73. package/src/lib/orchestrator/workspace-inventory.ts +5 -1
  74. package/src/lib/public-npm.ts +17 -0
  75. package/src/lib/session-attribution.ts +52 -0
  76. package/src/lib/session-state.ts +285 -0
  77. package/src/lib/session-stop.ts +64 -0
  78. package/src/lib/workset/record.ts +20 -0
  79. package/src/lib/workset/worktree.ts +85 -17
  80. package/src/opencode/background-server.ts +145 -0
  81. package/src/opencode/companion-hooks.ts +3 -1
  82. package/src/opencode/companion-policy.ts +2 -2
  83. package/src/opencode/projected-guidance.ts +2 -1
  84. package/src/opencode/session-register.ts +176 -0
  85. package/src/opencode/tui.tsx +19 -29
  86. package/src/runtime/claude-delivery-plan.ts +14 -3
  87. package/src/runtime/current-branch.ts +10 -0
  88. package/src/runtime/env.ts +13 -7
  89. package/src/runtime/git-layout.ts +164 -17
  90. package/src/runtime/launch-env-guard.ts +65 -0
  91. package/src/runtime/opencode-server-record.ts +136 -0
  92. package/src/runtime/projection.ts +40 -6
  93. package/src/runtime/repo-local.ts +6 -1
  94. package/src/runtime/serving-claude-wrap.ts +28 -0
  95. package/src/runtime/session-context.ts +4 -3
  96. package/src/runtime/session-registry.ts +434 -0
  97. package/src/runtime/tokensave-route.ts +10 -5
  98. package/src/runtime/wrap-state.ts +31 -0
  99. package/src/studio.ts +2 -0
  100. package/src/templates/mate-skills/agents/mate-apply-change/SKILL.md +49 -21
  101. package/src/templates/mate-skills/agents/mate-archive-change/SKILL.md +0 -5
  102. package/src/templates/mate-skills/agents/mate-propose-change/SKILL.md +2 -8
  103. package/src/templates/mate-skills/agents/mate-propose-change/references/mate-revise.md +1 -3
  104. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +2 -4
  105. package/src/templates/mate-skills/claude/mate-apply-change/SKILL.md +49 -21
  106. package/src/templates/mate-skills/claude/mate-archive-change/SKILL.md +0 -5
  107. package/src/templates/mate-skills/claude/mate-propose-change/SKILL.md +2 -8
  108. package/src/templates/mate-skills/claude/mate-propose-change/references/mate-revise.md +1 -3
  109. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +2 -4
  110. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +404 -30
  111. package/src/tools/setup/dynamic-plugins/hydrate.ts +4 -3
  112. package/src/tools/setup/providers/claude-plugin-hooks.ts +26 -0
  113. package/src/tools/setup/providers/claude.ts +21 -1
  114. package/studio-dist/client/assets/app-CdPiFv59.css +2 -0
  115. package/studio-dist/client/assets/button-BIIHE0EQ.js +3 -0
  116. package/studio-dist/client/assets/companion-view-DM6YyXaR.js +1 -0
  117. package/studio-dist/client/assets/delivery-path-DELxj0Av.js +1 -0
  118. package/studio-dist/client/assets/factory-BZy0E8ty.js +4 -0
  119. package/studio-dist/client/assets/index-B3wkMzjA.js +40 -0
  120. package/studio-dist/client/assets/markdown-view-pQ2Qp_i5.js +1 -0
  121. package/studio-dist/client/assets/panel-CbajlC3p.js +1 -0
  122. package/studio-dist/client/assets/{prepaint-CD5OpmTM.js → prepaint-CwSrpdFA.js} +7 -4
  123. package/studio-dist/client/assets/react-CN2GSx7x.js +1 -0
  124. package/studio-dist/client/assets/reports-DllhYQ5_.js +1 -0
  125. package/studio-dist/client/assets/routes-COm-G3mK.js +1 -0
  126. package/studio-dist/client/assets/skills-DmWAy-jZ.js +1 -0
  127. package/studio-dist/client/assets/specs-BG3Wi3ln.js +1 -0
  128. package/studio-dist/client/assets/steps-DFsH3Neu.js +1 -0
  129. package/studio-dist/client/assets/vault-B2q1nBY5.js +1 -0
  130. package/studio-dist/client/assets/warnings-BSXIyuSQ.js +1 -0
  131. package/studio-dist/client/assets/workflow-DlsQD6Hc.js +1 -0
  132. package/studio-dist/server/assets/{__23tanstack-start-server-fn-resolver-BQKuMdJW.js → __23tanstack-start-server-fn-resolver-M2GBs8s3.js} +179 -9
  133. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +35 -25
  134. package/studio-dist/server/assets/button-CIJqAhni.js +11929 -0
  135. package/studio-dist/server/assets/{companion-view-aBady57v.js → companion-view-DISASvdJ.js} +13 -7
  136. package/studio-dist/server/assets/companions-BYbHWKOZ.js +15 -0
  137. package/studio-dist/server/assets/delivery-path-C29fBynY.js +654 -0
  138. package/studio-dist/server/assets/{factory-DT3UzHlh.js → factory-DGPmNGbo.js} +1 -0
  139. package/studio-dist/server/assets/{factory-D6xnjedJ.js → factory-DUTa0eDs.js} +317 -530
  140. package/studio-dist/server/assets/markdown-view-Bn7xPdks.js +86 -0
  141. package/studio-dist/server/assets/panel-3Jmn4awF.js +169 -0
  142. package/studio-dist/server/assets/{prepaint-BMke0fo1.js → prepaint-DJfTQ_VH.js} +6 -2
  143. package/studio-dist/server/assets/{react-COs0LHn-.js → react-Ce6dj15C.js} +4 -9
  144. package/studio-dist/server/assets/reports-C06RXVE2.js +18 -0
  145. package/studio-dist/server/assets/reports-D6YMqhnO.js +142 -0
  146. package/studio-dist/server/assets/router-C8MGqlAY.js +13713 -0
  147. package/studio-dist/server/assets/routes-BcFgvqf7.js +622 -0
  148. package/studio-dist/server/assets/{shell-CboT2f66.js → shell-DS3wUexh.js} +1 -0
  149. package/studio-dist/server/assets/skills-BEnOxiDl.js +266 -0
  150. package/studio-dist/server/assets/skills-CtrBAtX3.js +28 -0
  151. package/studio-dist/server/assets/specs-C8rv34-5.js +211 -0
  152. package/studio-dist/server/assets/{start-BW5ovN0k.js → start-h3ICWwd2.js} +4 -1
  153. package/studio-dist/server/assets/steps-Dq_CwY_s.js +181 -0
  154. package/studio-dist/server/assets/{vault-BGulVoNh.js → vault-BmWnryh3.js} +16 -1
  155. package/studio-dist/server/assets/vault-Fvxt2Tzl.js +1032 -0
  156. package/studio-dist/server/assets/{views-Bd7cRr27.js → views-BgYa-za2.js} +1 -3
  157. package/studio-dist/server/assets/warnings-DzR6fyZh.js +23 -0
  158. package/studio-dist/server/assets/workflow-liRYecHk.js +73 -0
  159. package/studio-dist/server/server.js +3 -157
  160. package/studio-dist/client/assets/companion-view-Csva26Ir.js +0 -1
  161. package/studio-dist/client/assets/delivery-path-DJMpRmiY.js +0 -1
  162. package/studio-dist/client/assets/factory-B7l9ZQyx.js +0 -4
  163. package/studio-dist/client/assets/index-n6uo_92S.js +0 -40
  164. package/studio-dist/client/assets/queries-CN3JwMBX.js +0 -1
  165. package/studio-dist/client/assets/react-CabXf2Ds.js +0 -1
  166. package/studio-dist/client/assets/report-time-Dc-KOqQu.js +0 -1
  167. package/studio-dist/client/assets/reports-C01RsnMA.js +0 -1
  168. package/studio-dist/client/assets/routes-4pbC-2Hj.js +0 -1
  169. package/studio-dist/client/assets/skills-CihQganl.js +0 -1
  170. package/studio-dist/client/assets/spec-areas-C2L48N4C.js +0 -1
  171. package/studio-dist/client/assets/specs-D24_35_K.js +0 -1
  172. package/studio-dist/client/assets/studio-DKxfi691.css +0 -1
  173. package/studio-dist/client/assets/studio-queries-rvbJupCy.js +0 -3
  174. package/studio-dist/client/assets/vault-Bd4CQiTK.js +0 -1
  175. package/studio-dist/client/assets/warnings-V_Ys51wJ.js +0 -1
  176. package/studio-dist/client/assets/workflow-BJejeVwQ.js +0 -1
  177. package/studio-dist/server/assets/delivery-path-BkKNjgkf.js +0 -778
  178. package/studio-dist/server/assets/queries-Ag2iL8q2.js +0 -107
  179. package/studio-dist/server/assets/report-time-DAfzln-N.js +0 -8
  180. package/studio-dist/server/assets/reports-BnUNJVtx.js +0 -126
  181. package/studio-dist/server/assets/router-BH--drIx.js +0 -4298
  182. package/studio-dist/server/assets/routes-khSDK1bV.js +0 -361
  183. package/studio-dist/server/assets/skills-MWYnWoKs.js +0 -106
  184. package/studio-dist/server/assets/spec-areas-DcnO6vW-.js +0 -16
  185. package/studio-dist/server/assets/specs-DE3w8hZP.js +0 -155
  186. package/studio-dist/server/assets/studio-queries-CLnP9kGu.js +0 -3365
  187. package/studio-dist/server/assets/vault-CuyyhLyB.js +0 -832
  188. package/studio-dist/server/assets/warnings-BH05rOuG.js +0 -15
  189. package/studio-dist/server/assets/workflow-BSuIKWqH.js +0 -42
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Keeps Claude sessions an editor plugin started current in the Mate session
3
+ * registry, from Claude's own hook events. Any other session writes nothing.
4
+ */
5
+ import {
6
+ addSession,
7
+ endSession,
8
+ isRegistered,
9
+ patchSession,
10
+ refreshSession,
11
+ startedByEditor,
12
+ type RegisteredSession,
13
+ type SessionInput,
14
+ type WriteOptions,
15
+ } from "../runtime/session-registry";
16
+ import { currentBranch } from "../runtime/current-branch";
17
+ import { PROJECTED_FLAG } from "../runtime/projected-flag";
18
+ import { resolveProjection } from "../runtime/projection";
19
+ import { readWrapStateSync } from "../runtime/wrap-state";
20
+ import { hookOutcome, runHook, type HookCall, type HookEnv, type HookOutcome } from "./hook-io";
21
+
22
+ export interface SessionRegisterDeps {
23
+ register: (input: SessionInput) => Promise<unknown>;
24
+ /** Updates a registered session; writes nothing for any other. */
25
+ refresh: (input: SessionInput) => Promise<unknown>;
26
+ registered: (id: string) => Promise<boolean>;
27
+ end: (id: string) => Promise<unknown>;
28
+ patch: (id: string, patch: Partial<RegisteredSession>) => Promise<unknown>;
29
+ branch: (cwd: string) => Promise<string | null>;
30
+ /** True when the Working Repository at `dir` is wrapped for Claude, so the wrap's hook copy runs. */
31
+ wrappedForClaude: (dir: string) => boolean;
32
+ now: () => Date;
33
+ }
34
+
35
+ /** Hooks skip a write they cannot lock within 2 s; the next event registers again. */
36
+ const HOOK_WRITE: WriteOptions = { lock: { waitMs: 2000 } };
37
+
38
+ export const sessionRegisterDeps: SessionRegisterDeps = {
39
+ register: (input) => addSession(input, HOOK_WRITE),
40
+ refresh: (input) => refreshSession(input, HOOK_WRITE),
41
+ registered: (id) => isRegistered(id, HOOK_WRITE),
42
+ end: (id) => endSession(id, HOOK_WRITE),
43
+ patch: (id, patch) => patchSession(id, patch, HOOK_WRITE),
44
+ branch: currentBranch,
45
+ wrappedForClaude: (dir) => {
46
+ const projection = resolveProjection(dir);
47
+ return !!projection && readWrapStateSync(projection.repoRoot).runtimes.has("claude");
48
+ },
49
+ now: () => new Date(),
50
+ };
51
+
52
+ interface ClaudeHookInput {
53
+ session_id?: unknown;
54
+ cwd?: unknown;
55
+ transcript_path?: unknown;
56
+ }
57
+
58
+ function stringField(value: unknown): string | undefined {
59
+ return typeof value === "string" && value.length > 0 ? value : undefined;
60
+ }
61
+
62
+ function pidOf(env: HookEnv): number | undefined {
63
+ const pid = Number(env.CLAUDE_PID);
64
+ return Number.isInteger(pid) && pid > 0 ? pid : undefined;
65
+ }
66
+
67
+ /**
68
+ * Registers the session of a `SessionStart` event when an editor plugin started
69
+ * it, else refreshes it if registered (a resume). Never throws: a registry
70
+ * failure must not touch the session.
71
+ */
72
+ export async function registerClaudeSession(
73
+ env: HookEnv,
74
+ cwd: string,
75
+ input: unknown,
76
+ deps: SessionRegisterDeps = sessionRegisterDeps,
77
+ ): Promise<void> {
78
+ const event = (input ?? {}) as ClaudeHookInput;
79
+ const id = stringField(event.session_id);
80
+ if (!id) return;
81
+ const dir = stringField(event.cwd) ?? cwd;
82
+ try {
83
+ const editor = startedByEditor(env);
84
+ // Any other session costs one registry read, no Git call.
85
+ if (!editor && !(await deps.registered(id))) return;
86
+ const branch = await deps.branch(dir).catch(() => null);
87
+ const transcript = stringField(event.transcript_path);
88
+ const pid = pidOf(env);
89
+ const entry: SessionInput = {
90
+ id,
91
+ runtime: "claude",
92
+ cwd: dir,
93
+ origin: "editor",
94
+ ...(pid !== undefined ? { pid } : {}),
95
+ ...(branch ? { branch } : {}),
96
+ ...(transcript ? { transcript } : {}),
97
+ };
98
+ await (editor ? deps.register(entry) : deps.refresh(entry));
99
+ } catch {
100
+ /* best-effort */
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Legacy rule: wraps before `--projected` registered this copy bare, and only
106
+ * this hook re-wraps them. So a bare copy counts as the wrap's unless
107
+ * `CLAUDE_PLUGIN_ROOT`, set for plugin hooks only, marks it as the plugin's.
108
+ * Lives here, not in `session-prepare`, so the recording hooks load light.
109
+ */
110
+ export function isWrapCopy({ argv, env }: Pick<HookCall, "argv" | "env">): boolean {
111
+ return argv.includes(PROJECTED_FLAG) || !env.CLAUDE_PLUGIN_ROOT;
112
+ }
113
+
114
+ /**
115
+ * Which hook copy registers: the wrap's always; the plugin's only where no wrap
116
+ * copy runs, i.e. a Mate launch in a repository not wrapped for Claude.
117
+ */
118
+ export function registersHere(
119
+ wrapCopy: boolean,
120
+ dir: string,
121
+ deps: Pick<SessionRegisterDeps, "wrappedForClaude"> = sessionRegisterDeps,
122
+ ): boolean {
123
+ if (wrapCopy) return true;
124
+ try {
125
+ return !deps.wrappedForClaude(dir);
126
+ } catch {
127
+ return true;
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Applies `write` to the event's session when this hook copy records; always
133
+ * an empty outcome, and a failed write is dropped. The registry read comes
134
+ * first: most sessions are not registered, and the wrap check reads files.
135
+ */
136
+ async function recordForSession(
137
+ call: HookCall,
138
+ wrapCopy: boolean,
139
+ deps: SessionRegisterDeps,
140
+ write: (id: string) => Promise<unknown>,
141
+ ): Promise<HookOutcome> {
142
+ const event = (call.input ?? {}) as ClaudeHookInput;
143
+ const id = stringField(event.session_id);
144
+ const dir = stringField(event.cwd) ?? call.cwd;
145
+ if (!id || !(await deps.registered(id).catch(() => false))) return hookOutcome(null);
146
+ if (registersHere(wrapCopy, dir, deps)) await write(id).catch(() => {});
147
+ return hookOutcome(null);
148
+ }
149
+
150
+ /** `SessionEnd`: records `endedAt` for a registered session. */
151
+ export function runSessionEndHook(
152
+ call: HookCall,
153
+ wrapCopy: boolean,
154
+ deps: SessionRegisterDeps = sessionRegisterDeps,
155
+ ): Promise<HookOutcome> {
156
+ return recordForSession(call, wrapCopy, deps, (id) => deps.end(id));
157
+ }
158
+
159
+ /** `Notification`: records when the session asked the user for input. */
160
+ export function runNotificationHook(
161
+ call: HookCall,
162
+ wrapCopy: boolean,
163
+ deps: SessionRegisterDeps = sessionRegisterDeps,
164
+ ): Promise<HookOutcome> {
165
+ return recordForSession(call, wrapCopy, deps, (id) =>
166
+ deps.patch(id, { attentionAt: deps.now().toISOString() }),
167
+ );
168
+ }
169
+
170
+ type RecordingHook = (call: HookCall, wrapCopy: boolean) => Promise<HookOutcome>;
171
+
172
+ /** Shim entry for a recording hook; exits zero even when reading its input fails. */
173
+ function runRecordingHook(
174
+ hook: RecordingHook,
175
+ copyOf: (call: HookCall) => boolean,
176
+ argv: readonly string[],
177
+ ): Promise<number> {
178
+ return runHook(
179
+ (input) => {
180
+ const call = { env: process.env, cwd: process.cwd(), argv, input };
181
+ return hook(call, copyOf(call));
182
+ },
183
+ () => hookOutcome(null),
184
+ );
185
+ }
186
+
187
+ export function runEnd(
188
+ copyOf: (call: HookCall) => boolean,
189
+ argv: readonly string[] = process.argv.slice(2),
190
+ ): Promise<number> {
191
+ return runRecordingHook(runSessionEndHook, copyOf, argv);
192
+ }
193
+
194
+ export function runNotification(
195
+ copyOf: (call: HookCall) => boolean,
196
+ argv: readonly string[] = process.argv.slice(2),
197
+ ): Promise<number> {
198
+ return runRecordingHook(runNotificationHook, copyOf, argv);
199
+ }
@@ -11,14 +11,18 @@ interface TokensaveHookInput {
11
11
  /**
12
12
  * `updatedInput` when the call should run against the session directory's
13
13
  * worktree, else no output. Never a permission decision: the call keeps its
14
- * own permission flow. Input-pure, so the plugin copy and a carried copy
15
- * emit the same rewrite and the call is routed once either way.
14
+ * own permission flow. Input-pure apart from `CLAUDE_PROJECT_DIR`, the start
15
+ * directory whose checkout the MCP server serves, so the plugin copy and a
16
+ * carried copy emit the same rewrite and the call is routed once either way.
16
17
  */
17
18
  export function buildTokensaveRoute(input: unknown, deps?: RouteDeps): HookOutcome {
18
19
  const { cwd, tool_name: tool, tool_input: toolInput } = (input ?? {}) as TokensaveHookInput;
19
20
  const updatedInput =
20
21
  typeof cwd === "string" && typeof tool === "string"
21
- ? routeTokensaveInput(tool, cwd, toolInput, deps)
22
+ ? routeTokensaveInput(tool, cwd, toolInput, {
23
+ servedDirectory: process.env.CLAUDE_PROJECT_DIR,
24
+ ...deps,
25
+ })
22
26
  : undefined;
23
27
  return hookOutcome(
24
28
  updatedInput ? { hookSpecificOutput: { hookEventName: "PreToolUse", updatedInput } } : null,
@@ -17,10 +17,11 @@ import { checkCommitAttribution } from "../runtime/commit-attribution-guard";
17
17
  import { gitEnvironment } from "../runtime/companion-git";
18
18
  import { companionForkRefusal } from "../runtime/companion-sync";
19
19
  import { readCompanionRuntimeContext } from "../runtime/env";
20
+ import { guardLaunchEnvironment } from "../runtime/launch-env-guard";
20
21
  import { companionLinkPath } from "../runtime/repo-local";
21
22
  import { checkSecretAccess, type SecretToolCall } from "../runtime/secret-guard";
22
23
  import { stripHeredocBodies } from "../runtime/shell-heredoc";
23
- import type { HookEnv } from "./hook-io";
24
+ import { hookFolder, type HookEnv } from "./hook-io";
24
25
 
25
26
  export interface HookOutcome {
26
27
  exitCode: number;
@@ -372,7 +373,13 @@ export async function run(): Promise<number> {
372
373
  } catch {
373
374
  payload = {};
374
375
  }
375
- const outcome = await evaluate(payload, process.env);
376
+ // A background session can inherit another launch's environment from Claude's daemon.
377
+ guardLaunchEnvironment(process.env, process.cwd());
378
+ const outcome = await evaluate(
379
+ payload,
380
+ process.env,
381
+ hookFolder(payload, process.env, process.cwd()),
382
+ );
376
383
  if (outcome.stderr) process.stderr.write(outcome.stderr);
377
384
  return outcome.exitCode;
378
385
  }
@@ -81,7 +81,6 @@ export async function archiveChange(
81
81
  // The settlement covers every repository, so each delivery's merge state is refreshed.
82
82
  refreshAll: true,
83
83
  requireDelivery: !request.skipBranch,
84
- markSkipped: request.skipBranch === true,
85
84
  },
86
85
  deps,
87
86
  );
@@ -1,7 +1,9 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
3
 
4
+ import { readCompanionConfig } from "../orchestrator/config-store";
4
5
  import type { CapabilityConfig, TicketFormat } from "../orchestrator/types";
6
+ import { listRefsWith } from "./resolve-branch";
5
7
 
6
8
  export type { TicketFormat };
7
9
 
@@ -68,6 +70,16 @@ export function configuredTicketFormat(capabilities: readonly CapabilityConfig[]
68
70
  };
69
71
  }
70
72
 
73
+ /** Why `--ticket` is refused while the companion's tickets are off. */
74
+ export const TICKETS_OFF =
75
+ "tickets are off for this companion; set `ticket: jira` on the openspec capability (mate setup --ticket jira) to use one.";
76
+
77
+ /** The ticket setting in a companion's `framework.yaml`, as `mate artifact link` reads it. */
78
+ export async function companionTicketFormat(companionPath: string): Promise<TicketFormat> {
79
+ const config = await readCompanionConfig(companionPath);
80
+ return configuredTicketFormat(config.capabilities ?? []).format;
81
+ }
82
+
71
83
  /** Read-only local Git queries against a Working Repository. Nothing here touches the network. */
72
84
  export interface WorkingRepoGit {
73
85
  /** Checked-out branch, or null in a detached HEAD. */
@@ -82,6 +94,8 @@ export interface WorkingRepoGit {
82
94
  branchExists(branch: string): Promise<boolean>;
83
95
  /** True when the ref (`refs/heads/<b>`, `refs/remotes/origin/<b>`) resolves. */
84
96
  hasRef(ref: string): Promise<boolean>;
97
+ /** Full names of the refs under the given prefixes; empty when Git fails. */
98
+ listRefs?(prefixes: string[]): Promise<string[]>;
85
99
  }
86
100
 
87
101
  export function workingRepoGit(repoPath: string): WorkingRepoGit {
@@ -128,5 +142,6 @@ export function workingRepoGit(repoPath: string): WorkingRepoGit {
128
142
  );
129
143
  },
130
144
  hasRef,
145
+ listRefs: listRefsWith((args) => run(...args)),
131
146
  };
132
147
  }
@@ -1,7 +1,13 @@
1
- import { workingRepoGit, type ProtectionReason, type TicketFormat } from "./branches";
1
+ import {
2
+ workingRepoGit,
3
+ type ProtectionReason,
4
+ type TicketFormat,
5
+ type WorkingRepoGit,
6
+ } from "./branches";
2
7
  import { changeNameOf, locateChange, type ChangeLocation } from "../change-layout";
3
8
  import { companionRelative, type DeliveryEnvironment } from "./environment";
4
9
  import {
10
+ canaryTicketOf,
5
11
  findDelivery,
6
12
  ticketCandidateOf,
7
13
  legacyDeliveryBranch,
@@ -20,7 +26,12 @@ import {
20
26
  type RefreshAccess,
21
27
  type RefreshCache,
22
28
  } from "./refresh";
23
- import { resolveDeliveryBranch, type HasRef } from "./resolve-branch";
29
+ import {
30
+ mergeProbeWith,
31
+ resolveDeliveryBranch,
32
+ type HasRef,
33
+ type ListRefs,
34
+ } from "./resolve-branch";
24
35
  import {
25
36
  repositoryAccessFor,
26
37
  type RepositoryAccess,
@@ -34,7 +45,10 @@ export interface DeliveryEdit {
34
45
  pr?: string;
35
46
  /** The user's answer, recorded after any refresh with source `user`. */
36
47
  confirm?: MergeState;
37
- /** A Jira key recorded for the change; refused while the companion's tickets are off. */
48
+ /**
49
+ * Records the Delivery Branch resolved with this Jira key, which names a new branch
50
+ * `workset/<TICKET>-<id>`; the key itself is not stored. Refused while tickets are off.
51
+ */
38
52
  ticket?: string;
39
53
  }
40
54
 
@@ -59,14 +73,15 @@ export interface DeliveryRequest {
59
73
  includeArchived?: boolean;
60
74
  /** A change left without any delivery answers `needsBranch` and nothing is written. */
61
75
  requireDelivery?: boolean;
62
- /** Marks a record left without any delivery as `skipped`, so it stays held back. */
63
- markSkipped?: boolean;
64
76
  }
65
77
 
66
78
  export type DeliveryRefusal =
67
79
  | { reason: "unknown-change"; change: string }
68
80
  | { reason: "no-repository" }
69
81
  | { reason: "tickets-off" }
82
+ | { reason: "no-resolved-branch"; change: string; diagnostics: string[] }
83
+ /** `--ticket` on a repository whose delivery is direct or not applicable. */
84
+ | { reason: "settled-delivery"; change: string; repository: string; delivery: string }
70
85
  | { reason: "protected-branch"; branch: string; protection: ProtectionReason | null }
71
86
  | {
72
87
  reason: "no-delivery-branch";
@@ -77,13 +92,14 @@ export type DeliveryRefusal =
77
92
 
78
93
  export interface DeliveryResult {
79
94
  defaultBranch: string | null;
95
+ /** The `dependsOn` changes `defaultBranch` is inherited from; empty when it is not. */
96
+ inheritedFrom: string[];
80
97
  diagnostics: string[];
81
98
  /** The companion's ticket setting. */
82
99
  ticketFormat: TicketFormat;
83
100
  /**
84
- * With `ticketFormat` `jira` and no recorded ticket: the single Jira key in the branch
85
- * recorded for the repository, else in the Working Repository's current branch. Never
86
- * recorded without an explicit `--ticket`.
101
+ * With `ticketFormat` `jira`: the single Jira key in the branch recorded for the
102
+ * repository, else in the Working Repository's current branch, upper-cased.
87
103
  */
88
104
  ticketCandidate: string | null;
89
105
  change: string;
@@ -116,19 +132,32 @@ export interface RecordDeliveryDeps extends RepositoryAccessDeps {
116
132
  repositoryAccess?: (repository: string) => RepositoryAccess;
117
133
  }
118
134
 
119
- /** Ref lookup in the repository's local checkout; null when none is known. */
120
- async function hasRefIn(
135
+ /** Local Git of the repository's checkout; null when none is known. */
136
+ async function checkoutGit(
121
137
  environment: DeliveryEnvironment,
122
138
  repository: string,
123
- ): Promise<HasRef | null> {
139
+ ): Promise<WorkingRepoGit | null> {
124
140
  const working = environment.workingRepo;
125
- if (working?.slug && sameRepository(working.slug, repository)) {
126
- return (ref) => working.git.hasRef(ref);
127
- }
141
+ if (working?.slug && sameRepository(working.slug, repository)) return working.git;
128
142
  const checkout = await environment.checkoutOf?.(repository);
129
- if (!checkout) return null;
130
- const git = workingRepoGit(checkout);
131
- return (ref) => git.hasRef(ref);
143
+ return checkout ? workingRepoGit(checkout) : null;
144
+ }
145
+
146
+ /** Ref lookups in the repository's local checkout; null when none is known. */
147
+ async function refsIn(
148
+ environment: DeliveryEnvironment,
149
+ repository: string,
150
+ ): Promise<{ hasRef: HasRef; listRefs: ListRefs | null } | null> {
151
+ const git = await checkoutGit(environment, repository);
152
+ if (!git) return null;
153
+ return { hasRef: (ref) => git.hasRef(ref), listRefs: git.listRefs?.bind(git) ?? null };
154
+ }
155
+
156
+ /** A delivery a ticket must not replace: direct, or not applicable. */
157
+ function settledDelivery(record: DeliveryRecord, repository: string): string | null {
158
+ const delivery = findDelivery(record, repository);
159
+ if (delivery?.notApplicable !== undefined) return `not applicable (${delivery.notApplicable})`;
160
+ return delivery?.direct ? `${delivery.branch} [direct]` : null;
132
161
  }
133
162
 
134
163
  function hasDeliveryBranch(record: DeliveryRecord, repository: string): boolean {
@@ -165,16 +194,25 @@ export async function recordDelivery(
165
194
  if (edit.ticket !== undefined && ticketFormat === "none") {
166
195
  return { refusal: { reason: "tickets-off" } };
167
196
  }
168
- const repositoryEdits =
169
- edit.delivery !== undefined || edit.pr !== undefined || edit.confirm !== undefined;
170
- const edits = repositoryEdits || edit.ticket !== undefined || request.markSkipped === true;
171
- if (repositoryEdits && !repository) return { refusal: { reason: "no-repository" } };
197
+ const edits =
198
+ edit.delivery !== undefined ||
199
+ edit.pr !== undefined ||
200
+ edit.confirm !== undefined ||
201
+ edit.ticket !== undefined;
202
+ if (edits && !repository) return { refusal: { reason: "no-repository" } };
203
+ const refuseProtected = async (
204
+ repo: string,
205
+ branch: string,
206
+ direct: boolean,
207
+ ): Promise<{ refusal: DeliveryRefusal } | null> => {
208
+ const protection = await access(repo).protection(branch);
209
+ return protection.protected && !direct
210
+ ? { refusal: { reason: "protected-branch", branch, protection: protection.reason } }
211
+ : null;
212
+ };
172
213
  if (repository && edit.delivery && "branch" in edit.delivery) {
173
- const { branch, direct } = edit.delivery;
174
- const protection = await access(repository).protection(branch);
175
- if (protection.protected && !direct) {
176
- return { refusal: { reason: "protected-branch", branch, protection: protection.reason } };
177
- }
214
+ const refused = await refuseProtected(repository, edit.delivery.branch, edit.delivery.direct);
215
+ if (refused) return refused;
178
216
  }
179
217
 
180
218
  const refreshAccess: RefreshAccess = {
@@ -185,7 +223,9 @@ export async function recordDelivery(
185
223
  };
186
224
  const cache: RefreshCache = new Map();
187
225
  const resolved: Array<DeliveryResult & { dir: string }> = [];
188
- const hasRef = repository ? await hasRefIn(environment, repository) : null;
226
+ const refs = repository ? await refsIn(environment, repository) : null;
227
+ const local = repository ? await access(repository).local?.() : null;
228
+ const mergeProbe = local ? mergeProbeWith(local.git, local.defaultBranch) : null;
189
229
  const currentBranch = (await environment.workingRepo?.git.currentBranch()) ?? null;
190
230
 
191
231
  for (const { change, dir, archived } of located) {
@@ -193,8 +233,11 @@ export async function recordDelivery(
193
233
  const resolution = await resolveDeliveryBranch({
194
234
  companionPath: environment.companionPath,
195
235
  repository,
196
- hasRef,
236
+ hasRef: refs?.hasRef ?? null,
237
+ listRefs: refs?.listRefs ?? null,
238
+ mergeProbe,
197
239
  change,
240
+ ...(edit.ticket !== undefined ? { ticket: edit.ticket } : {}),
198
241
  });
199
242
  const diagnostics = resolution.diagnostics;
200
243
  const defaultBranch = resolution.branch;
@@ -204,13 +247,29 @@ export async function recordDelivery(
204
247
  `Recorded branch ${recordedBranch} differs from default ${defaultBranch}; preserving recorded delivery unless explicitly relinked.`,
205
248
  );
206
249
  }
207
- if (edit.ticket !== undefined) record = { ...record, ticket: edit.ticket };
208
- if (repository && edit.delivery) {
209
- record = upsertDelivery(record, repository, edit.delivery);
250
+ const canaryTicket = record.deliveries.length === 0 ? await canaryTicketOf(dir) : null;
251
+ if (canaryTicket) {
252
+ diagnostics.push(
253
+ `${change}'s record holds only ticket ${canaryTicket}, which Mate no longer reads; record the branch that delivered it with --branch.`,
254
+ );
255
+ }
256
+ let delivery = edit.delivery;
257
+ if (repository && edit.ticket !== undefined) {
258
+ const settled = settledDelivery(record, repository);
259
+ if (settled) {
260
+ return { refusal: { reason: "settled-delivery", change, repository, delivery: settled } };
261
+ }
262
+ if (!defaultBranch) return { refusal: { reason: "no-resolved-branch", change, diagnostics } };
263
+ const refused = await refuseProtected(repository, defaultBranch, false);
264
+ if (refused) return refused;
265
+ delivery = { branch: defaultBranch, direct: false };
266
+ }
267
+ if (repository && delivery) {
268
+ record = upsertDelivery(record, repository, delivery);
210
269
  // Recording a branch keeps its local tip, so a later deletion cannot hide the merge.
211
- if ("branch" in edit.delivery) {
270
+ if ("branch" in delivery) {
212
271
  const local = await access(repository).local?.();
213
- const head = await local?.git.tip(edit.delivery.branch);
272
+ const head = await local?.git.tip(delivery.branch);
214
273
  if (head) record = upsertDelivery(record, repository, { head });
215
274
  }
216
275
  }
@@ -225,9 +284,6 @@ export async function recordDelivery(
225
284
  }
226
285
  return { needsBranch: { change, record, defaultBranch, diagnostics, suggestedBranch } };
227
286
  }
228
- if (request.markSkipped && record.deliveries.length === 0) {
229
- record = { ...record, skipped: true };
230
- }
231
287
 
232
288
  if (repository && edit.pr !== undefined) {
233
289
  if (!hasDeliveryBranch(record, repository)) {
@@ -259,12 +315,11 @@ export async function recordDelivery(
259
315
  const candidateSource = recordedBranch ?? currentBranch;
260
316
  resolved.push({
261
317
  defaultBranch,
318
+ inheritedFrom: resolution.inheritedFrom,
262
319
  diagnostics,
263
320
  ticketFormat,
264
321
  ticketCandidate:
265
- ticketFormat === "jira" && !record.ticket && candidateSource
266
- ? ticketCandidateOf(candidateSource)
267
- : null,
322
+ ticketFormat === "jira" && candidateSource ? ticketCandidateOf(candidateSource) : null,
268
323
  dir,
269
324
  change: record.change,
270
325
  path: companionRelative(environment, dir),
@@ -60,24 +60,25 @@ export interface Delivery {
60
60
  export interface DeliveryRecord {
61
61
  version: 1;
62
62
  change: string;
63
- /** The change's Jira ticket; names its computed Delivery Branch. */
64
- ticket?: string;
65
- /** Set by `archive --skip-branch`, so a ticket-only record stays held back. */
66
- skipped?: true;
67
63
  deliveries: Delivery[];
68
64
  }
69
65
 
70
- const JIRA_KEY = /^[A-Z][A-Z0-9]+-\d+$/;
71
- const JIRA_KEYS = /(?<![A-Za-z0-9])[A-Z][A-Z0-9]+-\d+(?!\d)/g;
66
+ const JIRA_KEY = /^[A-Za-z][A-Za-z0-9]+-\d+$/;
67
+ const JIRA_KEYS = /(?<![A-Za-z0-9])[A-Za-z][A-Za-z0-9]+-\d+(?!\d)/g;
72
68
 
73
- /** A Jira issue key such as `ABC-123`. */
69
+ /** A Jira issue key such as `ABC-123`, in any case. */
74
70
  export function isJiraKey(value: string): boolean {
75
71
  return JIRA_KEY.test(value);
76
72
  }
77
73
 
78
- /** The single distinct Jira key in a branch name; null for none or several. */
74
+ /** A Jira key in its canonical upper-case form. */
75
+ export function normalizeJiraKey(value: string): string {
76
+ return value.toUpperCase();
77
+ }
78
+
79
+ /** The single distinct Jira key in a branch name, upper-cased; null for none or several. */
79
80
  export function ticketCandidateOf(branch: string): string | null {
80
- const keys = new Set(branch.match(JIRA_KEYS) ?? []);
81
+ const keys = new Set((branch.match(JIRA_KEYS) ?? []).map(normalizeJiraKey));
81
82
  return keys.size === 1 ? [...keys][0]! : null;
82
83
  }
83
84
 
@@ -125,15 +126,12 @@ export function isPublishable(status: DeliveryStatus): boolean {
125
126
  return status === "merged" || status === "not-applicable" || status === "legacy";
126
127
  }
127
128
 
128
- /** The warning a `legacy` archive publishes with; a ticket-only record names its ticket. */
129
- export function legacyDeliveryWarning(anchorName: string, record?: DeliveryRecord | null): string {
130
- if (record?.ticket) {
131
- return `${anchorName}: ticket ${record.ticket} records no delivery branch, so its merge was not checked; publishing it as a legacy archive.`;
132
- }
129
+ /** The warning a `legacy` archive publishes with. */
130
+ export function legacyDeliveryWarning(anchorName: string): string {
133
131
  return `${anchorName} has no delivery.yaml, so its merge was not checked; publishing it as a legacy archive.`;
134
132
  }
135
133
 
136
- /** `workset/<workset-id>`, or `workset/<TICKET>-<workset-id>` with a ticket. */
134
+ /** `workset/<workset-id>`, or `workset/<TICKET>-<workset-id>` when a ticket is given. */
137
135
  export function defaultDeliveryBranch(worksetId: string, ticket?: string | null): string {
138
136
  return ticket ? `workset/${ticket}-${worksetId}` : `workset/${worksetId}`;
139
137
  }
@@ -205,10 +203,6 @@ export function settleDelivery(
205
203
  const missing = scoped.filter((repository) => !findDelivery(record, repository));
206
204
  const unscoped = unscopedDeliveries(record, scoped);
207
205
  if (record.deliveries.length === 0) {
208
- // A ticket-only record was archived past Mate; it publishes like a legacy archive.
209
- if (record.ticket && !record.skipped) {
210
- return { status: "legacy", unsettled: [], missing: [], unscoped };
211
- }
212
206
  return { status: "unlinked", unsettled: missing, missing, unscoped };
213
207
  }
214
208
  const branches = record.deliveries.filter((entry) => entry.notApplicable === undefined);
@@ -323,27 +317,35 @@ export async function readDeliveryRecord(changeDir: string): Promise<DeliveryRec
323
317
  const document = parsed as Record<string, unknown>;
324
318
  const deliveries = document.deliveries ?? [];
325
319
  if (!Array.isArray(deliveries)) throw malformed(file, "deliveries must be a list");
326
- const ticket = optionalString(document.ticket, file, "ticket");
327
- if (ticket !== undefined && !isJiraKey(ticket)) {
328
- throw malformed(file, "ticket must be a Jira key such as ABC-123");
329
- }
320
+ // Canary records may carry `ticket` or `skipped`; both are ignored and dropped on write.
330
321
  return {
331
322
  version: 1,
332
323
  change:
333
324
  optionalString(document.change, file, "change") ?? changeNameOf(path.basename(changeDir)),
334
- ...(ticket !== undefined ? { ticket } : {}),
335
- ...(document.skipped === true ? { skipped: true as const } : {}),
336
325
  deliveries: deliveries.map((entry) => parseDelivery(entry, file)),
337
326
  };
338
327
  }
339
328
 
340
- /** Keys in file order: `version, change, ticket, skipped, deliveries`. */
329
+ /**
330
+ * The `ticket` a canary record carried, which is no longer read; null when there is none or
331
+ * the file cannot be read. Only explains why such a record settles as `unlinked`.
332
+ */
333
+ export async function canaryTicketOf(changeDir: string): Promise<string | null> {
334
+ try {
335
+ const document = parse(await fs.readFile(path.join(changeDir, DELIVERY_FILE), "utf8")) as {
336
+ ticket?: unknown;
337
+ } | null;
338
+ return typeof document?.ticket === "string" ? document.ticket : null;
339
+ } catch {
340
+ return null;
341
+ }
342
+ }
343
+
344
+ /** Keys in file order: `version, change, deliveries`. */
341
345
  function orderedRecord(record: DeliveryRecord): DeliveryRecord {
342
346
  return {
343
347
  version: record.version,
344
348
  change: record.change,
345
- ...(record.ticket ? { ticket: record.ticket } : {}),
346
- ...(record.skipped ? { skipped: true as const } : {}),
347
349
  deliveries: record.deliveries,
348
350
  };
349
351
  }