@uniqbit/mate-core 1.0.1-canary.0 → 1.0.1-canary.2

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 (45) hide show
  1. package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +1 -1
  2. package/package.json +1 -1
  3. package/src/cli/commands/artifact/finish/command.ts +18 -6
  4. package/src/cli/commands/artifact/finish/engine.ts +3 -1
  5. package/src/cli/commands/artifact/finish/git.ts +4 -2
  6. package/src/cli/commands/artifact/pending/discovery.ts +2 -2
  7. package/src/cli/commands/companion/link-refresh-report.ts +19 -0
  8. package/src/cli/commands/companion/link.ts +3 -2
  9. package/src/cli/commands/companion/sync.ts +25 -1
  10. package/src/cli/commands/companion/update.ts +1 -17
  11. package/src/cli/commands/plugin/plugin.ts +6 -1
  12. package/src/cli/commands/vscode/release-vsix.json +2 -2
  13. package/src/cli/main.ts +12 -2
  14. package/src/hooks/validate-artifact-path.ts +140 -22
  15. package/src/lib/delivery/record-delivery.ts +14 -0
  16. package/src/lib/delivery/staging/apply-chain.ts +61 -31
  17. package/src/lib/delivery/staging/pending.ts +13 -0
  18. package/src/lib/delivery/staging/project.ts +22 -6
  19. package/src/lib/delivery/staging/publish.ts +10 -11
  20. package/src/lib/delivery/staging/submit.ts +2 -8
  21. package/src/lib/orchestrator/companion-git-sync.ts +53 -24
  22. package/src/lib/orchestrator/projection-claude-skills.ts +13 -2
  23. package/src/lib/orchestrator/refresh-working-claude-links.ts +48 -30
  24. package/src/lib/workset/worktree.ts +1 -0
  25. package/src/opencode/companion-hooks.ts +3 -1
  26. package/src/runtime/artifact-refusal.ts +17 -7
  27. package/src/runtime/companion-guidance.ts +2 -2
  28. package/src/runtime/companion-sync.ts +24 -3
  29. package/src/runtime/shell-heredoc.ts +70 -28
  30. package/src/runtime/shell-variables.ts +257 -0
  31. package/src/templates/capabilities/openspec-cap/mate-full/schema.yaml +5 -0
  32. package/src/templates/capabilities/openspec-cap/mate-minimal/schema.yaml +7 -0
  33. package/src/templates/capabilities/react-doctor/mate-react-doctor/SKILL.md +20 -2
  34. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +2 -2
  35. package/src/templates/mate-skills/agents/mate-publish-artifact/references/openspec.md +6 -6
  36. package/src/templates/mate-skills/agents/mate-submit-change/SKILL.md +4 -4
  37. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +2 -2
  38. package/src/templates/mate-skills/claude/mate-publish-artifact/references/openspec.md +6 -6
  39. package/src/templates/mate-skills/claude/mate-submit-change/SKILL.md +4 -4
  40. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +30 -30
  41. package/src/tools/setup/capabilities/openspec.ts +3 -1
  42. package/src/tools/setup/capabilities/tokensave.ts +8 -1
  43. package/src/tools/setup/dynamic-plugins/verify.ts +1 -2
  44. package/src/tools/setup/mate.ts +2 -1
  45. package/src/tools/setup.ts +22 -1
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mate-companion-mentions",
3
- "version": "1.0.1-canary.0",
3
+ "version": "1.0.1-canary.2",
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"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uniqbit/mate-core",
3
- "version": "1.0.1-canary.0",
3
+ "version": "1.0.1-canary.2",
4
4
  "description": "Core framework and plugin APIs for Mate.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -91,6 +91,8 @@ const BOOLEAN_FLAGS: BooleanFlagSet = new Set([
91
91
  ...CONFIRM_FLAGS,
92
92
  ]);
93
93
 
94
+ const KNOWN_FLAGS: ReadonlySet<string> = new Set([...BOOLEAN_FLAGS, "type"]);
95
+
94
96
  async function defaultHasRemote(companionPath: string): Promise<boolean> {
95
97
  return (await stagingRemote(companionGit(companionPath, { prompt: "never" }))) !== null;
96
98
  }
@@ -153,6 +155,7 @@ function publicationResult(
153
155
  ...(publication.merges ? { merges: publication.merges } : {}),
154
156
  ...(publication.blocked ? { blocked: true } : {}),
155
157
  ...(publication.conflict ? { conflict: publication.conflict } : {}),
158
+ ...(publication.conflicts ? { conflicts: publication.conflicts } : {}),
156
159
  ...(publication.dependencies
157
160
  ? {
158
161
  dependencies: publication.dependencies.map((dependency) =>
@@ -298,7 +301,22 @@ export async function runArtifactPublishCommand(
298
301
  const emitOut = deps.stdout ?? ((line: string) => process.stdout.write(`${line}\n`));
299
302
  const emitErr = deps.stderr ?? ((line: string) => process.stderr.write(`${line}\n`));
300
303
 
304
+ /** Argument refusals go to stderr in every mode: nothing was resolved to report on. */
305
+ const refuse = (message: string): void => {
306
+ emitErr(message);
307
+ process.exitCode = 1;
308
+ };
309
+
301
310
  const flags = parseFlags(argv, BOOLEAN_FLAGS);
311
+ const unknown = Object.keys(flags).find((name) => !KNOWN_FLAGS.has(name));
312
+ if (unknown !== undefined) {
313
+ refuse(
314
+ unknown === "fetch"
315
+ ? 'mate: unknown option: --fetch. Fetch with `mate artifact link "<change>" --refresh --fetch --json`, then publish with --refresh again.'
316
+ : `mate: unknown option: --${unknown}`,
317
+ );
318
+ return;
319
+ }
302
320
  const noPush = flags["no-push"] === true;
303
321
  const json = flags.json === true;
304
322
  const type = typeof flags.type === "string" ? flags.type : DEFAULT_FINISHER_TYPE;
@@ -312,12 +330,6 @@ export async function runArtifactPublishCommand(
312
330
  ? positionals.filter((token) => !token.includes("/"))
313
331
  : positionals;
314
332
 
315
- /** Argument refusals go to stderr in every mode: nothing was resolved to report on. */
316
- const refuse = (message: string): void => {
317
- emitErr(message);
318
- process.exitCode = 1;
319
- };
320
-
321
333
  if (allMode && (specsMode || positionals.length > 0)) {
322
334
  refuse(
323
335
  "mate: --all already publishes both pending changes and drifted specs; drop the extra target.",
@@ -65,8 +65,10 @@ export interface FinishResult {
65
65
  dependencies?: FinishResult[];
66
66
  /** The conflict is recorded as `blocked` on the pending branch. */
67
67
  blocked?: boolean;
68
- /** A requirement changed since the delta was written, with the texts to resolve it from. */
68
+ /** The first of `conflicts`, kept for readers of one conflict. */
69
69
  conflict?: PublicationConflict;
70
+ /** One per stale requirement of the failing change, in scan order, at most `STALE_SCAN_LIMIT`. */
71
+ conflicts?: PublicationConflict[];
70
72
  /** True when a prior publication already committed or pushed this publication. */
71
73
  resumed: boolean;
72
74
  step: FinishStep;
@@ -32,7 +32,7 @@ export class RemoteFetchError extends Error {
32
32
  }
33
33
  }
34
34
 
35
- export type WorkingTreeChange = "new" | "modified";
35
+ export type WorkingTreeChange = "new" | "modified" | "deleted";
36
36
 
37
37
  /**
38
38
  * Git operations the finish engine needs, injectable for deterministic tests. All
@@ -139,7 +139,9 @@ function parsePorcelainPath(line: string): string {
139
139
  }
140
140
 
141
141
  function parsePorcelainKind(line: string): WorkingTreeChange {
142
- return /[?A]/.test(line.slice(0, 2)) ? "new" : "modified";
142
+ const status = line.slice(0, 2);
143
+ if (status.includes("D")) return "deleted";
144
+ return /[?A]/.test(status) ? "new" : "modified";
143
145
  }
144
146
 
145
147
  /** `ls-files --stage -z` output (`<mode> <sha> <stage>\t<path>`) as `update-index` arguments. */
@@ -27,7 +27,7 @@ export interface SpecAttribution {
27
27
  export interface UnattributedSpec {
28
28
  /** Companion-relative POSIX path of the canonical spec. */
29
29
  path: string;
30
- /** Whether the spec is new or already tracked and modified. */
30
+ /** Whether the spec is new, modified, or deleted from the working tree or index. */
31
31
  kind: WorkingTreeChange;
32
32
  /** Every archive naming this spec, oldest anchor first; empty when none does. */
33
33
  touchedByArchives: SpecAttribution[];
@@ -36,7 +36,7 @@ export interface UnattributedSpec {
36
36
  export interface UncommittedSpecChange {
37
37
  /** Companion-relative POSIX path of the canonical spec. */
38
38
  path: string;
39
- /** Whether the spec is new or already tracked and modified. */
39
+ /** Whether the spec is new, modified, or deleted from the working tree or index. */
40
40
  kind: WorkingTreeChange;
41
41
  }
42
42
 
@@ -0,0 +1,19 @@
1
+ import { FRAMEWORK_NAME } from "../../../framework";
2
+ import type { LinkRefreshResult } from "../../../lib/orchestrator/refresh-working-claude-links";
3
+
4
+ export function reportLinkRefresh(results: LinkRefreshResult[]): void {
5
+ for (const result of results) {
6
+ const where = result.repository?.path ?? "the linked Working Repositories";
7
+ if (result.outcome === "written") {
8
+ process.stdout.write(
9
+ `${FRAMEWORK_NAME}: refreshed Claude skill and command links in ${where}.\n`,
10
+ );
11
+ } else if (result.outcome === "current") {
12
+ process.stdout.write(`${FRAMEWORK_NAME}: Claude links already current in ${where}.\n`);
13
+ } else {
14
+ process.stderr.write(
15
+ `${FRAMEWORK_NAME}: warning: could not refresh Claude links in ${where}: ${result.error}\n`,
16
+ );
17
+ }
18
+ }
19
+ }
@@ -33,6 +33,7 @@ import type { CompanionSource, LinkedRepository } from "../../../lib/orchestrato
33
33
  import { invalidateInstallState } from "../../../lib/install";
34
34
  import { createStartupProgress } from "../../../lib/components/startup-progress";
35
35
  import { companionGit, describeGitFailure, type GitResult } from "../../../runtime/companion-git";
36
+ import { expandHome } from "../../../opencode/companion-policy";
36
37
 
37
38
  interface CompanionLinkCommandDeps {
38
39
  selectCompanionLinkInputs?: (
@@ -144,7 +145,7 @@ function chosenCompanionPaths(
144
145
  extractName: (url: string) => string | null,
145
146
  ): string[] {
146
147
  if (inputs.source === "git") {
147
- if (inputs.clonePath) return [path.resolve(inputs.clonePath)];
148
+ if (inputs.clonePath) return [path.resolve(expandHome(inputs.clonePath))];
148
149
  const repoName = extractName(inputs.gitUrl ?? "");
149
150
  return repoName ? [path.join(companionsDir, repoName)] : [];
150
151
  }
@@ -152,7 +153,7 @@ function chosenCompanionPaths(
152
153
  return (inputs.companionPaths ?? []).map((companionPath) => path.resolve(companionPath));
153
154
  }
154
155
  const localPath = inputs.localPath?.trim();
155
- return localPath ? [path.resolve(localPath)] : [];
156
+ return localPath ? [path.resolve(expandHome(localPath))] : [];
156
157
  }
157
158
 
158
159
  export const companionLinkCommandDeps = {
@@ -2,9 +2,13 @@ import { FRAMEWORK_NAME } from "../../../framework";
2
2
  import { createStartupProgress } from "../../../lib/components/startup-progress";
3
3
  import { settleLinkedAt } from "../../../lib/delivery/staging/settle-linked";
4
4
  import { syncCompanionGit } from "../../../lib/orchestrator/companion-git-sync";
5
- import { LaunchPreflightError } from "../../../lib/orchestrator/types";
5
+ import { readCompanionConfig } from "../../../lib/orchestrator/config-store";
6
+ import { refreshWorkingClaudeLinks } from "../../../lib/orchestrator/refresh-working-claude-links";
7
+ import { type FrameworkConfig, LaunchPreflightError } from "../../../lib/orchestrator/types";
6
8
  import { resolveCompanionRuntime } from "../../../runtime/env";
9
+ import { errorMessage } from "../../../runtime/error-message";
7
10
  import { readCompanionPolicy } from "../../../runtime/policy";
11
+ import { reportLinkRefresh } from "./link-refresh-report";
8
12
  import { resolveCompanionPath, resolveRepoPath } from "./tui";
9
13
 
10
14
  export interface CompanionSyncDeps {
@@ -15,6 +19,11 @@ export interface CompanionSyncDeps {
15
19
  syncCompanionGit: typeof syncCompanionGit;
16
20
  /** Records merges this machine's linked checkouts settle on the pending branch. */
17
21
  settleLinked: typeof settleLinkedAt;
22
+ loadConfig: (companionPath: string) => Promise<FrameworkConfig>;
23
+ refreshWorkingClaudeLinks: (
24
+ companionPath: string,
25
+ config: FrameworkConfig,
26
+ ) => ReturnType<typeof refreshWorkingClaudeLinks>;
18
27
  createProgress: typeof createStartupProgress;
19
28
  }
20
29
 
@@ -26,9 +35,23 @@ export const companionSyncDeps: CompanionSyncDeps = {
26
35
  readCompanionPolicy,
27
36
  syncCompanionGit,
28
37
  settleLinked: settleLinkedAt,
38
+ loadConfig: readCompanionConfig,
39
+ refreshWorkingClaudeLinks,
29
40
  createProgress: createStartupProgress,
30
41
  };
31
42
 
43
+ async function refreshClaudeLinks(companionPath: string): Promise<void> {
44
+ try {
45
+ const config = await companionSyncDeps.loadConfig(companionPath);
46
+ const results = await companionSyncDeps.refreshWorkingClaudeLinks(companionPath, config);
47
+ reportLinkRefresh(results.filter((result) => result.outcome !== "current"));
48
+ } catch (error) {
49
+ process.stderr.write(
50
+ `${FRAMEWORK_NAME}: warning: could not refresh Claude links: ${errorMessage(error)}\n`,
51
+ );
52
+ }
53
+ }
54
+
32
55
  /**
33
56
  * The Projection Root answers for a Wrapped Repository, which can never take
34
57
  * the launch path — so the command must resolve there too, not only through the
@@ -106,6 +129,7 @@ export async function runCompanionSyncCommand(): Promise<void> {
106
129
  process.stdout.write(`${FRAMEWORK_NAME}: recorded the merge of ${change}.\n`);
107
130
  }
108
131
  if (settled.warning) process.stderr.write(`${FRAMEWORK_NAME}: ${settled.warning}\n`);
132
+ await refreshClaudeLinks(companionPath);
109
133
  } catch (error) {
110
134
  progress.fail("git");
111
135
  if (error instanceof LaunchPreflightError) {
@@ -28,6 +28,7 @@ import {
28
28
  type CompanionSyncOptions,
29
29
  } from "../../../tools/setup";
30
30
  import type { ManagedOutputOwner, ManagedOutputReport } from "../../../tools/setup/plugin";
31
+ import { reportLinkRefresh } from "./link-refresh-report";
31
32
  import { confirm } from "../../confirm";
32
33
  import { defaultGitOps, type GitOps } from "../artifact/finish/git";
33
34
  import { resolveCompanionPath } from "./tui";
@@ -218,23 +219,6 @@ function listPaths(paths: string[]): string {
218
219
  return paths.map((changed) => ` ${changed}`).join("\n");
219
220
  }
220
221
 
221
- function reportLinkRefresh(results: LinkRefreshResult[]): void {
222
- for (const result of results) {
223
- const where = result.repository?.path ?? "the linked Working Repositories";
224
- if (result.outcome === "written") {
225
- process.stdout.write(
226
- `${FRAMEWORK_NAME}: refreshed Claude skill and command links in ${where}.\n`,
227
- );
228
- } else if (result.outcome === "current") {
229
- process.stdout.write(`${FRAMEWORK_NAME}: Claude links already current in ${where}.\n`);
230
- } else {
231
- process.stderr.write(
232
- `${FRAMEWORK_NAME}: warning: could not refresh Claude links in ${where}: ${result.error}\n`,
233
- );
234
- }
235
- }
236
- }
237
-
238
222
  /** Version precondition; returns the running version when the update may proceed. */
239
223
  async function checkVersion(progress: StartupProgressController): Promise<string | undefined> {
240
224
  const current = companionUpdateDeps.getCurrentVersion();
@@ -6,12 +6,17 @@ export async function runPluginCommand(
6
6
  argv: string[],
7
7
  deps: PluginInstallCommandDeps = {},
8
8
  ): Promise<void> {
9
+ if (!subcommand) {
10
+ console.error("mate: plugin command required. Use `mate plugin install <package>`.");
11
+ process.exitCode = 1;
12
+ return;
13
+ }
9
14
  switch (subcommand) {
10
15
  case "install":
11
16
  if (!(await runPluginInstallCommand(argv, deps))) process.exitCode = 1;
12
17
  return;
13
18
  default:
14
- console.error(`Unknown plugin command: ${subcommand ?? ""}`);
19
+ console.error(`Unknown plugin command: ${subcommand}`);
15
20
  console.error(usage());
16
21
  process.exitCode = 1;
17
22
  }
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "1.0.1-canary.0",
3
- "sha512": "sha512-5MM2kuh/ihpcEgM2DQhi0SeXbOahrasT0uaBgjUTdO7A5W1gComjzEcRbgqp2hikQH5K9NsrL9OiFun1Vwgx5A=="
2
+ "version": "1.0.1-canary.2",
3
+ "sha512": "sha512-2jfqdRqW5MddrYlP+r+wCjiJI5HWCSZN8ErbgGUFcTf/VbS6mDFw7sBKqyuaemhLOX94pVebOdnnHkU3h4TBoQ=="
4
4
  }
package/src/cli/main.ts CHANGED
@@ -19,7 +19,7 @@ import { runPluginCommand } from "./commands/plugin/plugin";
19
19
  import { runReportCommand } from "./commands/report";
20
20
  import { runSessionContextCommand } from "./commands/session/context";
21
21
  import { runSessionCommand } from "./commands/session/prepare";
22
- import { runStudioCommand } from "./commands/studio";
22
+ import { parseStudioServeArgs, runStudioCommand } from "./commands/studio";
23
23
  import { runTriageCommand } from "./commands/triage";
24
24
  import { runUpdateCommand } from "./commands/update";
25
25
  import { runUnwrapCommand } from "./commands/unwrap";
@@ -113,6 +113,7 @@ const MAIN_ANSWERS_HELP = new Set([
113
113
 
114
114
  /** True when `args` ask for help before a `--`, which passes what follows on untouched. */
115
115
  function asksForHelp(command: string, args: readonly string[]): boolean {
116
+ if (command === "cap") return args[0] === "--help" || args[0] === "-h";
116
117
  if (!MAIN_ANSWERS_HELP.has(command) || (command === "plugin" && args[0] === "install")) {
117
118
  return false;
118
119
  }
@@ -167,7 +168,16 @@ export async function main(argv = process.argv, deps: MainDeps = mainDeps): Prom
167
168
  // A package registers once per process, so a load here would pin the
168
169
  // pre-install version for the install's own sync; both installs load after their plugin step.
169
170
  if (!(command === "install" || (command === "plugin" && subcommand === "install"))) {
170
- await deps.hydrateDynamicPlugins({ includeLocal: !ignoresLocalPlugins });
171
+ const served =
172
+ command === "studio" && subcommand === "serve"
173
+ ? parseStudioServeArgs(rest, process.env)
174
+ : undefined;
175
+ const companionPath =
176
+ served && "launchCompanion" in served ? served.launchCompanion : undefined;
177
+ await deps.hydrateDynamicPlugins({
178
+ includeLocal: !ignoresLocalPlugins,
179
+ ...(companionPath ? { companionPath } : {}),
180
+ });
171
181
  }
172
182
 
173
183
  if (!command || command === "help" || command === "--help" || command === "-h" || helpRequest) {
@@ -22,7 +22,8 @@ import type { FrictionCheck } from "../runtime/friction-fingerprint";
22
22
  import { guardLaunchEnvironment } from "../runtime/launch-env-guard";
23
23
  import { companionLinkPath } from "../runtime/repo-local";
24
24
  import { checkSecretAccess, type SecretToolCall } from "../runtime/secret-guard";
25
- import { stripHeredocBodies } from "../runtime/shell-heredoc";
25
+ import { commandTextMask, heredocBodies, stripHeredocBodies } from "../runtime/shell-heredoc";
26
+ import { wordExpander } from "../runtime/shell-variables";
26
27
  import { hookFolder, type HookEnv } from "./hook-io";
27
28
 
28
29
  export interface HookOutcome {
@@ -53,8 +54,25 @@ const ARTIFACT_PATH_MARKERS = [
53
54
  ];
54
55
 
55
56
  /** `[ \t]`, not `\s`: a redirect or `tee` names its target on its own line. */
56
- const MD_REDIRECT_PATTERN = />{1,2}[ \t]*([^\s;|&<>]+\.md)\b/g;
57
- const MD_TEE_PATTERN = /\btee[ \t]+(?:-a[ \t]+)?([^\s;|&<>]+\.md)\b/g;
57
+ const MD_REDIRECT_PATTERN = new RegExp(
58
+ String.raw`>{1,2}\|?[ \t]*("[^"\n]*\.md"|'[^'\n]*\.md'|[^\s;|&<>]+\.md)(?=[\s;|&<>'"\`)\\]|$)`,
59
+ "g",
60
+ );
61
+ const TEE_PATTERN = /\btee[ \t]+([^|;&)\n]*)/g;
62
+ const TEE_WORD = String.raw`"[^"\n]*"|'[^'\n]*'|[^\s<>"']+`;
63
+ const TEE_INPUT_REDIRECT = String.raw`<+[ \t]*(?:${TEE_WORD})`;
64
+ const TEE_WORD_PATTERN = new RegExp(`${TEE_INPUT_REDIRECT}|${TEE_WORD}`, "g");
65
+ const SHELL_WORD = String.raw`(?:[^\s;&|()\`'"]*\/)?(?:sh|bash|dash|ksh|zsh|ash|mksh|yash|posh|csh|tcsh|fish)`;
66
+ const SHELL_C_OPTION = String.raw`(?:${SHELL_WORD}|su)(?:[ \t]+[^\s;&|()\`'"]+)*?[ \t]+-[A-Za-z]*c(?:[ \t]+--)?`;
67
+ const NESTED_SHELL_PATTERN = new RegExp(
68
+ String.raw`(?<![^\s;&|(\`])(?:${SHELL_C_OPTION}|eval)[ \t]+\$?(['"])`,
69
+ "g",
70
+ );
71
+ const COMMAND_PREFIX = String.raw`(?:[A-Za-z_]\w*=[^\s;&|]*|env|sudo|exec|command|xargs)[ \t]+`;
72
+ const RUNS_SHELL_PATTERN = new RegExp(
73
+ String.raw`(?:^|[|;&(\`\n])[ \t]*(?:${COMMAND_PREFIX})*(${SHELL_WORD}|eval)(?=[\s;&|)\`<>]|$)`,
74
+ "gd",
75
+ );
58
76
 
59
77
  export function artifactLikePath(filePath: string): boolean {
60
78
  if (!filePath) return false;
@@ -185,21 +203,32 @@ function isProductDocumentationPath(target: string, ctx: GuardContext): boolean
185
203
  return false;
186
204
  }
187
205
 
188
- function blockWrite(target: string, resolved: string, ctx: GuardContext): HookOutcome {
206
+ interface CommandTarget {
207
+ path: string;
208
+ unresolved?: string;
209
+ }
210
+
211
+ function blockWrite(
212
+ { path: target, unresolved }: CommandTarget,
213
+ resolved: string,
214
+ ctx: GuardContext,
215
+ ): HookOutcome {
189
216
  const refusal = artifactRefusal({
190
217
  target,
191
218
  resolved,
192
219
  companion: ctx.companion,
193
220
  repoRoot: ctx.repoRoot,
221
+ unresolved,
194
222
  });
195
223
  return { exitCode: 2, stderr: `${refusal}\n`, check: "artifact" };
196
224
  }
197
225
 
198
226
  function checkFilePath(
199
- filePath: string,
227
+ target: CommandTarget,
200
228
  ctx: GuardContext,
201
229
  allowExisting = false,
202
230
  ): HookOutcome | null {
231
+ const filePath = target.path;
203
232
  if (!filePath) return null;
204
233
 
205
234
  const normalized = resolveArtifactTarget(filePath, ctx.repoRoot);
@@ -220,7 +249,7 @@ function checkFilePath(
220
249
  return null;
221
250
  }
222
251
 
223
- return blockWrite(filePath, normalized, ctx);
252
+ return blockWrite(target, normalized, ctx);
224
253
  }
225
254
 
226
255
  /**
@@ -235,24 +264,109 @@ async function checkForkedCompanion(
235
264
  ctx: GuardContext,
236
265
  ): Promise<HookOutcome | null> {
237
266
  if (!filePath || !artifactLikePath(filePath)) return null;
238
- if (!isCompanionPath(resolveArtifactTarget(filePath, ctx.repoRoot), ctx)) return null;
267
+ const target = resolveArtifactTarget(filePath, ctx.repoRoot);
268
+ if (!isCompanionPath(target, ctx)) return null;
239
269
 
240
- const refusal = await companionForkRefusal(ctx.env, ctx.companion);
270
+ const refusal = await companionForkRefusal(ctx.env, ctx.companion, { target });
241
271
  return refusal ? { exitCode: 2, stderr: `${refusal}\n`, check: "fork" } : null;
242
272
  }
243
273
 
244
- /** Heredoc bodies are what a command writes, not what it runs: they are not scanned. */
245
- export function commandMatches(command: string): string[] {
246
- const targets: string[] = [];
247
- const commandText = stripHeredocBodies(command);
248
- for (const pattern of [MD_REDIRECT_PATTERN, MD_TEE_PATTERN]) {
249
- const matcher = new RegExp(pattern.source, pattern.flags);
250
- for (const match of commandText.matchAll(matcher)) {
251
- const target = match[1].trim().replace(/^["']+|["']+$/g, "");
252
- if (target) targets.push(target);
274
+ type Expand = ReturnType<typeof wordExpander>;
275
+
276
+ function nestedScript(text: string, start: number): { script: string; doubleQuoted: boolean } {
277
+ const quote = text[start];
278
+ if (quote === "'" && text[start - 1] === "$") {
279
+ let end = start + 1;
280
+ while (end < text.length && text[end] !== "'") end += text[end] === "\\" ? 2 : 1;
281
+ return { script: text.slice(start + 1, end).replace(/\\(.)/g, "$1"), doubleQuoted: false };
282
+ }
283
+ if (quote === "'") {
284
+ const end = text.indexOf("'", start + 1);
285
+ return { script: text.slice(start + 1, end === -1 ? undefined : end), doubleQuoted: false };
286
+ }
287
+ let end = start + 1;
288
+ while (end < text.length && text[end] !== '"') end += text[end] === "\\" ? 2 : 1;
289
+ const script = text.slice(start + 1, end).replace(/\\([$`"\\\n])/g, "$1");
290
+ return { script, doubleQuoted: true };
291
+ }
292
+
293
+ function shellWordOffsets(commandText: string, isCommand: boolean[]): number[] {
294
+ const offsets: number[] = [];
295
+ for (const match of commandText.matchAll(RUNS_SHELL_PATTERN)) {
296
+ const at = match.indices![1]![0];
297
+ if (isCommand[at]) offsets.push(at);
298
+ }
299
+ return offsets;
300
+ }
301
+
302
+ function scanTargets(
303
+ commandText: string,
304
+ isScanned: (offset: number) => boolean,
305
+ ): { raw: string; at: number }[] {
306
+ const found: { raw: string; at: number }[] = [];
307
+ for (const match of commandText.matchAll(MD_REDIRECT_PATTERN)) {
308
+ if (isScanned(match.index)) found.push({ raw: match[1]!, at: match.index });
309
+ }
310
+ for (const match of commandText.matchAll(TEE_PATTERN)) {
311
+ if (!isScanned(match.index)) continue;
312
+ const argsAt = match.index + match[0].length - match[1]!.length;
313
+ for (const word of match[1]!.matchAll(TEE_WORD_PATTERN)) {
314
+ if (/^[-<]/.test(word[0]) || !/\.md["']?$/.test(word[0])) continue;
315
+ found.push({ raw: word[0], at: argsAt + word.index });
253
316
  }
254
317
  }
255
- return targets;
318
+ return found;
319
+ }
320
+
321
+ function commandTargets(
322
+ command: string,
323
+ expandInCallingShell?: (raw: string) => ReturnType<Expand>,
324
+ ): CommandTarget[] {
325
+ if (!command.includes(".md")) return [];
326
+ const targets: CommandTarget[] = [];
327
+ const commandText = stripHeredocBodies(command);
328
+ const isCommand = commandTextMask(commandText);
329
+ let own: Expand | undefined;
330
+ const expand = (raw: string, offset: number) =>
331
+ expandInCallingShell
332
+ ? expandInCallingShell(raw)
333
+ : (own ??= wordExpander(commandText))(raw, offset);
334
+ const shellWords = shellWordOffsets(commandText, isCommand);
335
+ const scanQuotedText = shellWords.length > 0;
336
+ const found = scanTargets(commandText, (offset) => scanQuotedText || isCommand[offset]!);
337
+ for (const { raw, at } of found) {
338
+ const expanded = expand(raw, at);
339
+ const target =
340
+ expanded.unresolved === undefined
341
+ ? { path: expanded.text }
342
+ : { path: raw.replace(/^["']+|["']+$/g, ""), unresolved: expanded.unresolved };
343
+ if (target.path) targets.push(target);
344
+ }
345
+ for (const match of commandText.matchAll(new RegExp(NESTED_SHELL_PATTERN))) {
346
+ if (!isCommand[match.index]) continue;
347
+ const quoteAt = match.index + match[0].length - 1;
348
+ const { script, doubleQuoted } = nestedScript(commandText, quoteAt);
349
+ targets.push(
350
+ ...commandTargets(script, doubleQuoted ? (raw) => expand(raw, quoteAt) : undefined),
351
+ );
352
+ }
353
+ const shellLines = new Set(
354
+ shellWords.map((at) => commandText.slice(0, at).split("\n").length - 1),
355
+ );
356
+ for (const body of heredocBodies(command).filter((body) => shellLines.has(body.line))) {
357
+ targets.push(...commandTargets(body.text));
358
+ }
359
+ return uniqueTargets(targets);
360
+ }
361
+
362
+ function uniqueTargets(targets: CommandTarget[]): CommandTarget[] {
363
+ const seen = new Set<string>();
364
+ return targets.filter(({ path, unresolved }) => {
365
+ const key = `${path}\0${unresolved ?? ""}`;
366
+ if (seen.has(key)) return false;
367
+ seen.add(key);
368
+ return true;
369
+ });
256
370
  }
257
371
 
258
372
  const stringOrEmpty = (value: unknown) => (typeof value === "string" ? value : "");
@@ -361,7 +475,7 @@ function recordHookRefusal(
361
475
  const { toolName, toolInput } = call;
362
476
  const command = toolName === "Bash" ? stringOrEmpty(toolInput.command) : "";
363
477
  const paths = command
364
- ? commandMatches(command)
478
+ ? commandTargets(command).map((target) => target.path)
365
479
  : [toolInput.file_path, toolInput.notebook_path, toolInput.path].map(stringOrEmpty);
366
480
  return recordRefusal({
367
481
  check,
@@ -414,7 +528,11 @@ async function decide({ toolName, toolInput }: ToolCall, ctx: GuardContext): Pro
414
528
  if (toolName === "Write" || toolName === "Edit" || toolName === "MultiEdit") {
415
529
  const filePath = String(toolInput.file_path ?? "");
416
530
  /** The path refusal wins when both apply: its message is not replaced. */
417
- const outcome = checkFilePath(filePath, ctx, toolName === "Edit" || toolName === "MultiEdit");
531
+ const outcome = checkFilePath(
532
+ { path: filePath },
533
+ ctx,
534
+ toolName === "Edit" || toolName === "MultiEdit",
535
+ );
418
536
  return outcome ?? (await checkForkedCompanion(filePath, ctx)) ?? allow;
419
537
  }
420
538
 
@@ -423,12 +541,12 @@ async function decide({ toolName, toolInput }: ToolCall, ctx: GuardContext): Pro
423
541
  const attribution = checkCommitAttribution(command);
424
542
  if (attribution) return { exitCode: 2, stderr: `${attribution}\n`, check: "attribution" };
425
543
 
426
- const targets = commandMatches(command);
544
+ const targets = commandTargets(command);
427
545
  for (const target of targets) {
428
546
  const outcome = checkFilePath(target, ctx);
429
547
  if (outcome) return outcome;
430
548
  }
431
- for (const target of targets) {
549
+ for (const { path: target } of targets) {
432
550
  // oxlint-disable-next-line no-await-in-loop -- the first refusal wins
433
551
  const outcome = await checkForkedCompanion(target, ctx);
434
552
  if (outcome) return outcome;
@@ -324,6 +324,20 @@ export async function recordDelivery(
324
324
  };
325
325
  }
326
326
  }
327
+ const confirmOnly =
328
+ edit.confirm !== undefined &&
329
+ edit.delivery === undefined &&
330
+ edit.pr === undefined &&
331
+ edit.ticket === undefined;
332
+ if (!repository && confirmOnly) {
333
+ const recorded = new Set<string>();
334
+ for (const { dir, change } of located) {
335
+ for (const delivery of (await readOrUnlinkedRecord(dir, change)).deliveries) {
336
+ if (delivery.branch !== undefined) recorded.add(delivery.repository);
337
+ }
338
+ }
339
+ if (recorded.size === 1) repository = [...recorded][0]!;
340
+ }
327
341
  if (edits && !repository) return { refusal: { reason: "no-repository" } };
328
342
  const refuseProtected = async (
329
343
  repo: string,