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

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mate-companion-mentions",
3
- "version": "1.0.1-canary.2",
3
+ "version": "1.0.2-canary.0",
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.2",
3
+ "version": "1.0.2-canary.0",
4
4
  "description": "Core framework and plugin APIs for Mate.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -24,6 +24,7 @@ import {
24
24
  commandOutput,
25
25
  renderDelivery,
26
26
  renderOutcome,
27
+ refusalWithHints,
27
28
  sharedRefusalMessage,
28
29
  unscopedDeliveryWarning,
29
30
  } from "./output";
@@ -182,7 +183,12 @@ export async function runArtifactLinkCommand(
182
183
  },
183
184
  deps,
184
185
  );
185
- if ("refusal" in outcome) return refuse(refusalMessage(outcome.refusal));
186
+ if ("refusal" in outcome) {
187
+ const { refusal } = outcome;
188
+ return refuse(
189
+ await refusalWithHints(refusalMessage(refusal), refusal, environment.companionPath),
190
+ );
191
+ }
186
192
  const sessionEnv = deps.sessionEnv ?? process.env;
187
193
  // One change names the session's work; a batch link names none.
188
194
  if (changes.length === 1) {
@@ -2,6 +2,7 @@ import { TICKETS_OFF } from "../../../../lib/delivery/branches";
2
2
  import type { Delivery, UnscopedDelivery } from "../../../../lib/delivery/record";
3
3
  import type { BranchOutcome } from "../../../../lib/delivery/refresh";
4
4
  import type { DeliveryRefusal } from "../../../../lib/delivery/record-delivery";
5
+ import { withLinkedCompanionHints } from "../../shared/companion-selection";
5
6
 
6
7
  export interface CommandOutput {
7
8
  emitOut: (line: string) => void;
@@ -80,6 +81,15 @@ export function renderOutcome(outcome: BranchOutcome): string[] {
80
81
  return lines;
81
82
  }
82
83
 
84
+ export async function refusalWithHints(
85
+ message: string,
86
+ refusal: DeliveryRefusal,
87
+ inUse: string,
88
+ ): Promise<string> {
89
+ if (refusal.reason !== "unknown-change" && refusal.reason !== "missing-folder") return message;
90
+ return withLinkedCompanionHints(message, refusal.change, inUse);
91
+ }
92
+
83
93
  /** Wording for the refusals `link` and `archive` share; `unknown-change` names each command. */
84
94
  export function sharedRefusalMessage(
85
95
  refusal: Exclude<DeliveryRefusal, { reason: "unknown-change" }>,
@@ -20,6 +20,7 @@ import {
20
20
  commandOutput,
21
21
  renderDelivery,
22
22
  renderOutcome,
23
+ refusalWithHints,
23
24
  sharedRefusalMessage,
24
25
  unscopedDeliveryWarning,
25
26
  } from "./output";
@@ -156,7 +157,12 @@ export async function runArtifactSubmitCommand(
156
157
  },
157
158
  },
158
159
  );
159
- if ("refusal" in outcome) return refuse(refusalMessage(outcome.refusal));
160
+ if ("refusal" in outcome) {
161
+ const { refusal } = outcome;
162
+ return refuse(
163
+ await refusalWithHints(refusalMessage(refusal), refusal, environment.companionPath),
164
+ );
165
+ }
160
166
 
161
167
  const { results } = outcome;
162
168
  for (const result of results) {
@@ -6,8 +6,11 @@ import {
6
6
  type CompanionMatch,
7
7
  findRepoLocalLinkedRepository,
8
8
  } from "../../../lib/orchestrator/repository-link";
9
+ import { shellQuote } from "../../../lib/delivery/staging/apply-chain";
10
+ import { repositoryFromEnvironment } from "../../../lib/orchestrator/framework-context";
9
11
  import { GlobalConfigStore } from "../../../lib/orchestrator/global-config-store";
10
12
  import { projectWorkingRepositoryBestEffort } from "../../../lib/orchestrator/working-repo-projection";
13
+ import { findChangeInLinkedCompanions } from "../../../lib/workflow/work";
11
14
  import { resolveProjection } from "../../../runtime/projection";
12
15
  import { selectCompanion } from "../../companion-selector";
13
16
 
@@ -20,10 +23,13 @@ export const launchAmbiguityDeps = {
20
23
  * the Linked Companions are that list when populated and the single match
21
24
  * otherwise.
22
25
  */
23
- resolveLinkedCompanions: async (cwd: string): Promise<CompanionMatch[]> => {
26
+ resolveLinkedCompanions: async (
27
+ cwd: string,
28
+ options?: { write?: boolean },
29
+ ): Promise<CompanionMatch[]> => {
24
30
  const { match, ambiguousMatches } = await new CompanionResolver(
25
31
  new GlobalConfigStore(),
26
- ).resolveWithDiagnostics(cwd);
32
+ ).resolveWithDiagnostics(cwd, options);
27
33
  if (ambiguousMatches.length > 0) return ambiguousMatches;
28
34
  return match ? [match] : [];
29
35
  },
@@ -40,6 +46,8 @@ export interface CompanionSelectionOptions {
40
46
  ignoreProjection?: boolean;
41
47
  /** Outranks the environment, the projection, and the picker. */
42
48
  companion?: string;
49
+ /** Check `companion` against the session's Working Repository (`MATE_REPO_PATH`) when one is set, as later resolution uses it. */
50
+ sessionRepository?: boolean;
43
51
  /** Pin an interactive answer for this process without writing a projection. */
44
52
  persistSelection?: boolean;
45
53
  /** Never open the picker; an unresolved ambiguity returns false as it does without a TTY. */
@@ -58,13 +66,75 @@ function reportLinkedCompanions(message: string, matches: CompanionMatch[]): voi
58
66
  }
59
67
  }
60
68
 
69
+ async function sessionLinkedCompanions(
70
+ cwd: string,
71
+ options?: { write?: boolean },
72
+ ): Promise<CompanionMatch[]> {
73
+ return launchAmbiguityDeps.resolveLinkedCompanions(
74
+ repositoryFromEnvironment(cwd)?.path ?? cwd,
75
+ options,
76
+ );
77
+ }
78
+
79
+ export async function withLinkedCompanionHints(
80
+ message: string,
81
+ change: string,
82
+ inUse: string,
83
+ ): Promise<string> {
84
+ let holders: string[];
85
+ try {
86
+ const linked = await sessionLinkedCompanions(process.cwd(), { write: false });
87
+ holders = await findChangeInLinkedCompanions(
88
+ linked.map((match) => match.companionPath),
89
+ change,
90
+ inUse,
91
+ );
92
+ } catch {
93
+ return message;
94
+ }
95
+ const hints = holders.map(
96
+ (holder) =>
97
+ `${FRAMEWORK_NAME}: ${change} is in the linked companion ${holder}; re-run with --companion ${/^[\w./-]+$/.test(holder) ? holder : shellQuote(holder)}.`,
98
+ );
99
+ return [message, ...hints].join("\n");
100
+ }
101
+
102
+ export function takeCompanionFlag(
103
+ args: string[],
104
+ ): { args: string[]; companion?: string } | { error: string } {
105
+ const rest: string[] = [];
106
+ let companion: string | undefined;
107
+ for (let index = 0; index < args.length; index += 1) {
108
+ const arg = args[index]!;
109
+ if (arg === "--companion") {
110
+ const value = args[index + 1];
111
+ if (!value || value.startsWith("--")) return { error: "--companion requires a path" };
112
+ companion = value;
113
+ index += 1;
114
+ } else if (arg.startsWith("--companion=")) {
115
+ const value = arg.slice("--companion=".length);
116
+ if (!value) return { error: "--companion requires a path" };
117
+ companion = value;
118
+ } else {
119
+ rest.push(arg);
120
+ }
121
+ }
122
+ return companion === undefined ? { args: rest } : { args: rest, companion };
123
+ }
124
+
61
125
  /**
62
126
  * Rank 1. Validated against the Linked Companions so a wrap can never record a
63
127
  * companion that does not link the Working Repository.
64
128
  */
65
- async function pinExplicitCompanion(cwd: string, companion: string): Promise<boolean> {
129
+ async function pinExplicitCompanion(
130
+ cwd: string,
131
+ companion: string,
132
+ sessionRepository = false,
133
+ ): Promise<boolean> {
66
134
  const resolved = path.resolve(companion);
67
- const linked = await launchAmbiguityDeps.resolveLinkedCompanions(cwd);
135
+ const linked = sessionRepository
136
+ ? await sessionLinkedCompanions(cwd)
137
+ : await launchAmbiguityDeps.resolveLinkedCompanions(cwd);
68
138
  const chosen = linked.find((match) => path.resolve(match.companionPath) === resolved);
69
139
  if (!chosen) {
70
140
  reportLinkedCompanions(
@@ -112,7 +182,9 @@ export async function ensureUnambiguousCompanion(
112
182
  cwd: string = process.cwd(),
113
183
  options: CompanionSelectionOptions = {},
114
184
  ): Promise<boolean> {
115
- if (options.companion) return pinExplicitCompanion(cwd, options.companion);
185
+ if (options.companion) {
186
+ return pinExplicitCompanion(cwd, options.companion, options.sessionRepository);
187
+ }
116
188
  if (process.env.MATE_ARTIFACT_PATH && !options.reselect) return true;
117
189
 
118
190
  const ambiguousMatches = await launchAmbiguityDeps.resolveCompanionMatches(cwd);
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "1.0.1-canary.2",
3
- "sha512": "sha512-2jfqdRqW5MddrYlP+r+wCjiJI5HWCSZN8ErbgGUFcTf/VbS6mDFw7sBKqyuaemhLOX94pVebOdnnHkU3h4TBoQ=="
2
+ "version": "1.0.2-canary.0",
3
+ "sha512": "sha512-Fb5H0vqrRjJFPQzboE/BvMAgVvZa9FG88ZlubyHek+QKT7fU4nfFTilRvWQTFxa2arcO10A5ADT2L5B7x1C1Mw=="
4
4
  }
@@ -45,6 +45,7 @@ import { turnHooksEnabled } from "../../../runtime/workflow/turn";
45
45
  import { type BooleanFlagSet, parseFlags, positionalArgs, stringFlag } from "../../parse-flags";
46
46
  import { usage } from "../../usage";
47
47
  import { commandOutput, type CommandOutput } from "../artifact/delivery/output";
48
+ import { withLinkedCompanionHints } from "../shared/companion-selection";
48
49
 
49
50
  export interface WorkflowCommandDeps {
50
51
  /** The Session Companion's path; resolved from the launch environment by default. */
@@ -269,7 +270,13 @@ async function runDone(argv: string[], run: Run, deps: WorkflowCommandDeps): Pro
269
270
  const { companionPath, workflow } = resolved;
270
271
  try {
271
272
  const reported = await reportStep(openWork(companionPath, workflow), workflow, skill, name);
272
- if ("problem" in reported) return fail(run, [{ path: "", message: reported.problem }]);
273
+ if ("problem" in reported) {
274
+ const { problem, missing } = reported;
275
+ const message = missing
276
+ ? await withLinkedCompanionHints(problem, missing, companionPath)
277
+ : problem;
278
+ return fail(run, [{ path: "", message }]);
279
+ }
273
280
  await noteForTurn(deps.env ?? process.env, skill, name ?? "");
274
281
  const { handoff, ...done } = reported;
275
282
  const result: StepDone = {
@@ -348,7 +355,11 @@ async function runNext(argv: string[], run: Run, deps: WorkflowCommandDeps): Pro
348
355
  return fail(run, [{ path: "", message: noStep(workflow, after) }]);
349
356
  }
350
357
  const found = await openWork(companionPath, workflow).find(name);
351
- if ("problem" in found) return fail(run, [{ path: "", message: found.problem }]);
358
+ if ("problem" in found) {
359
+ return fail(run, [
360
+ { path: "", message: await withLinkedCompanionHints(found.problem, name, companionPath) },
361
+ ]);
362
+ }
352
363
  try {
353
364
  const { progress, subject } = await found.input();
354
365
  const { stage: position, open, handoff } = pathPosition(workflow, progress, subject, after);
@@ -12,7 +12,7 @@ import {
12
12
  import { runWrapPass, type WrapPassResult } from "../../lib/orchestrator/wrap-pass";
13
13
  import { withCompanionLock } from "../../runtime/companion-lock";
14
14
  import { WRAP_RUNTIMES } from "../../runtime/wrap-state";
15
- import { launchAmbiguityDeps } from "./shared/companion-selection";
15
+ import { launchAmbiguityDeps, takeCompanionFlag } from "./shared/companion-selection";
16
16
 
17
17
  export interface WrapCommandDependencies {
18
18
  findRepoLocalLinkedRepository?: typeof findRepoLocalLinkedRepository;
@@ -43,25 +43,11 @@ function reportChangedPaths(changed: ProjectionChangedPaths): void {
43
43
  * is parsed there too; this only rejects anything else.
44
44
  */
45
45
  export function parseWrapArgs(argv: string[]): { companion?: string } | { error: string } {
46
- let companion: string | undefined;
47
- for (let index = 0; index < argv.length; index += 1) {
48
- const arg = argv[index]!;
49
- if (arg === "--companion") {
50
- const value = argv[index + 1];
51
- if (!value || value.startsWith("--")) return { error: "--companion requires a path" };
52
- companion = value;
53
- index += 1;
54
- continue;
55
- }
56
- if (arg.startsWith("--companion=")) {
57
- const value = arg.slice("--companion=".length);
58
- if (!value) return { error: "--companion requires a path" };
59
- companion = value;
60
- continue;
61
- }
62
- return { error: `unknown wrap option: ${arg}` };
63
- }
64
- return companion === undefined ? {} : { companion };
46
+ const taken = takeCompanionFlag(argv);
47
+ if ("error" in taken) return taken;
48
+ const { args, ...picked } = taken;
49
+ if (args.length > 0) return { error: `unknown wrap option: ${args[0]}` };
50
+ return picked;
65
51
  }
66
52
 
67
53
  /**
package/src/cli/main.ts CHANGED
@@ -37,6 +37,7 @@ import {
37
37
  import { resolveRootContext } from "../lib/orchestrator/root-context";
38
38
  import {
39
39
  ensureUnambiguousCompanion,
40
+ takeCompanionFlag,
40
41
  type CompanionSelectionOptions,
41
42
  } from "./commands/shared/companion-selection";
42
43
  import { ensureRuntimeDirectory, refreshRuntimeDirectory } from "../lib/runtime-directory-refresh";
@@ -279,18 +280,22 @@ export async function main(argv = process.argv, deps: MainDeps = mainDeps): Prom
279
280
  await runPluginCommand(subcommand, rest);
280
281
  return;
281
282
  case "artifact":
282
- if (!(await gate({ updateGuard: true, companion: true, install: true }))) return;
283
- await runArtifactCommand(subcommand, rest);
284
- return;
285
- case "workflow":
286
- // The gates of `artifact`: a stage skill resolves and records in its Session Companion.
287
- // `next` writes nothing and the turn hooks run it, so a required update cannot switch
288
- // their hand-off check off.
289
- if (!(await gate({ updateGuard: subcommand !== "next", companion: true, install: true }))) {
283
+ case "workflow": {
284
+ const taken = takeCompanionFlag(argv.slice(3));
285
+ if ("error" in taken) {
286
+ console.error(`${FRAMEWORK_NAME}: ${taken.error}`);
287
+ process.exitCode = 1;
290
288
  return;
291
289
  }
292
- await runWorkflowCommand(subcommand, rest);
290
+ const [sub, ...subArgs] = taken.args;
291
+ const companion = taken.companion
292
+ ? { companion: taken.companion, sessionRepository: true }
293
+ : true;
294
+ const runByTurnHooks = command === "workflow" && sub === "next";
295
+ if (!(await gate({ updateGuard: !runByTurnHooks, companion, install: true }))) return;
296
+ await (command === "artifact" ? runArtifactCommand : runWorkflowCommand)(sub, subArgs);
293
297
  return;
298
+ }
294
299
  case "companion":
295
300
  switch (subcommand) {
296
301
  // setup/link are recovery paths and must never be gated on the
package/src/cli/usage.ts CHANGED
@@ -53,10 +53,12 @@ export function usage(): string {
53
53
  " [--json] one triple per stale requirement of the change",
54
54
  ` ${n} artifact project <change> [--json]`,
55
55
  ` ${n} artifact apply-context <change> --json [--since <digest>]`,
56
+ ` ${n} artifact <subcommand> ... [--companion <path>] in that Linked Companion, for this command`,
56
57
  ` ${n} workflow steps <stage> [--json] a Delivery Path stage's steps, entry and next stage`,
57
58
  ` ${n} workflow done <skill> [<change>] [--json] record a finished step; prints the next`,
58
59
  ` ${n} workflow next <change> [--after <skill>] [--json] the stage a change is at and its next actions`,
59
60
  ` ${n} workflow trust [--json] approve the run: commands the companion's workflow declares`,
61
+ ` ${n} workflow <subcommand> ... [--companion <path>] in that Linked Companion, for this command`,
60
62
  ` ${n} doctor`,
61
63
  ` ${n} friction on record Mate's friction on this machine (off by default)`,
62
64
  ` ${n} friction off stop recording; the records stay`,
@@ -38,15 +38,16 @@ export function noStep(workflow: Workflow, skill: string): string {
38
38
 
39
39
  /**
40
40
  * Reports step `skill` for the work named `name`, recording it when the stage records it. A
41
- * missing work is a problem only where it should exist; before that, and without `name`, the
42
- * hand-off goes by stage order. Throws on a record that cannot be read or written.
41
+ * missing work is a problem only where it should exist, then `missing` names it; before that, and
42
+ * without `name`, the hand-off goes by stage order. Throws on a record that cannot be read or
43
+ * written.
43
44
  */
44
45
  export async function reportStep(
45
46
  work: Work,
46
47
  workflow: Workflow,
47
48
  skill: string,
48
49
  name?: string,
49
- ): Promise<ReportedStep | { problem: string }> {
50
+ ): Promise<ReportedStep | { problem: string; missing?: string }> {
50
51
  const rule = stepReport(workflow, skill);
51
52
  if (!rule) return { problem: noStep(workflow, skill) };
52
53
  let item: WorkItem | null = null;
@@ -54,7 +55,7 @@ export async function reportStep(
54
55
  if (name && rule.stage.milestone !== "published") {
55
56
  const found = await work.find(name);
56
57
  if (!("problem" in found)) item = found;
57
- else if (rule.needsWork) return found;
58
+ else if (rule.needsWork) return { ...found, missing: name };
58
59
  }
59
60
  const records = item !== null && rule.records;
60
61
  if (records) await item!.recordStep(rule.stage.id, skill);
@@ -3,7 +3,7 @@ import path from "node:path";
3
3
  import { changeNames, locate } from "../change-layout";
4
4
  import { readDeliveryRecord, recordStep } from "../delivery/record";
5
5
  import { submitArtifactType } from "../delivery/staging/registry";
6
- import type { Workflow } from "./declaration";
6
+ import { readWorkflow, type Workflow } from "./declaration";
7
7
  import type { PathProgress, PathSubject } from "./position";
8
8
 
9
9
  /**
@@ -49,6 +49,30 @@ export interface WorkOptions {
49
49
  root?: string;
50
50
  }
51
51
 
52
+ /**
53
+ * The companions of `linked`, other than `inUse`, that hold `name` as active work. Each is read
54
+ * through its own workflow; one whose workflow cannot be read is skipped.
55
+ */
56
+ export async function findChangeInLinkedCompanions(
57
+ linked: string[],
58
+ name: string,
59
+ inUse: string,
60
+ ): Promise<string[]> {
61
+ const others = linked.filter((companion) => path.resolve(companion) !== path.resolve(inUse));
62
+ const held = await Promise.all(
63
+ others.map(async (companion) => {
64
+ try {
65
+ const verdict = readWorkflow(companion);
66
+ if (!verdict.ok) return false;
67
+ return !("problem" in (await openWork(companion, verdict.workflow).find(name)));
68
+ } catch {
69
+ return false;
70
+ }
71
+ }),
72
+ );
73
+ return others.filter((_, index) => held[index]);
74
+ }
75
+
52
76
  /** The work of `workflow`'s companion at `companionPath`. */
53
77
  export function openWork(
54
78
  companionPath: string,
@@ -7,59 +7,142 @@ export const HEREDOC_MARKER = /^<<-?\s*(['"]?)([\w.-]+)\1/;
7
7
  * place to the state at the end.
8
8
  */
9
9
  export function commandTextMask(text: string, spans: string[] = []): boolean[] {
10
+ return scanCommandText(text, spans, true);
11
+ }
12
+
13
+ const NO_COMMAND_SPANS = new Set(["'", "$'", '"', "((", "$((", "$["]);
14
+
15
+ // The heredoc scan passes false: a marker found by mistake hides the lines after it from every guard.
16
+ function scanCommandText(text: string, spans: string[], ambiguousIsCommand: boolean): boolean[] {
10
17
  const mask = Array.from({ length: text.length }, () => false);
18
+ const closes = new Map<number, number>();
19
+ let wordStart = startsWords(spans.at(-1));
11
20
  for (let i = 0; i < text.length; i++) {
12
21
  const span = spans.at(-1);
13
- const char = text[i];
14
- mask[i] = span !== "'" && span !== "$'" && span !== '"' && span !== "((";
22
+ const char = text[i]!;
23
+ const open = arithmeticOpen(text, i, wordStart);
24
+ let nextWordStart = startsWords(span) && /[ \t\n;&|()]/.test(char);
25
+ mask[i] =
26
+ span === "${" ? ambiguousIsCommand : span === undefined || !NO_COMMAND_SPANS.has(span);
15
27
  if (span === "'") {
16
28
  if (char === "'") spans.pop();
17
29
  } else if (span === "$'") {
18
30
  if (char === "\\") i++;
19
31
  else if (char === "'") spans.pop();
20
32
  } else if (char === "\\") {
33
+ nextWordStart = text[i + 1] === "\n" && wordStart;
21
34
  i++;
22
- } else if (
23
- char === "#" &&
24
- (span === undefined || span === "(" || span === "`") &&
25
- (i === 0 || /[\s;&|()`]/.test(text[i - 1]!))
26
- ) {
35
+ } else if (char === "$" && text[i + 1] === "$") {
36
+ i++;
37
+ } else if (char === "#" && wordStart) {
27
38
  mask[i] = false;
28
- const end = text.indexOf("\n", i);
29
- i = end === -1 ? text.length : end - 1;
39
+ i = commentEnd(text, i, span === "`") - 1;
40
+ } else if (wordStart && keywordAt(text, i, "case")) {
41
+ spans.push("case");
42
+ i += 3;
43
+ } else if (wordStart && span === "case" && keywordAt(text, i, "esac")) {
44
+ spans.pop();
45
+ i += 3;
30
46
  } else if (char === "`") {
31
47
  if (span === "`") spans.pop();
32
- else spans.push("`");
48
+ else {
49
+ spans.push("`");
50
+ nextWordStart = true;
51
+ }
33
52
  } else if (char === "$" && text[i + 1] === "'" && span !== '"') {
34
53
  spans.push("$'");
35
54
  i++;
36
- } else if (char === "$" && text[i + 1] === "(" && text[i + 2] === "(") {
37
- spans.push("((");
38
- i += 2;
55
+ } else if (char === "$" && text[i + 1] === "[") {
56
+ spans.push("$[");
57
+ i++;
58
+ } else if (open !== undefined && (!ambiguousIsCommand || !opensSubshell(text, open, closes))) {
59
+ spans.push("$((");
60
+ i = open;
39
61
  } else if (char === "$" && text[i + 1] === "(") {
40
- spans.push("(");
62
+ spans.push("$(");
63
+ nextWordStart = true;
64
+ i++;
65
+ } else if (char === "$" && text[i + 1] === "{" && (startsWords(span) || span === "${")) {
66
+ spans.push("${");
41
67
  i++;
42
68
  } else if (span === '"') {
43
69
  if (char === '"') spans.pop();
44
- } else if (span === "((") {
70
+ } else if (span === "((" || span === "$((") {
45
71
  if (char === "(") spans.push("((");
46
- else if (char === ")") {
47
- spans.pop();
48
- if (spans.at(-1) !== "((" && text[i + 1] === ")") i++;
49
- }
72
+ else if (char === ")" && spans.pop() === "$((" && text[i + 1] === ")") i++;
73
+ } else if (span === "$[") {
74
+ if (char === "[") spans.push("$[");
75
+ else if (char === "]") spans.pop();
50
76
  } else if (char === "'" || char === '"') {
51
77
  spans.push(char);
52
- } else if (span === "(") {
78
+ } else if (span === "(" || span === "$(" || span === "case") {
53
79
  if (char === "(") spans.push("(");
54
- else if (char === ")") spans.pop();
80
+ else if (char === ")" && span !== "case") nextWordStart = spans.pop() === "(";
81
+ } else if (span === "${") {
82
+ if (char === "{") spans.push("${");
83
+ else if (char === "}") spans.pop();
55
84
  }
85
+ wordStart = nextWordStart;
56
86
  }
57
87
  return mask;
58
88
  }
59
89
 
90
+ function startsWords(span: string | undefined): boolean {
91
+ return span === undefined || span === "(" || span === "$(" || span === "`" || span === "case";
92
+ }
93
+
94
+ function keywordAt(text: string, i: number, word: string): boolean {
95
+ return text.startsWith(word, i) && /^[\s;&|()]?$/.test(text[i + word.length] ?? "");
96
+ }
97
+
98
+ function arithmeticOpen(text: string, i: number, wordStart: boolean): number | undefined {
99
+ const open = text[i] === "$" ? i + 2 : wordStart ? i + 1 : undefined;
100
+ return open !== undefined && text[open - 1] === "(" && text[open] === "(" ? open : undefined;
101
+ }
102
+
103
+ function commentEnd(text: string, start: number, inBackticks: boolean): number {
104
+ for (let i = start + 1; i < text.length; i++) {
105
+ if (text[i] === "\n") return i;
106
+ if (!inBackticks) continue;
107
+ if (text[i] === "\\") i++;
108
+ else if (text[i] === "`") return i;
109
+ }
110
+ return text.length;
111
+ }
112
+
113
+ function opensSubshell(text: string, open: number, closes: Map<number, number>): boolean {
114
+ if (!closes.has(open)) matchParens(text, open, closes);
115
+ const close = closes.get(open)!;
116
+ return close !== -1 && text[close + 1] !== ")";
117
+ }
118
+
119
+ function matchParens(text: string, open: number, closes: Map<number, number>): void {
120
+ const opens: number[] = [];
121
+ for (let i = open; i < text.length; i++) {
122
+ const char = text[i];
123
+ if (char === "\\") i++;
124
+ else if (char === "'" || char === '"')
125
+ i = quoteEnd(text, i, char === '"' || text[i - 1] === "$");
126
+ else if (char === "(") opens.push(i);
127
+ else if (char === ")") {
128
+ closes.set(opens.pop()!, i);
129
+ if (opens.length === 0) return;
130
+ }
131
+ }
132
+ for (const unclosed of opens) closes.set(unclosed, -1);
133
+ }
134
+
135
+ function quoteEnd(text: string, start: number, escapes: boolean): number {
136
+ for (let i = start + 1; i < text.length; i++) {
137
+ if (escapes && text[i] === "\\") i++;
138
+ else if (text[i] === text[start]) return i;
139
+ }
140
+ return text.length;
141
+ }
142
+
60
143
  function heredocTerminators(line: string, spans: string[]): string[] {
61
144
  const terminators: string[] = [];
62
- const isCommand = commandTextMask(line, spans);
145
+ const isCommand = scanCommandText(line, spans, false);
63
146
  for (let i = 0; i < line.length; i++) {
64
147
  if (!isCommand[i] || line[i] !== "<" || line[i + 1] !== "<") continue;
65
148
  if (line[i + 2] === "<") {