@uniqbit/mate-core 1.0.0 → 1.0.1-canary.1

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 (46) 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/agent-selector.ts +16 -0
  4. package/src/cli/commands/artifact/finish/command.ts +18 -6
  5. package/src/cli/commands/artifact/finish/engine.ts +3 -1
  6. package/src/cli/commands/artifact/finish/git.ts +4 -2
  7. package/src/cli/commands/artifact/pending/discovery.ts +2 -2
  8. package/src/cli/commands/companion/link.ts +3 -2
  9. package/src/cli/commands/triage.ts +11 -23
  10. package/src/cli/commands/vscode/release-vsix.json +2 -2
  11. package/src/cli/commands/workflow/workflow.ts +3 -2
  12. package/src/cli/companion-selector.ts +26 -0
  13. package/src/cli/main.ts +12 -2
  14. package/src/hooks/validate-artifact-path.ts +79 -17
  15. package/src/lib/components/select-one.tsx +122 -0
  16. package/src/lib/delivery/record-delivery.ts +14 -0
  17. package/src/lib/delivery/staging/apply-chain.ts +60 -30
  18. package/src/lib/delivery/staging/pending.ts +13 -0
  19. package/src/lib/delivery/staging/project.ts +21 -6
  20. package/src/lib/delivery/staging/publish.ts +10 -11
  21. package/src/lib/delivery/staging/submit.ts +2 -8
  22. package/src/lib/orchestrator/companion-git-sync.ts +53 -24
  23. package/src/lib/workflow/handoff.ts +1 -1
  24. package/src/lib/workflow/position.ts +29 -2
  25. package/src/lib/workset/worktree.ts +1 -0
  26. package/src/opencode/companion-hooks.ts +3 -1
  27. package/src/runtime/artifact-refusal.ts +17 -7
  28. package/src/runtime/companion-guidance.ts +2 -2
  29. package/src/runtime/companion-sync.ts +21 -1
  30. package/src/runtime/shell-heredoc.ts +67 -26
  31. package/src/runtime/shell-variables.ts +257 -0
  32. package/src/templates/capabilities/openspec-cap/mate-full/schema.yaml +3 -0
  33. package/src/templates/capabilities/openspec-cap/mate-minimal/schema.yaml +4 -0
  34. package/src/templates/capabilities/react-doctor/mate-react-doctor/SKILL.md +20 -2
  35. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +2 -2
  36. package/src/templates/mate-skills/agents/mate-publish-artifact/references/openspec.md +6 -6
  37. package/src/templates/mate-skills/agents/mate-submit-change/SKILL.md +4 -4
  38. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +2 -2
  39. package/src/templates/mate-skills/claude/mate-publish-artifact/references/openspec.md +6 -6
  40. package/src/templates/mate-skills/claude/mate-submit-change/SKILL.md +4 -4
  41. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +30 -30
  42. package/src/tools/setup/capabilities/openspec.ts +3 -1
  43. package/src/tools/setup/capabilities/tokensave.ts +8 -1
  44. package/src/tools/setup/mate.ts +2 -1
  45. package/src/tools/setup.ts +22 -1
  46. package/src/cli/companion-selector.tsx +0 -139
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mate-companion-mentions",
3
- "version": "1.0.0",
3
+ "version": "1.0.1-canary.1",
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.0",
3
+ "version": "1.0.1-canary.1",
4
4
  "description": "Core framework and plugin APIs for Mate.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -0,0 +1,16 @@
1
+ import { selectOne } from "../lib/components/select-one";
2
+ import { TRIAGE_AGENT_NAMES, type FoundAgent } from "../lib/triage/launch";
3
+
4
+ /** `--version` lines carry extra text (`2.1.0 (Claude Code)`); show the number alone. */
5
+ export function agentLabel(found: FoundAgent): string {
6
+ const name = TRIAGE_AGENT_NAMES[found.agent];
7
+ const version = found.version?.match(/\d+\.\d+\S*/)?.[0];
8
+ return version ? `${name} ${version}` : name;
9
+ }
10
+
11
+ export function selectAgent(agents: FoundAgent[]): Promise<FoundAgent | null> {
12
+ return selectOne(agents, {
13
+ title: "Several agents are installed — pick one",
14
+ toItem: (found) => ({ key: found.agent, label: agentLabel(found) }),
15
+ });
16
+ }
@@ -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
 
@@ -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 = {
@@ -1,5 +1,3 @@
1
- import readline from "node:readline/promises";
2
-
3
1
  import { FRAMEWORK_NAME } from "../../framework";
4
2
  import { FrictionRefusal } from "../../lib/friction/fields";
5
3
  import { formatCommand } from "../../runtime/command-arg";
@@ -17,6 +15,7 @@ import {
17
15
  } from "../../lib/triage/prepare";
18
16
  import { recordTriageLauncher } from "../../lib/triage/session";
19
17
  import { currentSession } from "../../runtime/session-id";
18
+ import { selectAgent } from "../agent-selector";
20
19
  import { collectDoctorReport } from "./doctor";
21
20
 
22
21
  interface TriageArgs {
@@ -57,35 +56,23 @@ export interface TriageDeps {
57
56
  cwd?: string;
58
57
  env?: Record<string, string | undefined>;
59
58
  now?: Date;
60
- /** Asks which agent to start; null when no terminal can ask. Defaults to a prompt on a TTY stdin. */
59
+ /** Asks which agent to start; null when no terminal can ask. Defaults to a menu when stdin and stdout are TTYs. */
61
60
  ask?: AskAgent | null;
62
61
  collectDoctor?: (cwd: string) => Promise<unknown>;
63
62
  launch?: typeof launchAgent;
64
63
  }
65
64
 
66
- type AskAgent = (choices: TriageAgent[]) => Promise<TriageAgent | null>;
67
-
68
- const askAgent: AskAgent = async (choices) => {
69
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
70
- try {
71
- const answer = await rl.question(`Start which agent? (${choices.join("/")}) `);
72
- const picked = answer.trim().toLowerCase();
73
- return choices.find((choice) => choice === picked) ?? null;
74
- } finally {
75
- rl.close();
76
- }
77
- };
65
+ type AskAgent = (agents: FoundAgent[]) => Promise<FoundAgent | null>;
78
66
 
79
67
  async function chooseAgent(
80
68
  requested: TriageAgent | null,
81
69
  agents: FoundAgent[],
82
70
  ask: AskAgent | null,
83
71
  ): Promise<{ found: FoundAgent } | { error: string }> {
84
- const pick = (id: TriageAgent | null, error: string) => {
85
- const found = agents.find((agent) => agent.agent === id);
86
- return found ? { found } : { error };
87
- };
88
- if (requested) return pick(requested, `${TRIAGE_AGENT_NAMES[requested]} was not found on PATH.`);
72
+ if (requested) {
73
+ const found = agents.find((agent) => agent.agent === requested);
74
+ return found ? { found } : { error: `${TRIAGE_AGENT_NAMES[requested]} was not found on PATH.` };
75
+ }
89
76
  if (agents.length === 0) {
90
77
  return {
91
78
  error: `No agent was found: install ${TRIAGE_AGENTS.map((id) => TRIAGE_AGENT_NAMES[id]).join(" or ")}, or start your own agent with the prompt in prompt.md.`,
@@ -94,8 +81,8 @@ async function chooseAgent(
94
81
  if (agents.length === 1) return { found: agents[0]! };
95
82
  const flags = agents.map((agent) => `--agent ${agent.agent}`).join(" or ");
96
83
  if (!ask) return { error: `Several agents are installed; choose one with ${flags}.` };
97
- const picked = await ask(agents.map((agent) => agent.agent));
98
- return pick(picked, `No agent chosen; choose one with ${flags}.`);
84
+ const found = await ask(agents);
85
+ return found ? { found } : { error: `No agent chosen; choose one with ${flags}.` };
99
86
  }
100
87
 
101
88
  function printPaths(files: TriageSessionFiles): void {
@@ -152,7 +139,8 @@ export async function runTriageCommand(argv: string[] = [], deps: TriageDeps = {
152
139
  return;
153
140
  }
154
141
 
155
- const ask = deps.ask === undefined ? (process.stdin.isTTY ? askAgent : null) : deps.ask;
142
+ const terminal = Boolean(process.stdin.isTTY && process.stdout.isTTY);
143
+ const ask = deps.ask === undefined ? (terminal ? selectAgent : null) : deps.ask;
156
144
  const choice = await chooseAgent(args.agent, agents, ask);
157
145
  if ("error" in choice) {
158
146
  console.error(`${FRAMEWORK_NAME}: ${choice.error}`);
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "1.0.0",
3
- "sha512": "sha512-pUKQLcYiKxPD5TZmBeRaY9b49n2Jl7gXHfXThaTAOmDF3hA2pAyT0uEBMV4ZZmJ2M2oXmq+rxCf2Fzkwu3O77g=="
2
+ "version": "1.0.1-canary.1",
3
+ "sha512": "sha512-POY5kGVRAUOfB07GTSiaK3Z2rvGEn4R8eM3iV6epjxP6HaTC1+NEgsZP+II287gVtt7km4q3Vz7R/Hx09OvXJQ=="
4
4
  }
@@ -323,8 +323,9 @@ export interface ChangeNext {
323
323
  /**
324
324
  * @command mate workflow next <change>
325
325
  * @description Prints the stage a change is at and its next actions as a `## Next steps`
326
- * section, writing nothing: the hand-off `mate workflow done` would print, computed from the
327
- * declaration, the change's Delivery Record and its tasks alone, whatever a session wrote.
326
+ * section, writing nothing: the hand-off `mate workflow done` would print, less its
327
+ * `Start a fresh session` before apply, computed from the declaration, the change's Delivery
328
+ * Record and its tasks alone, whatever a session wrote.
328
329
  * @flags
329
330
  * - `--json` — emit a {@link ChangeNext}: `ok`, `change`, `stage`, `open`, `handoff`,
330
331
  * `actions` and `optional`.
@@ -0,0 +1,26 @@
1
+ import { selectOne, type SelectOneOptions } from "../lib/components/select-one";
2
+ import type { CompanionMatch } from "../lib/orchestrator/repository-link";
3
+
4
+ /**
5
+ * Prompts the user to pick one companion when the active working repo is
6
+ * linked from more than one companion's registry (`CompanionResolver`
7
+ * reports this via `ambiguousMatches`, since only one companion may be
8
+ * active for a repo at a time).
9
+ */
10
+ export function selectCompanion(
11
+ matches: CompanionMatch[],
12
+ options: SelectOneOptions = {},
13
+ ): Promise<CompanionMatch | null> {
14
+ return selectOne(
15
+ matches,
16
+ {
17
+ title: "Multiple companions link this repo — pick one",
18
+ toItem: (match) => ({
19
+ key: match.companionPath,
20
+ label: match.companionPath,
21
+ description: `(repo: ${match.repositoryId})`,
22
+ }),
23
+ },
24
+ options,
25
+ );
26
+ }
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, 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,11 @@ 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_WORD = String.raw`([^\s;|&<>]+\.md)(?=[\s;|&<>'"\`)\\]|$)`;
58
+ const MD_REDIRECT_PATTERN = new RegExp(String.raw`>{1,2}[ \t]*` + MD_WORD, "g");
59
+ const MD_TEE_PATTERN = new RegExp(String.raw`\btee[ \t]+(?:-a[ \t]+)?` + MD_WORD, "g");
60
+ /** Any shell's or `su`'s `-c` string, or an `eval` string. */
61
+ const NESTED_SHELL_PATTERN = /(?<![^\s;&|(`])(?:-[A-Za-z]*c(?:[ \t]+--)?|eval)[ \t]+\$?(['"])/g;
58
62
 
59
63
  export function artifactLikePath(filePath: string): boolean {
60
64
  if (!filePath) return false;
@@ -185,21 +189,32 @@ function isProductDocumentationPath(target: string, ctx: GuardContext): boolean
185
189
  return false;
186
190
  }
187
191
 
188
- function blockWrite(target: string, resolved: string, ctx: GuardContext): HookOutcome {
192
+ interface CommandTarget {
193
+ path: string;
194
+ unresolved?: string;
195
+ }
196
+
197
+ function blockWrite(
198
+ { path: target, unresolved }: CommandTarget,
199
+ resolved: string,
200
+ ctx: GuardContext,
201
+ ): HookOutcome {
189
202
  const refusal = artifactRefusal({
190
203
  target,
191
204
  resolved,
192
205
  companion: ctx.companion,
193
206
  repoRoot: ctx.repoRoot,
207
+ unresolved,
194
208
  });
195
209
  return { exitCode: 2, stderr: `${refusal}\n`, check: "artifact" };
196
210
  }
197
211
 
198
212
  function checkFilePath(
199
- filePath: string,
213
+ target: CommandTarget,
200
214
  ctx: GuardContext,
201
215
  allowExisting = false,
202
216
  ): HookOutcome | null {
217
+ const filePath = target.path;
203
218
  if (!filePath) return null;
204
219
 
205
220
  const normalized = resolveArtifactTarget(filePath, ctx.repoRoot);
@@ -220,7 +235,7 @@ function checkFilePath(
220
235
  return null;
221
236
  }
222
237
 
223
- return blockWrite(filePath, normalized, ctx);
238
+ return blockWrite(target, normalized, ctx);
224
239
  }
225
240
 
226
241
  /**
@@ -235,23 +250,66 @@ async function checkForkedCompanion(
235
250
  ctx: GuardContext,
236
251
  ): Promise<HookOutcome | null> {
237
252
  if (!filePath || !artifactLikePath(filePath)) return null;
238
- if (!isCompanionPath(resolveArtifactTarget(filePath, ctx.repoRoot), ctx)) return null;
253
+ const target = resolveArtifactTarget(filePath, ctx.repoRoot);
254
+ if (!isCompanionPath(target, ctx)) return null;
239
255
 
240
- const refusal = await companionForkRefusal(ctx.env, ctx.companion);
256
+ const refusal = await companionForkRefusal(ctx.env, ctx.companion, { target });
241
257
  return refusal ? { exitCode: 2, stderr: `${refusal}\n`, check: "fork" } : null;
242
258
  }
243
259
 
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[] = [];
260
+ type Expand = ReturnType<typeof wordExpander>;
261
+
262
+ function nestedScript(text: string, start: number): { script: string; doubleQuoted: boolean } {
263
+ const quote = text[start];
264
+ if (quote === "'" && text[start - 1] === "$") {
265
+ let end = start + 1;
266
+ while (end < text.length && text[end] !== "'") end += text[end] === "\\" ? 2 : 1;
267
+ return { script: text.slice(start + 1, end).replace(/\\(.)/g, "$1"), doubleQuoted: false };
268
+ }
269
+ if (quote === "'") {
270
+ const end = text.indexOf("'", start + 1);
271
+ return { script: text.slice(start + 1, end === -1 ? undefined : end), doubleQuoted: false };
272
+ }
273
+ let end = start + 1;
274
+ while (end < text.length && text[end] !== '"') end += text[end] === "\\" ? 2 : 1;
275
+ const script = text.slice(start + 1, end).replace(/\\([$`"\\\n])/g, "$1");
276
+ return { script, doubleQuoted: true };
277
+ }
278
+
279
+ function commandTargets(
280
+ command: string,
281
+ expandInCallingShell?: (raw: string) => ReturnType<Expand>,
282
+ ): CommandTarget[] {
283
+ if (!command.includes(".md")) return [];
284
+ const targets: CommandTarget[] = [];
247
285
  const commandText = stripHeredocBodies(command);
286
+ const isCommand = commandTextMask(commandText);
287
+ let own: Expand | undefined;
288
+ const expand = (raw: string, offset: number) =>
289
+ expandInCallingShell
290
+ ? expandInCallingShell(raw)
291
+ : (own ??= wordExpander(commandText))(raw, offset);
248
292
  for (const pattern of [MD_REDIRECT_PATTERN, MD_TEE_PATTERN]) {
249
293
  const matcher = new RegExp(pattern.source, pattern.flags);
250
294
  for (const match of commandText.matchAll(matcher)) {
251
- const target = match[1].trim().replace(/^["']+|["']+$/g, "");
252
- if (target) targets.push(target);
295
+ if (!isCommand[match.index]) continue;
296
+ const raw = match[1].trim();
297
+ const expanded = expand(raw, match.index);
298
+ const target =
299
+ expanded.unresolved === undefined
300
+ ? { path: expanded.text }
301
+ : { path: raw.replace(/^["']+|["']+$/g, ""), unresolved: expanded.unresolved };
302
+ if (target.path) targets.push(target);
253
303
  }
254
304
  }
305
+ for (const match of commandText.matchAll(new RegExp(NESTED_SHELL_PATTERN))) {
306
+ if (!isCommand[match.index]) continue;
307
+ const quoteAt = match.index + match[0].length - 1;
308
+ const { script, doubleQuoted } = nestedScript(commandText, quoteAt);
309
+ targets.push(
310
+ ...commandTargets(script, doubleQuoted ? (raw) => expand(raw, quoteAt) : undefined),
311
+ );
312
+ }
255
313
  return targets;
256
314
  }
257
315
 
@@ -361,7 +419,7 @@ function recordHookRefusal(
361
419
  const { toolName, toolInput } = call;
362
420
  const command = toolName === "Bash" ? stringOrEmpty(toolInput.command) : "";
363
421
  const paths = command
364
- ? commandMatches(command)
422
+ ? commandTargets(command).map((target) => target.path)
365
423
  : [toolInput.file_path, toolInput.notebook_path, toolInput.path].map(stringOrEmpty);
366
424
  return recordRefusal({
367
425
  check,
@@ -414,7 +472,11 @@ async function decide({ toolName, toolInput }: ToolCall, ctx: GuardContext): Pro
414
472
  if (toolName === "Write" || toolName === "Edit" || toolName === "MultiEdit") {
415
473
  const filePath = String(toolInput.file_path ?? "");
416
474
  /** The path refusal wins when both apply: its message is not replaced. */
417
- const outcome = checkFilePath(filePath, ctx, toolName === "Edit" || toolName === "MultiEdit");
475
+ const outcome = checkFilePath(
476
+ { path: filePath },
477
+ ctx,
478
+ toolName === "Edit" || toolName === "MultiEdit",
479
+ );
418
480
  return outcome ?? (await checkForkedCompanion(filePath, ctx)) ?? allow;
419
481
  }
420
482
 
@@ -423,12 +485,12 @@ async function decide({ toolName, toolInput }: ToolCall, ctx: GuardContext): Pro
423
485
  const attribution = checkCommitAttribution(command);
424
486
  if (attribution) return { exitCode: 2, stderr: `${attribution}\n`, check: "attribution" };
425
487
 
426
- const targets = commandMatches(command);
488
+ const targets = commandTargets(command);
427
489
  for (const target of targets) {
428
490
  const outcome = checkFilePath(target, ctx);
429
491
  if (outcome) return outcome;
430
492
  }
431
- for (const target of targets) {
493
+ for (const { path: target } of targets) {
432
494
  // oxlint-disable-next-line no-await-in-loop -- the first refusal wins
433
495
  const outcome = await checkForkedCompanion(target, ctx);
434
496
  if (outcome) return outcome;
@@ -0,0 +1,122 @@
1
+ /** @jsxRuntime automatic */
2
+ /** @jsxImportSource react */
3
+ import { Box, render as inkRender } from "ink";
4
+ import React, { useEffect } from "react";
5
+ import { SelectMenu, type SelectMenuItem } from "./select-menu";
6
+ import { WizardFooter } from "./wizard-footer";
7
+ import { WizardHeader } from "./wizard-header";
8
+
9
+ export interface SelectOneOptions {
10
+ stdin?: NodeJS.ReadStream;
11
+ stdout?: NodeJS.WriteStream;
12
+ stderr?: NodeJS.WriteStream;
13
+ }
14
+
15
+ interface SelectOneConfig<T> {
16
+ title: string;
17
+ toItem: (value: T) => SelectMenuItem;
18
+ }
19
+
20
+ /** Raw mode turns Ctrl+C into "\x03" instead of SIGINT, so it cancels like q and escape. */
21
+ function parseSelectOneInput(input: string): "submit" | "cancel" | "up" | "down" | null {
22
+ if (input === "\r" || input === "\n") return "submit";
23
+ if (input === "\x1b[A" || input === "[A") return "up";
24
+ if (input === "\x1b[B" || input === "[B") return "down";
25
+ if (input === "\x1b" || input === "\x03" || input.toLowerCase() === "q") return "cancel";
26
+ return null;
27
+ }
28
+
29
+ interface SelectOneAppProps {
30
+ title: string;
31
+ items: SelectMenuItem[];
32
+ activeIndex: number;
33
+ onMounted?: () => void;
34
+ }
35
+
36
+ function SelectOneApp({
37
+ title,
38
+ items,
39
+ activeIndex,
40
+ onMounted,
41
+ }: SelectOneAppProps): React.JSX.Element {
42
+ useEffect(() => {
43
+ onMounted?.();
44
+ }, [onMounted]);
45
+
46
+ return (
47
+ <Box flexDirection="column" width="100%">
48
+ <WizardHeader title={title} step={0} totalSteps={1} />
49
+ <Box marginTop={1} flexDirection="column">
50
+ <SelectMenu items={items} activeIndex={activeIndex} />
51
+ </Box>
52
+ <WizardFooter hint="↑↓ navigate · enter select · q cancel" />
53
+ </Box>
54
+ );
55
+ }
56
+
57
+ /** Terminal menu that picks one of `values`; null when cancelled. */
58
+ export async function selectOne<T>(
59
+ values: T[],
60
+ config: SelectOneConfig<T>,
61
+ options: SelectOneOptions = {},
62
+ ): Promise<T | null> {
63
+ const stdin = options.stdin ?? process.stdin;
64
+ const stdout = options.stdout ?? process.stdout;
65
+ const stderr = options.stderr ?? process.stderr;
66
+ if (!stdin.isTTY || !stdout.isTTY) {
67
+ throw new Error("Select menu requires a TTY.");
68
+ }
69
+
70
+ const items = values.map(config.toItem);
71
+ let activeIndex = 0;
72
+ let finalResult: T | null = null;
73
+ let rendered: ReturnType<typeof inkRender> | undefined;
74
+
75
+ stdin.resume();
76
+ (stdin as NodeJS.ReadStream & { ref?: () => void }).ref?.();
77
+ const keepAlive = setInterval(() => {}, 1 << 30);
78
+
79
+ const cleanup = () => {
80
+ clearInterval(keepAlive);
81
+ stdin.off("data", onData);
82
+ stdin.pause();
83
+ stdin.setRawMode?.(false);
84
+ (stdin as NodeJS.ReadStream & { unref?: () => void }).unref?.();
85
+ };
86
+
87
+ const app = () => (
88
+ <SelectOneApp
89
+ title={config.title}
90
+ items={items}
91
+ activeIndex={activeIndex}
92
+ onMounted={onMounted}
93
+ />
94
+ );
95
+
96
+ const onMounted = () => {
97
+ stdin.on("data", onData);
98
+ };
99
+
100
+ const onData = (chunk: string) => {
101
+ const action = parseSelectOneInput(chunk);
102
+ if (!action) return;
103
+ if (action === "up" || action === "down") {
104
+ activeIndex = (activeIndex + (action === "up" ? -1 : 1) + items.length) % items.length;
105
+ rendered?.rerender(app());
106
+ return;
107
+ }
108
+ // Ink resolves exit only after a stdout flush; later keys must not overwrite the choice.
109
+ stdin.off("data", onData);
110
+ finalResult = action === "submit" ? (values[activeIndex] ?? null) : null;
111
+ rendered?.unmount();
112
+ };
113
+
114
+ stdin.setEncoding("utf8");
115
+ stdin.setRawMode?.(true);
116
+
117
+ rendered = inkRender(app(), { stdin, stdout, stderr });
118
+ return rendered
119
+ .waitUntilExit()
120
+ .then(() => finalResult)
121
+ .finally(cleanup);
122
+ }
@@ -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,