@uniqbit/mate-core 1.0.1-canary.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 (38) 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.ts +3 -2
  8. package/src/cli/commands/vscode/release-vsix.json +2 -2
  9. package/src/cli/main.ts +12 -2
  10. package/src/hooks/validate-artifact-path.ts +79 -17
  11. package/src/lib/delivery/record-delivery.ts +14 -0
  12. package/src/lib/delivery/staging/apply-chain.ts +60 -30
  13. package/src/lib/delivery/staging/pending.ts +13 -0
  14. package/src/lib/delivery/staging/project.ts +21 -6
  15. package/src/lib/delivery/staging/publish.ts +10 -11
  16. package/src/lib/delivery/staging/submit.ts +2 -8
  17. package/src/lib/orchestrator/companion-git-sync.ts +53 -24
  18. package/src/lib/workset/worktree.ts +1 -0
  19. package/src/opencode/companion-hooks.ts +3 -1
  20. package/src/runtime/artifact-refusal.ts +17 -7
  21. package/src/runtime/companion-guidance.ts +2 -2
  22. package/src/runtime/companion-sync.ts +21 -1
  23. package/src/runtime/shell-heredoc.ts +67 -26
  24. package/src/runtime/shell-variables.ts +257 -0
  25. package/src/templates/capabilities/openspec-cap/mate-full/schema.yaml +3 -0
  26. package/src/templates/capabilities/openspec-cap/mate-minimal/schema.yaml +4 -0
  27. package/src/templates/capabilities/react-doctor/mate-react-doctor/SKILL.md +20 -2
  28. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +2 -2
  29. package/src/templates/mate-skills/agents/mate-publish-artifact/references/openspec.md +6 -6
  30. package/src/templates/mate-skills/agents/mate-submit-change/SKILL.md +4 -4
  31. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +2 -2
  32. package/src/templates/mate-skills/claude/mate-publish-artifact/references/openspec.md +6 -6
  33. package/src/templates/mate-skills/claude/mate-submit-change/SKILL.md +4 -4
  34. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +30 -30
  35. package/src/tools/setup/capabilities/openspec.ts +3 -1
  36. package/src/tools/setup/capabilities/tokensave.ts +8 -1
  37. package/src/tools/setup/mate.ts +2 -1
  38. package/src/tools/setup.ts +22 -1
@@ -46,7 +46,7 @@ import {
46
46
  import { isSettled } from "../refresh";
47
47
  import { recordDir, sourceDir, type ArtifactType } from "./artifact-type";
48
48
  import { deliveryGroupFor, type DeliveryGroupName } from "./naming";
49
- import { sourcePathOf, staleParts, STALE_SCAN_LIMIT } from "./pending";
49
+ import { resubmitAccepts, sourcePathOf, staleParts } from "./pending";
50
50
  import { commitToPending } from "./pending-edit";
51
51
  import {
52
52
  defaultRef,
@@ -424,13 +424,7 @@ export async function acceptsBlock(
424
424
  base: string,
425
425
  tip: string,
426
426
  ): Promise<boolean> {
427
- const stale = await staleParts(type, work, ref, folder, base, tip);
428
- // Nothing stale: the block has another cause, which a new base would not lift.
429
- return (
430
- stale.length > 0 &&
431
- stale.length < STALE_SCAN_LIMIT &&
432
- stale.every((part) => part.overwrites === false)
433
- );
427
+ return resubmitAccepts(await staleParts(type, work, ref, folder, base, tip));
434
428
  }
435
429
 
436
430
  /** {@link acceptsBlock} for the folder as staged in the pending checkout `work`. */
@@ -7,6 +7,8 @@ import {
7
7
  companionGit,
8
8
  describeGitFailure,
9
9
  isAuthenticationFailure,
10
+ LITERAL_PATHSPECS,
11
+ nulPaths,
10
12
  outputLines,
11
13
  type GitResult,
12
14
  type UpstreamTarget,
@@ -25,6 +27,7 @@ import {
25
27
  import { FRAMEWORK_NAME } from "../../framework";
26
28
  import { artifactTypes, defaultArtifactType } from "../delivery/staging/registry";
27
29
  import { loadWorkflow } from "../workflow/declaration";
30
+ import { mateManagedSkillNames } from "../../tools/setup";
28
31
  import { LaunchPreflightError } from "./types";
29
32
 
30
33
  type GitCommandResult = GitResult;
@@ -121,11 +124,24 @@ const MANAGED_ROOTS = [".mate", ".opencode", ".claude", ".agents", ".graphify"];
121
124
 
122
125
  type SyncTarget = UpstreamTarget;
123
126
 
124
- function isManagedPath(filePath: string): boolean {
125
- const normalized = filePath.replaceAll("\\", "/").replace(/^\.\//, "");
127
+ const SKILL_ROOTS = new Set([".claude/skills", ".agents/skills", ".opencode/skills"]);
128
+
129
+ function normalizedPath(filePath: string): string {
130
+ return filePath.replaceAll("\\", "/").replace(/^\.\//, "");
131
+ }
132
+
133
+ function isManagedPath(normalized: string): boolean {
126
134
  return MANAGED_ROOTS.some((root) => normalized === root || normalized.startsWith(`${root}/`));
127
135
  }
128
136
 
137
+ function isForcedPath(filePath: string, mateSkillNames: ReadonlySet<string>): boolean {
138
+ const normalized = normalizedPath(filePath);
139
+ if (!isManagedPath(normalized)) return false;
140
+ const [root, folder, entry] = normalized.split("/");
141
+ if (entry === undefined || !SKILL_ROOTS.has(`${root}/${folder}`)) return true;
142
+ return mateSkillNames.has(entry);
143
+ }
144
+
129
145
  export class CompanionGitSync {
130
146
  constructor(private readonly options: CompanionGitSyncOptions = {}) {}
131
147
 
@@ -308,8 +324,10 @@ export class CompanionGitSync {
308
324
  "--no-progress",
309
325
  "--no-edit",
310
326
  ]);
327
+ if (merge.status === 0 && !stashRef) return;
328
+ const skillNames = await mateManagedSkillNames(companionPath);
311
329
  if (merge.status !== 0) {
312
- await this.resolveManagedConflicts(companionPath, target.ref);
330
+ await this.resolveManagedConflicts(companionPath, target.ref, skillNames);
313
331
  const conflicts = await this.unresolvedPaths(companionPath);
314
332
  if (conflicts.length > 0) {
315
333
  throw this.failure(
@@ -334,7 +352,7 @@ export class CompanionGitSync {
334
352
  const apply = await this.command(companionPath, ["stash", "apply", "--index", stashRef]);
335
353
  if (apply.status !== 0) {
336
354
  const applyConflicts = await this.unresolvedPaths(companionPath);
337
- await this.resolveManagedConflicts(companionPath, target.ref);
355
+ await this.resolveManagedConflicts(companionPath, target.ref, skillNames);
338
356
  const conflicts = await this.unresolvedPaths(companionPath);
339
357
  if (conflicts.length > 0) {
340
358
  throw this.failure(
@@ -354,7 +372,7 @@ export class CompanionGitSync {
354
372
  }
355
373
  }
356
374
 
357
- await this.discardManagedChanges(companionPath);
375
+ await this.discardManagedChanges(companionPath, skillNames);
358
376
  const remaining = await this.unresolvedPaths(companionPath);
359
377
  if (remaining.length > 0) {
360
378
  throw this.failure(
@@ -467,10 +485,15 @@ export class CompanionGitSync {
467
485
  return result.status === 0 ? outputLines(result.stdout) : [];
468
486
  }
469
487
 
470
- private async resolveManagedConflicts(companionPath: string, targetRef: string): Promise<void> {
488
+ private async resolveManagedConflicts(
489
+ companionPath: string,
490
+ targetRef: string,
491
+ skillNames: ReadonlySet<string>,
492
+ ): Promise<void> {
471
493
  const conflicts = await this.unresolvedPaths(companionPath);
472
- for (const conflict of conflicts.filter(isManagedPath)) {
494
+ for (const conflict of conflicts.filter((entry) => isForcedPath(entry, skillNames))) {
473
495
  const restore = await this.command(companionPath, [
496
+ ...LITERAL_PATHSPECS,
474
497
  "restore",
475
498
  `--source=${targetRef}`,
476
499
  "--staged",
@@ -485,26 +508,41 @@ export class CompanionGitSync {
485
508
  [conflict],
486
509
  );
487
510
  }
488
- await this.command(companionPath, ["add", "-A", "--", conflict]);
511
+ await this.command(companionPath, [...LITERAL_PATHSPECS, "add", "-A", "--", conflict]);
489
512
  }
490
513
  }
491
514
 
492
- private async discardManagedChanges(companionPath: string): Promise<void> {
493
- const tracked = await this.command(companionPath, [
494
- "ls-files",
495
- "--cached",
515
+ private async discardManagedChanges(
516
+ companionPath: string,
517
+ skillNames: ReadonlySet<string>,
518
+ ): Promise<void> {
519
+ const committed = await this.command(companionPath, [
520
+ "ls-tree",
521
+ "-r",
522
+ "--name-only",
523
+ "-z",
524
+ "HEAD",
496
525
  "--",
497
526
  ...MANAGED_ROOTS,
498
527
  ]);
499
- const trackedPaths = outputLines(tracked.stdout);
500
- if (trackedPaths.length > 0) {
528
+ if (committed.status !== 0) {
529
+ throw this.failure(
530
+ companionPath,
531
+ `Unable to list managed paths in HEAD: ${this.detail(committed)}`,
532
+ );
533
+ }
534
+ const committedPaths = nulPaths(committed.stdout).filter((entry) =>
535
+ isForcedPath(entry, skillNames),
536
+ );
537
+ if (committedPaths.length > 0) {
501
538
  const restore = await this.command(companionPath, [
539
+ ...LITERAL_PATHSPECS,
502
540
  "restore",
503
541
  "--source=HEAD",
504
542
  "--staged",
505
543
  "--worktree",
506
544
  "--",
507
- ...trackedPaths,
545
+ ...committedPaths,
508
546
  ]);
509
547
  if (restore.status !== 0) {
510
548
  throw this.failure(
@@ -513,15 +551,6 @@ export class CompanionGitSync {
513
551
  );
514
552
  }
515
553
  }
516
-
517
- // -x is intentionally omitted: ignored files are local state and must survive.
518
- const clean = await this.command(companionPath, ["clean", "-fd", "--", ...MANAGED_ROOTS]);
519
- if (clean.status !== 0) {
520
- throw this.failure(
521
- companionPath,
522
- `Unable to remove unmanaged managed-path files: ${this.detail(clean)}`,
523
- );
524
- }
525
554
  }
526
555
 
527
556
  private command(companionPath: string, args: readonly string[]): Promise<GitCommandResult> {
@@ -439,6 +439,7 @@ async function recordTarget(companionPath: string, worksetId: string): Promise<T
439
439
  if (record) return record;
440
440
  return [
441
441
  `no valid Workset ${worksetId}`,
442
+ `a Workset submitted to the inbox but not in this checkout needs \`${FRAMEWORK_NAME} artifact take "<change>"\` first, or pass --change <change>`,
442
443
  ...problems.map((problem) => `${problem.path}: ${problem.reason}`),
443
444
  ];
444
445
  }
@@ -97,7 +97,9 @@ export async function refuseForkedCompanionWrite(
97
97
  ): Promise<void> {
98
98
  if (!filePath || !isArtifactPath(filePath)) return;
99
99
  if (!isCompanionTarget(context, filePath)) return;
100
- const refusal = await companionForkRefusal(env, context.companionPath);
100
+ const refusal = await companionForkRefusal(env, context.companionPath, {
101
+ target: resolveArtifactTarget(filePath, context.repositoryPath),
102
+ });
101
103
  if (refusal) throw new GuardRefusal("fork", refusal);
102
104
  }
103
105
 
@@ -14,6 +14,8 @@ export interface ArtifactRefusalInput {
14
14
  companion: string;
15
15
  /** The Working Repository root relative targets resolve against. */
16
16
  repoRoot: string;
17
+ /** A shell expansion in the target, as written, that the command text does not settle. */
18
+ unresolved?: string;
17
19
  }
18
20
 
19
21
  /** The absolute path both guards judge: a relative target resolves against the repo root, never a `cd`. */
@@ -34,9 +36,10 @@ export function artifactRefusal({
34
36
  resolved,
35
37
  companion,
36
38
  repoRoot,
39
+ unresolved,
37
40
  }: ArtifactRefusalInput): string {
38
- const isRelative = !path.isAbsolute(target);
39
- const inside = relativeInside(resolved, repoRoot);
41
+ const isRelative = !unresolved && !path.isAbsolute(target);
42
+ const inside = unresolved ? null : relativeInside(resolved, repoRoot);
40
43
  const suggested = inside ? path.join(companion, inside) : null;
41
44
 
42
45
  const lines = [
@@ -51,11 +54,18 @@ export function artifactRefusal({
51
54
  "Relative paths resolve against the working repository; a preceding `cd` is not followed.",
52
55
  );
53
56
  }
54
- lines.push(
55
- suggested
56
- ? "Rewrite to the suggested absolute path and retry."
57
- : `Use an absolute path under ${companion}.`,
58
- );
57
+ if (unresolved) {
58
+ lines.push(
59
+ `The guardrail cannot expand ${unresolved}: it follows only a variable assigned a literal value earlier in the same straight-line command, quoted where the value holds a space or glob character.`,
60
+ `Use a literal absolute path under ${companion}.`,
61
+ );
62
+ } else {
63
+ lines.push(
64
+ suggested
65
+ ? "Rewrite to the suggested absolute path and retry."
66
+ : `Use an absolute path under ${companion}.`,
67
+ );
68
+ }
59
69
  if (path.basename(target) === "CLAUDE.md") {
60
70
  lines.push(`Note: CLAUDE.md already lives in the companion repo at ${companion}/CLAUDE.md.`);
61
71
  }
@@ -115,7 +115,7 @@ const SECRET_HANDLING_RULE = ` <rule id="secret-handling" severity="critical"
115
115
 
116
116
  export const FRICTION_GUIDANCE = `## Friction
117
117
 
118
- When ${FRAMEWORK_NAME} gets in your way without a refusal or error to point at, such as a skill step that does not fit or missing guidance, record it when it happens: \`${FRAMEWORK_NAME} friction report --kind <${REPORT_KINDS.join("|")}> --subject <${SUBJECT_TYPES.join("|")}>:<name> --expected "<what you expected>" --evidence "<what you saw>"\`. Record one report per problem, then keep working on your task. When nothing went wrong, record nothing.`;
118
+ When ${FRAMEWORK_NAME} gets in your way without a refusal or error to point at, such as a skill step that does not fit or missing guidance, record it: \`${FRAMEWORK_NAME} friction report --kind <${REPORT_KINDS.join("|")}> --subject <${SUBJECT_TYPES.join("|")}>:<name> --expected "<what you expected>" --evidence "<what you saw>"\`. Run it on its own, without \`cd\` or chaining; it only writes a local file. Record one report per problem, then keep working. When nothing went wrong, record nothing.`;
119
119
 
120
120
  function withFriction(policy: string, friction: boolean | undefined): string {
121
121
  return friction ? `${policy}\n\n${FRICTION_GUIDANCE}` : policy;
@@ -273,7 +273,7 @@ export function buildCompanionPolicyXml(
273
273
  if (hasOpenspecCapability(context.capabilities)) {
274
274
  lines.push(
275
275
  ` <rule id="openspec-scope" severity="critical">In OpenSpec, the frontmatter repository identifies the Working Repository; areas are repository-relative paths within that repository. Canonical specs use repository plus flat areas; change artifacts use paired scopes entries. In a monorepo, an Area normally stops at the package root. A cross-repository change may declare multiple scopes, but each resulting spec remains owned by one repository, and each requirement must bind its Area explicitly.</rule>`,
276
- ` <rule id="openspec-publish" severity="critical">Submit publishes nothing: it pushes an OpenSpec change folder (state: submitted) to the inbox mate/inbox to await its merge. A submitted change is not the truth: only publication lands it on the companion's default branch. openspec/specs/ is current; ${FRAMEWORK_NAME} artifact project "<name>" shows the unpublished outcome. ${FRAMEWORK_NAME} artifact pending --json --no-merge-check lists them with author, touched requirements, ref and path; read one (git show <ref>:<path>/<file>) only where it touches your work or the user names it; implement or revise one only when the user names it: ${FRAMEWORK_NAME} artifact take "<name>" brings it into the checkout when it is missing there, then resubmit it with mate-submit-change. Publish only through mate-publish-artifact (${FRAMEWORK_NAME} artifact publish "<name>" --json), after the user selects and confirms the commit and push, for a Delivery Group whose delivery branch is merged. It creates no tag. Never hand-commit or hand-tag one. Publish archives submitted changes and never submits: submitting is a precondition (mate-submit-change, before the merge).</rule>`,
276
+ ` <rule id="openspec-publish" severity="critical">Submit publishes nothing: it pushes an OpenSpec change folder (state: submitted) to the inbox mate/inbox to await its merge. A submitted change is not the truth: only publication lands it on the companion's default branch. An active change folder under openspec/changes/ stays uncommitted until publication; never commit one by hand. openspec/specs/ is current; ${FRAMEWORK_NAME} artifact project "<name>" shows the unpublished outcome. ${FRAMEWORK_NAME} artifact pending --json --no-merge-check lists them with author, touched requirements, ref and path; read one (git show <ref>:<path>/<file>) only where it touches your work or the user names it; implement or revise one only when the user names it: ${FRAMEWORK_NAME} artifact take "<name>" brings it into the checkout when it is missing there, then resubmit it with mate-submit-change. Publish only through mate-publish-artifact (${FRAMEWORK_NAME} artifact publish "<name>" --json), after the user selects and confirms the commit and push, for a Delivery Group whose delivery branch is merged. It creates no tag. Never hand-commit or hand-tag one. Publish archives submitted changes and never submits: submitting is a precondition (mate-submit-change, before the merge).</rule>`,
277
277
  );
278
278
  }
279
279
 
@@ -369,6 +369,11 @@ export interface ForkGuardOptions {
369
369
  homeDir?: string;
370
370
  }
371
371
 
372
+ export interface ForkRefusalOptions extends ForkGuardOptions {
373
+ /** Absolute path being written; an ignored one is never refused. */
374
+ target?: string;
375
+ }
376
+
372
377
  /**
373
378
  * The verdict both runtimes' artifact guards share, cached per interval so a
374
379
  * retry loop cannot spawn Git per write. `null` means "no refusal" — including
@@ -378,7 +383,7 @@ export interface ForkGuardOptions {
378
383
  export async function companionForkRefusal(
379
384
  env: Record<string, string | undefined>,
380
385
  companionPath: string,
381
- options: ForkGuardOptions = {},
386
+ options: ForkRefusalOptions = {},
382
387
  ): Promise<string | null> {
383
388
  if (!companionPath) return null;
384
389
  /**
@@ -392,9 +397,24 @@ export async function companionForkRefusal(
392
397
 
393
398
  const fork = await cachedCompanionForkState(companionPath, options);
394
399
  if (!fork?.forked) return null;
400
+ if (options.target && (await isIgnoredByCompanion(companionPath, options.target, options))) {
401
+ return null;
402
+ }
395
403
  return forkRefusalMessage(companionPath, fork);
396
404
  }
397
405
 
406
+ // Sync skips ignored files but reconciles tracked ones; `icase`: a case-insensitive disk lands `kept.md` on a tracked `Kept.md`.
407
+ async function isIgnoredByCompanion(
408
+ companionPath: string,
409
+ target: string,
410
+ { timeoutMs = GIT_QUERY_TIMEOUT_MS }: ForkGuardOptions,
411
+ ): Promise<boolean> {
412
+ const git = companionGit(companionPath, { prompt: "never", commandCapMs: timeoutMs });
413
+ if ((await git.run(["check-ignore", "-q", "--", target])).status !== 0) return false;
414
+ const tracked = await git.run(["ls-files", "-z", "--", `:(icase,literal)${target}`]);
415
+ return tracked.status === 0 && tracked.stdout === "";
416
+ }
417
+
398
418
  export async function cachedCompanionForkState(
399
419
  companionPath: string,
400
420
  options: ForkGuardOptions = {},
@@ -1,36 +1,77 @@
1
+ export const HEREDOC_MARKER = /^<<-?\s*(['"]?)([\w.-]+)\1/;
2
+
1
3
  /**
2
- * Where a heredoc starts, matched at a `<<` outside quotes: an optional `-`,
3
- * then the terminator word, optionally quoted. Shared by the secret guard's
4
- * shell tokenizer and the artifact guard's redirect scan, so both agree on
5
- * what is command text and what is a body.
4
+ * Per offset, whether the shell runs it as command text: outside quotes,
5
+ * comments and `$((…))`, or in a `$(…)` or backtick substitution, also one
6
+ * inside double quotes.
6
7
  */
7
- export const HEREDOC_MARKER = /^<<-?\s*(['"]?)([\w.-]+)\1/;
8
+ export function commandTextMask(text: string): boolean[] {
9
+ const mask = Array.from({ length: text.length }, () => false);
10
+ const spans: string[] = [];
11
+ for (let i = 0; i < text.length; i++) {
12
+ const span = spans.at(-1);
13
+ const char = text[i];
14
+ mask[i] = span !== "'" && span !== "$'" && span !== '"' && span !== "((";
15
+ if (span === "'") {
16
+ if (char === "'") spans.pop();
17
+ } else if (span === "$'") {
18
+ if (char === "\\") i++;
19
+ else if (char === "'") spans.pop();
20
+ } else if (char === "\\") {
21
+ i++;
22
+ } else if (
23
+ char === "#" &&
24
+ (span === undefined || span === "(" || span === "`") &&
25
+ (i === 0 || /[\s;&|()`]/.test(text[i - 1]!))
26
+ ) {
27
+ mask[i] = false;
28
+ const end = text.indexOf("\n", i);
29
+ i = end === -1 ? text.length : end - 1;
30
+ } else if (char === "`") {
31
+ if (span === "`") spans.pop();
32
+ else spans.push("`");
33
+ } else if (char === "$" && text[i + 1] === "'" && span !== '"') {
34
+ spans.push("$'");
35
+ i++;
36
+ } else if (char === "$" && text[i + 1] === "(" && text[i + 2] === "(") {
37
+ spans.push("((");
38
+ i += 2;
39
+ } else if (char === "$" && text[i + 1] === "(") {
40
+ spans.push("(");
41
+ i++;
42
+ } else if (span === '"') {
43
+ if (char === '"') spans.pop();
44
+ } else if (span === "((") {
45
+ if (char === "(") spans.push("((");
46
+ else if (char === ")") {
47
+ spans.pop();
48
+ if (spans.at(-1) !== "((" && text[i + 1] === ")") i++;
49
+ }
50
+ } else if (char === "'" || char === '"') {
51
+ spans.push(char);
52
+ } else if (span === "(") {
53
+ if (char === "(") spans.push("(");
54
+ else if (char === ")") spans.pop();
55
+ }
56
+ }
57
+ return mask;
58
+ }
8
59
 
9
- /** The terminators a command line opens, in order; quoted text is skipped. */
10
60
  function heredocTerminators(line: string): string[] {
11
61
  const terminators: string[] = [];
12
- let quote: string | undefined;
62
+ const isCommand = commandTextMask(line);
13
63
  for (let i = 0; i < line.length; i++) {
14
- const char = line[i];
15
- if (quote) {
16
- if (char === quote) quote = undefined;
17
- else if (char === "\\" && quote === '"') i++;
18
- } else if (char === "'" || char === '"') {
19
- quote = char;
20
- } else if (char === "\\") {
64
+ if (!isCommand[i] || line[i] !== "<" || line[i + 1] !== "<") continue;
65
+ if (line[i + 2] === "<") {
66
+ i += 2;
67
+ continue;
68
+ }
69
+ const marker = HEREDOC_MARKER.exec(line.slice(i));
70
+ if (marker) {
71
+ terminators.push(marker[2]);
72
+ i += marker[0].length - 1;
73
+ } else {
21
74
  i++;
22
- } else if (char === "<" && line[i + 1] === "<") {
23
- if (line[i + 2] === "<") {
24
- i += 2;
25
- continue;
26
- }
27
- const marker = HEREDOC_MARKER.exec(line.slice(i));
28
- if (marker) {
29
- terminators.push(marker[2]);
30
- i += marker[0].length - 1;
31
- } else {
32
- i++;
33
- }
34
75
  }
35
76
  }
36
77
  return terminators;
@@ -0,0 +1,257 @@
1
+ const NAME = /^[A-Za-z_]\w*$/;
2
+ const ASSIGNMENT = /^([A-Za-z_]\w*)(\+?)=([\s\S]*)$/;
3
+ const REFERENCE = /^\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))/;
4
+ const DYNAMIC = /^(?:\$\([^)]*\)?|\$\{[^}]*\}?|\$\w*|`[^`]*`?)/;
5
+ const SPLITS_OR_GLOBS = /[\s*?[]/;
6
+ const REWRITES_VALUE = /[~{}*?[]/;
7
+
8
+ const NON_ASSIGNING_COMMANDS = new Set([
9
+ ":",
10
+ "[",
11
+ "cat",
12
+ "chmod",
13
+ "cp",
14
+ "date",
15
+ "echo",
16
+ "false",
17
+ "git",
18
+ "grep",
19
+ "head",
20
+ "ln",
21
+ "ls",
22
+ "mkdir",
23
+ "mv",
24
+ "printf",
25
+ "rm",
26
+ "sed",
27
+ "sleep",
28
+ "sort",
29
+ "tail",
30
+ "tee",
31
+ "test",
32
+ "touch",
33
+ "true",
34
+ "wc",
35
+ ]);
36
+
37
+ export type Expansion =
38
+ | { text: string; unresolved?: undefined }
39
+ | { text?: undefined; unresolved: string };
40
+ type Lookup = (name: string) => string | null | undefined;
41
+
42
+ function expandWord(raw: string, lookup: Lookup, assignment = false): Expansion {
43
+ let text = "";
44
+ let quote: string | undefined;
45
+ for (let i = 0; i < raw.length; i++) {
46
+ const char = raw[i];
47
+ if (quote === "'") {
48
+ if (char === "'") quote = undefined;
49
+ else text += char;
50
+ } else if (char === "\\" && i + 1 < raw.length && (!quote || '$`"\\\n'.includes(raw[i + 1]))) {
51
+ text += raw[++i];
52
+ } else if (char === '"') {
53
+ quote = quote ? undefined : '"';
54
+ } else if (char === "'" && !quote) {
55
+ quote = "'";
56
+ } else if (char === "$" || char === "`") {
57
+ const rest = raw.slice(i);
58
+ const reference = REFERENCE.exec(rest);
59
+ const value = reference ? lookup(reference[1] ?? reference[2]) : undefined;
60
+ const splits = !quote && !assignment;
61
+ // zsh applies `:h`-style modifiers and `[…]` subscripts to an unbraced name.
62
+ const modified =
63
+ reference?.[2] !== undefined && /^[:[]/.test(rest.slice(reference[0].length));
64
+ if (
65
+ !reference ||
66
+ typeof value !== "string" ||
67
+ modified ||
68
+ (splits && SPLITS_OR_GLOBS.test(value))
69
+ ) {
70
+ return { unresolved: (reference ?? DYNAMIC.exec(rest))?.[0] ?? char };
71
+ }
72
+ text += value;
73
+ i += reference[0].length - 1;
74
+ } else if (assignment && !quote && (REWRITES_VALUE.test(char) || (i === 0 && char === "="))) {
75
+ return { unresolved: char };
76
+ } else {
77
+ text += char;
78
+ }
79
+ }
80
+ return { text };
81
+ }
82
+
83
+ type Binding = { at: number; name: string; value: string | null };
84
+ type ScanEvent = { at: number; name?: undefined } | Binding;
85
+
86
+ interface Word {
87
+ raw: string;
88
+ at: number;
89
+ }
90
+
91
+ interface Assignment extends Word {
92
+ name: string;
93
+ append: boolean;
94
+ value: string;
95
+ }
96
+
97
+ function parseAssignment(word: Word): Assignment | null {
98
+ const match = ASSIGNMENT.exec(word.raw);
99
+ return match ? { ...word, name: match[1], append: match[2] === "+", value: match[3] } : null;
100
+ }
101
+
102
+ function lookupIn(events: ScanEvent[]): Lookup {
103
+ return (name) =>
104
+ events.some((event) => event.name === undefined)
105
+ ? undefined
106
+ : events.findLast((event): event is Binding => event.name === name)?.value;
107
+ }
108
+
109
+ function scan(text: string): ScanEvent[] {
110
+ const events: ScanEvent[] = [];
111
+ const poison = (at: number) => events.push({ at });
112
+ const lookup = lookupIn(events);
113
+
114
+ const bind = (assigned: Assignment[], at: number, exported: boolean) => {
115
+ const own = new Set(assigned.map((assignment) => assignment.name));
116
+ for (const { name, append, value: raw } of assigned) {
117
+ // `export A=1 B=$A` expands `$A` before either is assigned.
118
+ const outer = (ref: string) => (exported && own.has(ref) ? undefined : lookup(ref));
119
+ const value = append ? undefined : expandWord(raw, outer, true).text;
120
+ events.push({ at, name, value: value ?? null });
121
+ }
122
+ };
123
+
124
+ const classify = (words: Word[], at: number, listed: boolean) => {
125
+ const parsed = words.map(parseAssignment);
126
+ const leading = parsed.indexOf(null);
127
+ const split = leading === -1 ? words.length : leading;
128
+ const rest = words.slice(split);
129
+ const exported =
130
+ split === 0 &&
131
+ rest[0]?.raw === "export" &&
132
+ rest.slice(1).every((word, k) => parsed[k + 1] !== null || NAME.test(word.raw));
133
+ const assigned = (exported ? parsed.slice(1) : parsed.slice(0, split)).filter(
134
+ (assignment): assignment is Assignment => assignment !== null,
135
+ );
136
+ for (const assignment of assigned) {
137
+ if (assignment.name === "IFS") poison(assignment.at);
138
+ }
139
+ const assignsOnly = exported || rest.length === 0;
140
+ if (assignsOnly && !listed) {
141
+ bind(assigned, at, exported);
142
+ return;
143
+ }
144
+ for (const { at: wordAt, name } of assigned) {
145
+ events.push({ at: wordAt, name, value: null });
146
+ }
147
+ if (assignsOnly) return;
148
+ const command = rest[0];
149
+ const printsToVariable =
150
+ command.raw === "printf" && rest.some((word) => word.raw.includes("-v"));
151
+ if (!NON_ASSIGNING_COMMANDS.has(command.raw) || printsToVariable) poison(command.at);
152
+ };
153
+
154
+ let words: Word[] = [];
155
+ let word = "";
156
+ let wordAt = 0;
157
+ let quote: string | undefined;
158
+ let listed = false;
159
+ let statementStart = -1;
160
+ // Words expand before redirects, so a later expansion in the statement still reaches its target.
161
+ const poisonStatement = () => events.push({ at: statementStart });
162
+ const add = (at: number, chars: string) => {
163
+ if (!word) wordAt = at;
164
+ word += chars;
165
+ };
166
+ const endWord = () => {
167
+ if (word) words.push({ raw: word, at: wordAt });
168
+ word = "";
169
+ };
170
+ const endCommand = (at: number, joinsNext: boolean) => {
171
+ endWord();
172
+ statementStart = at;
173
+ // `a &&` before a newline still joins the next statement to the list.
174
+ if (words.length === 0) {
175
+ listed ||= joinsNext;
176
+ return;
177
+ }
178
+ classify(words, at, listed || joinsNext);
179
+ words = [];
180
+ listed = joinsNext;
181
+ };
182
+ const dollar = (i: number): number => {
183
+ const next = text[i + 1];
184
+ if (next === "(" || next === "'" || next === '"') poisonStatement();
185
+ if (next !== "{") {
186
+ add(i, "$");
187
+ return i;
188
+ }
189
+ const close = text.indexOf("}", i);
190
+ const end = close === -1 ? text.length - 1 : close;
191
+ if (!NAME.test(text.slice(i + 2, end))) poisonStatement();
192
+ add(i, text.slice(i, end + 1));
193
+ return end;
194
+ };
195
+
196
+ for (let i = 0; i < text.length; i++) {
197
+ const char = text[i];
198
+ const next = text[i + 1];
199
+ if (quote === "'") {
200
+ add(i, char);
201
+ if (char === "'") quote = undefined;
202
+ } else if (quote === '"') {
203
+ if (char === "\\" && next !== undefined) add(i, char + text[++i]);
204
+ else if (char === "$") i = dollar(i);
205
+ else {
206
+ if (char === "`") poisonStatement();
207
+ if (char === '"') quote = undefined;
208
+ add(i, char);
209
+ }
210
+ } else if (char === "\\" && next === "\n") {
211
+ i++;
212
+ } else if (char === "\\" && next !== undefined) {
213
+ add(i, char + text[++i]);
214
+ } else if (char === "'" || char === '"') {
215
+ quote = char;
216
+ add(i, char);
217
+ } else if (char === "$") {
218
+ i = dollar(i);
219
+ } else if (char === "#" && !word) {
220
+ const lineEnd = text.indexOf("\n", i);
221
+ i = (lineEnd === -1 ? text.length : lineEnd) - 1;
222
+ } else if (char === " " || char === "\t") {
223
+ endWord();
224
+ } else if (char === ";" || char === "\n") {
225
+ if (char === ";" && next === ";") poison(i);
226
+ endCommand(i, false);
227
+ } else if (char === "&" && next === "&") {
228
+ endCommand(i++, true);
229
+ } else if (char === "|" && text[i - 1] !== ">") {
230
+ endCommand(i, true);
231
+ if (next === "|" || next === "&") i++;
232
+ } else if (char === "&" && text[i - 1] !== ">" && text[i - 1] !== "<" && next !== ">") {
233
+ poison(i);
234
+ endCommand(i, false);
235
+ } else if (char === "<" && next === "<") {
236
+ const herestring = text[i + 2] === "<";
237
+ if (!herestring && !/^<<-?[ \t]*['"\\]/.test(text.slice(i))) poison(i);
238
+ add(i, herestring ? "<<<" : "<<");
239
+ i += herestring ? 2 : 1;
240
+ } else {
241
+ if (char === "`") poisonStatement();
242
+ else if ("(){}".includes(char)) poison(i);
243
+ add(i, char);
244
+ }
245
+ }
246
+ endCommand(text.length, false);
247
+ // Heredoc bodies are stripped by a heuristic: after the first `<<` line the text is no proof.
248
+ const heredoc = text.indexOf("<<");
249
+ const heredocLineEnd = heredoc === -1 ? -1 : text.indexOf("\n", heredoc);
250
+ if (heredocLineEnd !== -1) poison(heredocLineEnd);
251
+ return events;
252
+ }
253
+
254
+ export function wordExpander(commandText: string): (raw: string, offset: number) => Expansion {
255
+ const events = scan(commandText);
256
+ return (raw, offset) => expandWord(raw, lookupIn(events.filter((event) => event.at < offset)));
257
+ }