@a2f0/agent-tool 0.1.58 → 0.1.60

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.
@@ -2,13 +2,19 @@ import { existsSync, readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { packageDirectories } from "../system/workspace";
4
4
 
5
- /** A test run or dependency install that a push-gate step reaches, with the chain that led to it. */
6
- export interface StepFinding { kind: "test" | "install"; runner: string; chain: string[] }
5
+ /** A test run, build, or dependency install that a push-gate step reaches, with the chain that led to it. */
6
+ export interface StepFinding { kind: "test" | "build" | "install"; runner: string; chain: string[] }
7
7
  export interface StepResolution { findings: StepFinding[]; errors: string[] }
8
8
 
9
9
  const MAX_DEPTH = 32;
10
10
  const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh"]);
11
- const WRAPPERS = new Set(["exec", "command", "time", "nohup", "nice"]);
11
+ /** Commands that run the command after them, with their options that take a separate value. */
12
+ const WRAPPERS: ReadonlyMap<string, ReadonlySet<string>> = new Map(Object.entries({
13
+ exec: ["-a"], command: [], nohup: [], nice: ["-n", "--adjustment"], time: ["-o", "--output", "-f", "--format"],
14
+ timeout: ["-s", "--signal", "-k", "--kill-after"], stdbuf: ["-i", "-o", "-e", "--input", "--output", "--error"],
15
+ env: ["-u", "--unset", "-C", "--chdir", "-S", "--split-string", "-a", "--argv0", "--env0-from", "-P", "-L", "-U"],
16
+ xargs: ["-a", "--arg-file", "-d", "--delimiter", "-E", "-I", "-J", "-L", "--max-lines", "-n", "--max-args", "-P", "--max-procs", "-R", "-S", "-s", "--max-chars", "--process-slot-var"],
17
+ }).map(([name, values]) => [name, new Set(values)]));
12
18
  const KEYWORDS = new Set(["if", "then", "else", "elif", "do", "while", "until", "!", "{", "}", "fi", "done", "esac"]);
13
19
  const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
14
20
 
@@ -21,7 +27,7 @@ const TOOLS = {
21
27
  pnpm: tool(["-C", "--dir", "--filter", "-F", "--reporter"], ["--filter", "-F", "--recursive", "-r"]),
22
28
  yarn: tool(["--cwd"]),
23
29
  exec: tool(["-p", "--package", "-c", "--call"]),
24
- turbo: tool(["--filter", "-F", "--concurrency", "--cache-dir", "--output-logs", "--log-order", "--log-prefix", "--env-mode", "--ui", "--cache", "--profile", "--graph", "--summarize"]),
30
+ turbo: tool(["--filter", "-F", "--concurrency", "--cache-dir", "--output-logs", "--log-order", "--log-prefix", "--env-mode", "--ui", "--cache", "--profile", "--graph", "--summarize", "--cwd", "--root-turbo-json", "--heap", "--team", "--token", "--api", "--login", "--trace", "--cpuprofile", "--remote-cache-timeout", "--cache-workers", "--pkg-inference-root"]),
25
31
  } as const;
26
32
  const INSTALLS: Record<"bun" | "npm" | "pnpm" | "yarn", string[]> = {
27
33
  bun: ["install", "i", "add", "a", "update", "remove", "rm"],
@@ -34,10 +40,14 @@ interface Context { root: string; seen: Set<string>; findings: StepFinding[]; er
34
40
 
35
41
  /**
36
42
  * Follow a declared push-gate step through package scripts, shell strings,
37
- * and `agent-tool run-group` plans to every test runner or dependency install
38
- * it reaches. Executables and script files are leaves: their contents are not
43
+ * command runners such as `env`, `uv run`, or `python -m`, and `agent-tool
44
+ * run-group` plans to every test runner, build, or dependency install it
45
+ * reaches. Executables and script files are leaves: their contents are not
39
46
  * inspected. Workspace filters resolve to every workspace package declaring
40
- * the script, which can over-report but never misses one.
47
+ * the script, which can over-report but never misses one. A command that both
48
+ * builds and tests, such as `cargo test`, is reported once, as a test; a runner
49
+ * that installs before running its command, such as `uv run pytest`, is
50
+ * reported as an install and its command as what it does.
41
51
  */
42
52
  export function resolveStep(root: string, command: string[]): StepResolution {
43
53
  const context: Context = { root, seen: new Set(), findings: [], errors: [] };
@@ -50,16 +60,34 @@ function report(context: Context, kind: StepFinding["kind"], runner: string, cha
50
60
  context.findings.push({ kind, runner, chain: chain.at(-1) === runner ? chain : [...chain, runner] });
51
61
  }
52
62
 
63
+ /**
64
+ * The options in one word, as getopt reads them: `--name=value`, `--name`
65
+ * with its value in the next word, or bundled short options (`-iC dir`,
66
+ * `-Cdir`), where the first that takes a value takes the rest of the word or,
67
+ * when nothing is left, the next word, which `next` supplies.
68
+ */
69
+ function optionWords(word: string, takesValue: ReadonlySet<string>, next: () => string | undefined): [string, string | undefined][] {
70
+ if (word.startsWith("--") || word.length <= 2) {
71
+ const equals = word.indexOf("=");
72
+ return equals > 0 ? [[word.slice(0, equals), word.slice(equals + 1)]] : [[word, takesValue.has(word) ? next() : undefined]];
73
+ }
74
+ const found: [string, string | undefined][] = [];
75
+ for (let at = 1; at < word.length; at++) {
76
+ const name = `-${word[at]}`;
77
+ if (!takesValue.has(name)) { found.push([name, undefined]); continue; }
78
+ const rest = word.slice(at + 1).replace(/^=/, "");
79
+ found.push([name, rest || next()]);
80
+ break;
81
+ }
82
+ return found;
83
+ }
84
+
53
85
  /** Skip leading options, consuming the separate value of the ones that take one; returns the options seen. */
54
86
  function options(argv: string[], spec: Tool): { rest: string[]; seen: Map<string, string | true> } {
55
87
  const seen = new Map<string, string | true>();
56
88
  let index = 0;
57
89
  while (index < argv.length && argv[index]!.startsWith("-") && argv[index] !== "--") {
58
- const value = argv[index]!;
59
- const equals = value.indexOf("=");
60
- if (equals > 0) seen.set(value.slice(0, equals), value.slice(equals + 1));
61
- else if (spec.values.has(value) && index + 1 < argv.length) { seen.set(value, argv[index + 1]!); index++; }
62
- else seen.set(value, true);
90
+ for (const [name, value] of optionWords(argv[index]!, spec.values, () => index + 1 < argv.length ? argv[++index] : undefined)) seen.set(name, value ?? true);
63
91
  index++;
64
92
  }
65
93
  return { rest: argv.slice(index), seen };
@@ -100,29 +128,29 @@ function scripts(directory: string): Record<string, unknown> | null {
100
128
  * arguments appended, then `post<name>`. An unknown name runs `fallback`, the
101
129
  * executable or file of that name, when the manager does so.
102
130
  */
103
- /** Workspace packages from `package.json` workspaces and from pnpm's `pnpm-workspace.yaml`. */
104
- function workspaceDirectories(context: Context): string[] {
105
- const directories = new Set(packageDirectories(context.root));
106
- const file = path.join(context.root, "pnpm-workspace.yaml");
131
+ /** Workspace packages of the workspace rooted at `root` (the repository's by default), from `package.json` workspaces and pnpm's `pnpm-workspace.yaml`. */
132
+ function workspaceDirectories(context: Context, root = context.root): string[] {
133
+ const directories = new Set(packageDirectories(root));
134
+ const file = path.join(root, "pnpm-workspace.yaml");
107
135
  if (!existsSync(file)) return [...directories];
108
136
  let patterns: unknown;
109
137
  try { patterns = (Bun.YAML.parse(readFileSync(file, "utf8")) as { packages?: unknown } | null)?.packages; }
110
- catch (error) { context.errors.push(`Cannot read pnpm-workspace.yaml: ${(error as Error).message}`); return [...directories]; }
138
+ catch (error) { context.errors.push(`Cannot read ${path.relative(context.root, file) || file}: ${(error as Error).message}`); return [...directories]; }
111
139
  const list = (Array.isArray(patterns) ? patterns : []).filter((pattern): pattern is string => typeof pattern === "string");
112
140
  const excluded = list.filter(pattern => pattern.startsWith("!")).map(pattern => new Bun.Glob(pattern.slice(1).replace(/\/$/, "")));
113
141
  for (const pattern of list.filter(pattern => !pattern.startsWith("!"))) {
114
- for (const match of new Bun.Glob(`${pattern.replace(/\/$/, "")}/package.json`).scanSync({ cwd: context.root, onlyFiles: true })) {
142
+ for (const match of new Bun.Glob(`${pattern.replace(/\/$/, "")}/package.json`).scanSync({ cwd: root, onlyFiles: true })) {
115
143
  const relative = path.dirname(match);
116
- if (!match.split("/").includes("node_modules") && !excluded.some(glob => glob.match(relative))) directories.add(path.join(context.root, relative));
144
+ if (!match.split("/").includes("node_modules") && !excluded.some(glob => glob.match(relative))) directories.add(path.join(root, relative));
117
145
  }
118
146
  }
119
147
  return [...directories];
120
148
  }
121
149
 
122
- /** Package managers run scripts from the nearest `package.json` at or above the directory, within the repository. */
123
- function packageRoot(context: Context, directory: string): string {
150
+ /** Package managers run scripts from the nearest `package.json` (or other `manifest`) at or above the directory, within the repository. */
151
+ function packageRoot(context: Context, directory: string, manifest = "package.json"): string {
124
152
  let current = directory;
125
- while (!existsSync(path.join(current, "package.json")) && current !== context.root && current.startsWith(`${context.root}${path.sep}`)) current = path.dirname(current);
153
+ while (!existsSync(path.join(current, manifest)) && current !== context.root && current.startsWith(`${context.root}${path.sep}`)) current = path.dirname(current);
126
154
  return current;
127
155
  }
128
156
 
@@ -147,12 +175,46 @@ function runScript(context: Context, name: string, args: string[], directory: st
147
175
  if (!found && fallback) visit(context, fallback, directory, chain, depth + 1);
148
176
  }
149
177
 
150
- function visit(context: Context, input: string[], cwd: string, chain: string[], depth: number): void {
151
- if (depth > MAX_DEPTH) { context.errors.push(`Resolution deeper than ${MAX_DEPTH} levels: ${chain.join(" -> ")}`); return; }
178
+ /**
179
+ * Strip what runs a command rather than being it: `NAME=value` assignments and
180
+ * wrappers such as `env -u NAME`, `nice -n 5`, or `timeout 60`, with their
181
+ * options. Returns the command and the directory it runs in (`env -C`), or
182
+ * null when nothing runs (`command -v`).
183
+ */
184
+ function unwrap(input: string[], cwd: string): { argv: string[]; cwd: string } | null {
152
185
  const argv = [...input];
153
- while (argv.length && (ASSIGNMENT.test(argv[0]!) || WRAPPERS.has(argv[0]!))) argv.shift();
154
- if (argv[0] === "env") { argv.shift(); while (argv.length && (argv[0]!.startsWith("-") || ASSIGNMENT.test(argv[0]!))) argv.shift(); }
155
- if (!argv.length) return;
186
+ let directory = cwd;
187
+ while (argv.length) {
188
+ if (ASSIGNMENT.test(argv[0]!)) { argv.shift(); continue; }
189
+ const wrapper = path.basename(argv[0]!);
190
+ const takesValue = WRAPPERS.get(wrapper);
191
+ if (!takesValue) break;
192
+ argv.shift();
193
+ while (argv[0]?.startsWith("-")) {
194
+ const option = argv.shift()!;
195
+ if (option === "--") break;
196
+ for (const [name, value] of optionWords(option, takesValue, () => argv.shift())) {
197
+ // `command -v` and `command -V` only describe the command.
198
+ if (wrapper === "command" && (name === "-v" || name === "-V")) return null;
199
+ if (wrapper !== "env" || value === undefined) continue;
200
+ if (name === "-C" || name === "--chdir") directory = path.resolve(directory, value);
201
+ // `env -S 'a b'` reads its words as if they were given separately.
202
+ else if (name === "-S" || name === "--split-string") argv.unshift(...splitShell(value).flat());
203
+ }
204
+ }
205
+ // `timeout` takes its duration before the command.
206
+ if (wrapper === "timeout") argv.shift();
207
+ }
208
+ return { argv, cwd: directory };
209
+ }
210
+
211
+ function visit(context: Context, input: string[], invokedIn: string, chain: string[], depth: number): void {
212
+ if (depth > MAX_DEPTH) { context.errors.push(`Resolution deeper than ${MAX_DEPTH} levels: ${chain.join(" -> ")}`); return; }
213
+ const unwrapped = unwrap(input, invokedIn);
214
+ if (unwrapped?.argv.length) dispatch(context, unwrapped.argv, unwrapped.cwd, chain, depth);
215
+ }
216
+
217
+ function dispatch(context: Context, argv: string[], cwd: string, chain: string[], depth: number): void {
156
218
  // `npx vitest@4` names the runner with a version selector.
157
219
  const name = path.basename(argv[0]!).replace(/(?<=.)@[^@/]*$/, "");
158
220
  const args = argv.slice(1);
@@ -165,55 +227,225 @@ function visit(context: Context, input: string[], cwd: string, chain: string[],
165
227
  } else if (name === "bun") bun(context, args, cwd, chain, depth, text);
166
228
  else if (name === "bunx" || name === "npx") execute(context, args, cwd, chain, depth);
167
229
  else if (name === "npm" || name === "pnpm" || name === "yarn") packageManager(context, name, args, cwd, chain, depth, text);
168
- else if (name === "turbo") { if (turboTasks(args).some(task => /^test/.test(task.slice(task.lastIndexOf("#") + 1)))) report(context, "test", text, chain); }
230
+ else if (name === "turbo") turbo(context, args, cwd, chain, text);
231
+ else if (name === "uv" || name === "uvx") uv(context, name === "uvx" ? ["tool", "run", ...args] : args, cwd, chain, depth, text);
232
+ else if (name === "poetry" || name === "pdm" || name === "hatch" || name === "pipenv" || name === "pipx") pythonProject(context, name, args, cwd, chain, depth, text);
233
+ else if (/^python[\d.]*$/.test(name)) python(context, args, cwd, chain, depth, text);
234
+ else if (name === "coverage") { if (args[0] === "run") coverageRun(context, args.slice(1), cwd, chain, depth, text); }
235
+ else if (name === "mise") mise(context, args, cwd, chain, depth);
169
236
  else if (testRunner(name, args)) report(context, "test", text, chain);
170
- else if (["pod", "bundle", "pip", "pip3"].includes(name) && args[0] === "install") report(context, "install", text, chain);
237
+ else if (builds(name, args)) report(context, "build", text, chain);
238
+ else if ((name === "pod" || name === "bundle") && args[0] === "install") report(context, "install", text, chain);
239
+ else if (/^pip[\d.]*$/.test(name) && options(args, PYTHON_TOOLS.pip).rest[0] === "install" && !previews("pip", "install", args)) report(context, "install", text, chain);
171
240
  else if (name === "bundle" && args[0] === "exec") visit(context, args.slice(1), cwd, chain, depth + 1);
172
241
  }
173
242
 
174
- function turboTasks(args: string[]): string[] {
175
- const rest = args[0] === "run" ? args.slice(1) : args;
176
- const tasks: string[] = [];
177
- for (let index = 0; index < rest.length; index++) {
178
- const value = rest[index]!;
243
+ /* Options, per tool, that take a separate value, so `--profile release` or `-x build` is never read as a subcommand or task. */
244
+ const WEBPACK_VALUES: ReadonlySet<string> = new Set(["-c", "--config", "--config-name", "--env", "--node-env", "--mode", "-o", "--output-path", "--entry", "--name", "-t", "--target", "-d", "--devtool", "--stats"]);
245
+ const DOCKER_VALUES: ReadonlySet<string> = new Set(["--config", "-c", "--context", "-H", "--host", "-l", "--log-level", "--tlscacert", "--tlscert", "--tlskey", "--builder", "-f", "--file", "-p", "--project-name", "--profile", "--env-file", "--project-directory", "--ansi", "--progress", "--parallel"]);
246
+ const GRADLE_VALUES: ReadonlySet<string> = new Set(["-p", "--project-dir", "-x", "--exclude-task", "-b", "--build-file", "-c", "--settings-file", "-g", "--gradle-user-home", "-I", "--init-script", "--include-build", "--project-cache-dir", "--console", "--warning-mode", "--max-workers", "--priority", "--update-locks", "--dependency-verification", "--write-verification-metadata", "--configuration-cache-problems", "--tests", "-D", "-P"]);
247
+ const XCODEBUILD_VALUES: ReadonlySet<string> = new Set(["-project", "-workspace", "-target", "-scheme", "-configuration", "-sdk", "-arch", "-destination", "-destination-timeout", "-xcconfig", "-toolchain", "-derivedDataPath", "-resultBundlePath", "-resultBundleVersion", "-archivePath", "-exportPath", "-exportOptionsPlist", "-clonedSourcePackagesDirPath", "-packageCachePath", "-testPlan", "-only-testing", "-skip-testing", "-only-test-configuration", "-skip-test-configuration", "-xctestrun", "-testProductsPath", "-test-iterations", "-jobs", "-parallel-testing-worker-count", "-maximum-parallel-testing-workers", "-maximum-concurrent-test-device-destinations", "-maximum-concurrent-test-simulator-destinations", "-parallel-testing-enabled", "-test-timeouts-enabled", "-default-test-execution-time-allowance", "-maximum-test-execution-time-allowance", "-test-repetition-relaunch-enabled", "-collect-test-diagnostics", "-localizationPath", "-exportLanguage", "-scmProvider", "-defaultPackageRegistryURL", "-packageDependencySCMToRegistryTransformation", "-authenticationKeyPath", "-authenticationKeyID", "-authenticationKeyIssuerID", "-framework", "-library", "-headers", "-debug-symbols", "-output", "-find-executable", "-find-library"]);
248
+ const RUNNER_VALUES: Record<string, ReadonlySet<string>> = {
249
+ go: new Set(["-C"]), cargo: new Set(["-C", "--config", "-Z", "--color"]), deno: new Set(["--config", "-c"]), swift: new Set(["--package-path"]),
250
+ vite: new Set(["-c", "--config", "--base", "-l", "--logLevel", "-m", "--mode", "--configLoader", "-f", "--filter"]),
251
+ astro: new Set(["--root", "--config", "--site", "--base", "--mode"]),
252
+ webpack: WEBPACK_VALUES, "webpack-cli": WEBPACK_VALUES, docker: DOCKER_VALUES, "docker-compose": DOCKER_VALUES,
253
+ };
254
+
255
+ /** The positional words before any `--`, skipping options and the separate values of those in `takesValue`. */
256
+ function positionals(args: string[], takesValue: ReadonlySet<string>): string[] {
257
+ const words: string[] = [];
258
+ for (let index = 0; index < args.length; index++) {
259
+ const value = args[index]!;
179
260
  if (value === "--") break;
180
- if (value.startsWith("-")) { if (!value.includes("=") && TOOLS.turbo.values.has(value)) index++; continue; }
181
- tasks.push(value);
261
+ if (value.startsWith("-")) { if (takesValue.has(value)) index++; continue; }
262
+ words.push(value);
182
263
  }
183
- return tasks;
264
+ return words;
184
265
  }
185
266
 
186
- /** Global options some runners take before their subcommand: `go -C dir test`, `cargo +nightly -Z flag test`. */
187
- const RUNNER_VALUES: Record<string, string[]> = { go: ["-C"], cargo: ["-C", "--config", "-Z", "--color"], deno: ["--config", "-c"], swift: ["--package-path"] };
267
+ /** The first positional word, after global options such as `go -C dir` or `cargo +nightly -Z flag`. */
188
268
  function subcommand(name: string, args: string[]): string | undefined {
189
- const values = RUNNER_VALUES[name] ?? [];
269
+ const takesValue = RUNNER_VALUES[name] ?? new Set();
190
270
  for (let index = 0; index < args.length; index++) {
191
271
  const value = args[index]!;
192
- if (values.includes(value)) { index++; continue; }
272
+ if (takesValue.has(value)) { index++; continue; }
193
273
  if (value.startsWith("-") || (name === "cargo" && value.startsWith("+"))) continue;
194
274
  return value;
195
275
  }
196
276
  return undefined;
197
277
  }
198
278
 
279
+ /** xcodebuild's actions: positional words other than `NAME=value` build settings. */
280
+ const xcodebuildActions = (args: string[]) => positionals(args, XCODEBUILD_VALUES).filter(word => !word.includes("="));
281
+ /** Gradle task paths such as `test` or `:app:testDebugUnitTest`. */
282
+ const gradleTask = (pattern: string) => new RegExp(`^(?::?[\\w-]+:)*(?:${pattern})$`, "i");
283
+ const GRADLE_TEST = gradleTask("test\\w*");
284
+ const GRADLE_BUILD = gradleTask("assemble\\w*|build(?:Needed|Dependents)?|bundle\\w*|install\\w*");
285
+
199
286
  function testRunner(name: string, args: string[]): boolean {
200
- if (["jest", "vitest", "mocha", "ava", "maestro", "detox", "pytest", "rspec"].includes(name)) return true;
287
+ if (["jest", "vitest", "mocha", "ava", "maestro", "detox", "pytest", "py.test", "tox", "nox", "rspec"].includes(name)) return true;
201
288
  const first = subcommand(name, args);
202
289
  if (name === "node") return args.some(arg => arg === "--test" || arg.startsWith("--test="));
203
290
  if (["playwright", "deno", "go", "swift"].includes(name)) return first === "test";
204
291
  if (name === "cargo") return first === "test" || first === "nextest";
205
- if (name === "gradle" || name === "gradlew") return args.some(arg => /^(?::?[\w-]+:)*test\w*$/i.test(arg));
206
- if (name === "xcodebuild") return args.some(arg => arg === "test" || arg === "test-without-building");
207
- if (/^python[\d.]*$/.test(name)) return args[0] === "-m" && args[1] === "pytest";
292
+ if (name === "gradle" || name === "gradlew") return positionals(args, GRADLE_VALUES).some(task => GRADLE_TEST.test(task));
293
+ if (name === "xcodebuild") return xcodebuildActions(args).some(action => action === "test" || action === "test-without-building");
208
294
  return false;
209
295
  }
210
296
 
297
+ /** webpack-cli subcommands that serve, inspect, or scaffold instead of bundling; any other first word is a build or an entry. */
298
+ const WEBPACK_OTHER = new Set(["serve", "server", "s", "info", "i", "configtest", "t", "version", "v", "help", "h", "init", "create", "new", "c", "n", "loader", "l", "plugin", "p", "migrate", "m"]);
299
+ /** xcodebuild options that only list, report, export, or resolve; without one, xcodebuild builds (its default action). */
300
+ const XCODEBUILD_OTHER = new Set(["-list", "-showBuildSettings", "-showBuildSettingsForIndex", "-showsdks", "-showdestinations", "-showTestPlans", "-version", "-usage", "-help", "-license", "-checkFirstLaunchStatus", "-runFirstLaunch", "-resolvePackageDependencies", "-exportArchive", "-create-xcframework", "-find-executable", "-find-library", "-downloadPlatform", "-downloadAllPlatforms", "-importPlatform"]);
301
+
302
+ /**
303
+ * Bundlers, framework builds, native compilers, image builds, and Python
304
+ * package builds. Static checks are not builds: `tsc` (whether `--noEmit` or
305
+ * `-b`), `cargo check|clippy|fmt`, linters, formatters, and type checkers.
306
+ */
307
+ function builds(name: string, args: string[]): boolean {
308
+ if (name === "rollup" || name === "tsup" || name === "pyproject-build") return true;
309
+ if (name === "esbuild") return args.some(arg => arg === "--bundle" || /^--out(?:file|dir)(?:=|$)/.test(arg));
310
+ const first = subcommand(name, args);
311
+ if (name === "webpack" || name === "webpack-cli") return !WEBPACK_OTHER.has(first ?? "");
312
+ if (["vite", "next", "astro", "electrobun", "swift", "go"].includes(name)) return first === "build";
313
+ if (name === "cargo") return ["build", "b", "run", "r"].includes(first ?? "");
314
+ // `expo run:ios|android` compiles the native app before launching it.
315
+ if (name === "expo") return first === "export" || /^(?:export|run):/.test(first ?? "");
316
+ if (name === "gradle" || name === "gradlew") return positionals(args, GRADLE_VALUES).some(task => GRADLE_BUILD.test(task));
317
+ if (name === "xcodebuild") {
318
+ if (args.some(arg => XCODEBUILD_OTHER.has(arg))) return false;
319
+ const actions = xcodebuildActions(args);
320
+ // Without an action, xcodebuild builds.
321
+ return !actions.length || actions.some(action => action !== "clean" && action !== "installsrc");
322
+ }
323
+ if (name === "docker-compose") return first === "build";
324
+ if (name === "docker") {
325
+ const [command, sub] = positionals(args, DOCKER_VALUES);
326
+ return command === "build" || ((command === "image" || command === "builder" || command === "compose") && sub === "build") || (command === "buildx" && ["build", "b", "bake"].includes(sub ?? ""));
327
+ }
328
+ return false;
329
+ }
330
+
331
+ /** turbo's subcommands that run no tasks. */
332
+ const TURBO_COMMANDS = new Set(["prune", "ls", "info", "query", "gen", "generate", "login", "logout", "link", "unlink", "daemon", "telemetry", "bin", "completion", "scan", "boundaries", "devtools", "docs", "config"]);
333
+
334
+ /** The tasks a `turbo` command runs: those after `run` or `watch`, or bare task names. */
335
+ function turboTasks(args: string[]): string[] {
336
+ const words = positionals(args, TOOLS.turbo.values);
337
+ if (words[0] === "run" || words[0] === "watch") return words.slice(1);
338
+ return TURBO_COMMANDS.has(words[0] ?? "") ? [] : words;
339
+ }
340
+
341
+ /** The value of `--name value` or `--name=value` before any `--`. */
342
+ function optionValue(args: string[], name: string): string | undefined {
343
+ for (let index = 0; index < args.length && args[index] !== "--"; index++) {
344
+ const value = args[index]!;
345
+ if (value === name) return args[index + 1];
346
+ if (value.startsWith(`${name}=`)) return value.slice(name.length + 1);
347
+ }
348
+ return undefined;
349
+ }
350
+
351
+ interface TurboConfig { file: string; section: string; tasks: Record<string, unknown>; extends: boolean }
352
+
353
+ function readTurboConfig(context: Context, file: string): TurboConfig | null {
354
+ const relative = path.relative(context.root, file) || file;
355
+ try {
356
+ const value: unknown = Bun.JSONC.parse(readFileSync(file, "utf8"));
357
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("expected an object");
358
+ // turbo 2 names the section `tasks`; turbo 1 named it `pipeline`.
359
+ const section = "tasks" in value ? "tasks" : "pipeline";
360
+ const tasks = (value as Record<string, unknown>)[section] ?? {};
361
+ if (!tasks || typeof tasks !== "object" || Array.isArray(tasks)) throw new Error(`expected ${section} to be an object`);
362
+ return { file: relative, section, tasks: tasks as Record<string, unknown>, extends: "extends" in value };
363
+ } catch (error) { context.errors.push(`Cannot read ${relative}: ${(error as Error).message}`); return null; }
364
+ }
365
+
366
+ function declaresWorkspaces(directory: string): boolean {
367
+ if (existsSync(path.join(directory, "pnpm-workspace.yaml"))) return true;
368
+ try { return (JSON.parse(readFileSync(path.join(directory, "package.json"), "utf8")) as { workspaces?: unknown }).workspaces !== undefined; } catch { return false; }
369
+ }
370
+
371
+ const turboFile = (directory: string) => ["turbo.json", "turbo.jsonc"].map(name => path.join(directory, name)).find(file => existsSync(file));
372
+
373
+ /**
374
+ * Every turbo configuration that can define a task: the root one, then each
375
+ * workspace package's. The root one is `--root-turbo-json` when given (read
376
+ * from the directory turbo starts in and from the repository root, wherever it
377
+ * exists), else the nearest at or above the directory turbo starts in
378
+ * (`--cwd`) without `extends`.
379
+ */
380
+ function turboConfigs(context: Context, args: string[], cwd: string): TurboConfig[] {
381
+ const loaded = new Map<string, TurboConfig | null>();
382
+ const load = (file: string) => { if (!loaded.has(file)) loaded.set(file, readTurboConfig(context, file)); return loaded.get(file)!; };
383
+ const start = path.resolve(cwd, optionValue(args, "--cwd") ?? ".");
384
+ const explicit = optionValue(args, "--root-turbo-json");
385
+ const roots: string[] = [];
386
+ if (explicit !== undefined) {
387
+ roots.push(...new Set([path.resolve(start, explicit), path.resolve(context.root, explicit)].filter(file => existsSync(file))));
388
+ if (!roots.length) context.errors.push(`Cannot read ${explicit} (--root-turbo-json): no such file.`);
389
+ } else for (let current = start; ; current = path.dirname(current)) {
390
+ const file = turboFile(current);
391
+ if (file && load(file) && !load(file)!.extends) { roots.push(file); break; }
392
+ if (current === context.root || !current.startsWith(`${context.root}${path.sep}`)) break;
393
+ }
394
+ // Packages come from the workspace turbo runs in, the nearest at or above where it starts that declares
395
+ // workspaces, and from the repository's. A workspace root is a workspace directory too, but its
396
+ // turbo.json is a root configuration, not a package's.
397
+ const workspaceRoots = new Set([context.root]);
398
+ for (let current = start; current.startsWith(`${context.root}${path.sep}`); current = path.dirname(current)) {
399
+ if (declaresWorkspaces(current)) { workspaceRoots.add(current); break; }
400
+ }
401
+ const packages = [...workspaceRoots].flatMap(root => workspaceDirectories(context, root).filter(directory => !workspaceRoots.has(directory))).flatMap(directory => turboFile(directory) ?? []);
402
+ return [...new Set([...roots, ...packages])].flatMap(file => load(file) ?? []);
403
+ }
404
+
405
+ /**
406
+ * `turbo run <task...>` runs its tasks and, unless `--only`, every task they
407
+ * depend on in turbo.json: `^name`, `name`, and `package#name` all run tasks
408
+ * named `name`. A dependency's definitions in the root and every package
409
+ * configuration are followed together, which can over-report but never misses
410
+ * one. The package scripts turbo runs for each task are not followed.
411
+ */
412
+ function turbo(context: Context, args: string[], cwd: string, chain: string[], text: string): void {
413
+ const queue = turboTasks(args).map(task => ({ task, hops: [] as string[] }));
414
+ if (!queue.length) return;
415
+ const separator = args.indexOf("--");
416
+ const configs = (separator === -1 ? args : args.slice(0, separator)).includes("--only") ? [] : turboConfigs(context, args, cwd);
417
+ const found: Partial<Record<"test" | "build", string[]>> = {};
418
+ const seen = new Set<string>();
419
+ while (queue.length) {
420
+ const { task, hops } = queue.shift()!;
421
+ const name = task.slice(task.lastIndexOf("#") + 1);
422
+ if (seen.has(name)) continue;
423
+ seen.add(name);
424
+ if (/^test/.test(name)) found.test ??= hops;
425
+ else if (/^build/.test(name)) found.build ??= hops;
426
+ for (const config of configs) {
427
+ for (const [key, definition] of Object.entries(config.tasks)) {
428
+ if (key.slice(key.lastIndexOf("#") + 1) !== name) continue;
429
+ const dependsOn = (definition as { dependsOn?: unknown } | null)?.dependsOn;
430
+ // `$TURBO_EXTENDS$` and turbo 1's `$ENV` entries name no task.
431
+ for (const dependency of Array.isArray(dependsOn) ? dependsOn : []) {
432
+ if (typeof dependency === "string" && !dependency.startsWith("$")) queue.push({ task: dependency.replace(/^\^/, ""), hops: [...hops, `${config.file} ${config.section}.${key}.dependsOn: ${dependency}`] });
433
+ }
434
+ }
435
+ }
436
+ }
437
+ const kind = found.test ? "test" : found.build ? "build" : null;
438
+ if (kind) context.findings.push({ kind, runner: text, chain: [...(chain.at(-1) === text ? chain : [...chain, text]), ...found[kind]!] });
439
+ }
440
+
211
441
  function bun(context: Context, args: string[], cwd: string, chain: string[], depth: number, text: string): void {
212
442
  const { rest, seen } = options(args, TOOLS.bun);
213
443
  const directory = directoryOption(cwd, seen);
214
444
  const sub = rest[0];
215
445
  if (!sub) return;
216
446
  if (sub === "test") report(context, "test", text, chain);
447
+ // The bundler is built in, so `bun build` never runs a package script of that name.
448
+ else if (sub === "build") report(context, "build", text, chain);
217
449
  else if (INSTALLS.bun.includes(sub)) report(context, "install", text, chain);
218
450
  else if (sub === "x") execute(context, rest.slice(1), directory, chain, depth);
219
451
  else if (sub === "exec") { if (rest[1]) visitShell(context, rest[1], directory, chain, depth + 1); }
@@ -228,25 +460,22 @@ function bun(context: Context, args: string[], cwd: string, chain: string[], dep
228
460
  else runScript(context, sub, rest.slice(1), directory, workspaceScoped(seen, TOOLS.bun), chain, depth, null);
229
461
  }
230
462
 
231
- /** npm reads its own options anywhere before `--`, so `npm run check --workspaces` selects workspaces. */
232
- function npmOptions(args: string[]): { rest: string[]; seen: Map<string, string | true> } {
463
+ /** Options read anywhere before `--`, as npm reads `npm run check --workspaces` and mise `mise x node@24 -C dir -- …`; returns the positional words, then `--` and what follows it. */
464
+ function scatteredOptions(args: string[], spec: Tool): { rest: string[]; seen: Map<string, string | true> } {
233
465
  const separator = args.indexOf("--");
234
466
  const before = separator === -1 ? args : args.slice(0, separator);
235
467
  const seen = new Map<string, string | true>(), positional: string[] = [];
236
468
  for (let index = 0; index < before.length; index++) {
237
469
  const value = before[index]!;
238
470
  if (!value.startsWith("-")) { positional.push(value); continue; }
239
- const equals = value.indexOf("=");
240
- if (equals > 0) seen.set(value.slice(0, equals), value.slice(equals + 1));
241
- else if (TOOLS.npm.values.has(value) && index + 1 < before.length) seen.set(value, before[++index]!);
242
- else seen.set(value, true);
471
+ for (const [name, found] of optionWords(value, spec.values, () => index + 1 < before.length ? before[++index] : undefined)) seen.set(name, found ?? true);
243
472
  }
244
473
  return { rest: separator === -1 ? positional : [...positional, ...args.slice(separator)], seen };
245
474
  }
246
475
 
247
476
  function packageManager(context: Context, manager: "npm" | "pnpm" | "yarn", args: string[], cwd: string, chain: string[], depth: number, text: string): void {
248
477
  const spec = TOOLS[manager];
249
- const { rest, seen } = manager === "npm" ? npmOptions(args) : options(args, spec);
478
+ const { rest, seen } = manager === "npm" ? scatteredOptions(args, spec) : options(args, spec);
250
479
  const directory = directoryOption(cwd, seen);
251
480
  const workspaces = workspaceScoped(seen, spec);
252
481
  const sub = rest[0];
@@ -269,6 +498,169 @@ function packageManager(context: Context, manager: "npm" | "pnpm" | "yarn", args
269
498
  else if (manager !== "npm") runScript(context, sub, rest.slice(1), directory, workspaces, chain, depth, rest);
270
499
  }
271
500
 
501
+ /** Options that take a separate value, for each Python runner and project manager, before and after its subcommand. */
502
+ const PYTHON_TOOLS = {
503
+ uv: tool([
504
+ "--directory", "--project", "--cache-dir", "--color", "--config-file", "--allow-insecure-host",
505
+ "-w", "--with", "--with-editable", "--with-requirements", "--from", "-c", "--constraints", "-b", "--build-constraints", "--overrides",
506
+ "--extra", "--no-extra", "--group", "--no-group", "--only-group", "--package", "--env-file", "-p", "--python", "--python-platform", "--torch-backend",
507
+ "--index", "--default-index", "-i", "--index-url", "--extra-index-url", "-f", "--find-links", "--index-strategy", "--keyring-provider",
508
+ "-P", "--upgrade-package", "--resolution", "--prerelease", "--fork-strategy", "--exclude-newer", "--exclude-newer-package", "--no-sources-package",
509
+ "--reinstall-package", "--link-mode", "-C", "--config-setting", "--config-settings-package", "--no-build-isolation-package", "--no-build-package",
510
+ "--no-binary-package", "--refresh-package",
511
+ // Hidden from `--help`, but they still take a value.
512
+ "--python-preference", "--preview-features", "--python-fetch", "--max-recursion-depth",
513
+ ]),
514
+ poetry: tool(["-C", "--directory", "-P", "--project"]),
515
+ // pdm takes `-p`, `--project`, and `--venv` only after its subcommand (`pdm -p api run` fails), but reading them before it too means a misplaced one never hides the command.
516
+ pdm: tool(["-c", "--config", "-p", "--project", "--venv"]),
517
+ pdmRun: tool(["-p", "--project", "-k", "--skip", "--venv", "--env", "--env-file", "--working-dir"]),
518
+ hatch: tool(["-e", "--env", "-p", "--project", "--data-dir", "--cache-dir", "--config"]),
519
+ hatchEnvRun: tool(["-e", "--env", "-i", "--include", "-x", "--exclude", "-f", "--filter"]),
520
+ pipenv: tool(["--python", "--pypi-mirror"]),
521
+ pipx: tool(["--python-args", "--with", "--spec", "--python", "--fetch-python", "--index-url", "--pip-args", "--cooldown", "--backend"]),
522
+ pip: tool(["--python", "--log", "--log-file", "--proxy", "--retries", "--resume-retries", "--timeout", "--exists-action", "--trusted-host", "--cert", "--client-cert", "--cache-dir", "--use-feature", "--use-deprecated", "--keyring-provider"]),
523
+ coverage: tool(["--rcfile", "--source", "--include", "--omit", "--context", "--concurrency", "--data-file", "--debug", "--save-signal"]),
524
+ } as const;
525
+ const MISE = tool(["-C", "--cd", "-E", "--env", "-j", "--jobs", "-c", "--command", "--allow-env", "--allow-net", "--allow-read", "--allow-write", "--secrets"]);
526
+ /** Subcommands that install a Python project's dependencies into its environment. */
527
+ const PYTHON_INSTALLS: Partial<Record<keyof typeof PYTHON_TOOLS, readonly string[]>> = {
528
+ uv: ["sync", "add", "remove"], poetry: ["install", "sync", "add", "remove", "update"], pdm: ["install", "sync", "add", "remove", "update"],
529
+ // `pipenv upgrade` only updates the lockfile; `pipenv update` also syncs.
530
+ pipenv: ["install", "sync", "update"],
531
+ };
532
+ /**
533
+ * A Python install that only previews or changes declarations and locks:
534
+ * `--dry-run`, `uv sync --check`, `uv add|remove` with `--no-sync` or
535
+ * `--frozen`, `pdm add|remove|update --no-sync`, or poetry's `--lock`. `pdm
536
+ * install --check` checks the lockfile and then installs.
537
+ */
538
+ function previews(tool: string, sub: string | undefined, args: string[]): boolean {
539
+ return args.some(arg => arg === "--dry-run"
540
+ || (tool === "uv" && sub === "sync" && arg === "--check")
541
+ || (tool === "uv" && (sub === "add" || sub === "remove") && (arg === "--no-sync" || arg === "--frozen"))
542
+ || (tool === "pdm" && (sub === "add" || sub === "remove" || sub === "update") && arg === "--no-sync")
543
+ || (tool === "poetry" && arg === "--lock"));
544
+ }
545
+ /** `uvx` and `pipx run` take a requirement for the command they run, such as `ruff==0.6`, `ruff>=0.6`, or `ruff[all]`; the command is its name. */
546
+ const requirement = ([first, ...rest]: string[]) => first === undefined ? [] : [first.replace(/^([A-Za-z0-9][\w.-]*)\s*(?:\[[^\]]*\])?\s*(?:[=<>!~].*)?$/s, "$1"), ...rest];
547
+
548
+ /** The directory a command runs in after options such as `--directory` or `-C`, applied in order. */
549
+ function movedTo(cwd: string, names: string[], ...seen: Map<string, string | true>[]): string {
550
+ let directory = cwd;
551
+ for (const options of seen) for (const name of names) { const value = options.get(name); if (typeof value === "string") directory = path.resolve(directory, value); }
552
+ return directory;
553
+ }
554
+
555
+ /**
556
+ * `uv run` syncs the project's environment before its command, even with
557
+ * `--frozen` or `--locked`, unless `--no-sync`, `--no-project`, or a script
558
+ * (`--script`, `--gui-script`) skips it; `-m` runs a module. `UV_NO_SYNC` is
559
+ * not read: whether a command sees a variable cannot be told from the step, so
560
+ * only the flag counts. `uvx` is `uv tool run`, whose cached tool environment, like `npx`'s
561
+ * download, is not counted as an install; neither are `--with` requirements.
562
+ */
563
+ function uv(context: Context, args: string[], cwd: string, chain: string[], depth: number, text: string): void {
564
+ const spec = PYTHON_TOOLS.uv;
565
+ const { rest, seen } = options(args, spec);
566
+ const sub = rest[0], words = rest.slice(1);
567
+ // uv reads its global options anywhere, so `uv tool --no-cache run` is `uv tool run`.
568
+ const tool = sub === "tool" ? options(words, spec) : { rest: [], seen: new Map<string, string | true>() };
569
+ if (sub === "run" || tool.rest[0] === "run") {
570
+ const run = scriptOptions(sub === "run" ? words : tool.rest.slice(1), spec);
571
+ const flags = new Set([...seen.keys(), ...tool.seen.keys(), ...run.seen.keys()]);
572
+ // Even without a command, `uv run` syncs before it lists what it could run.
573
+ if (sub === "run" && !["--no-sync", "--no-project", "-s", "--script", "--gui-script"].some(flag => flags.has(flag))) report(context, "install", text, chain);
574
+ if (!run.rest.length) return;
575
+ const module = sub === "run" && (run.seen.has("-m") || run.seen.has("--module"));
576
+ visit(context, module ? ["python", "-m", ...run.rest] : sub === "run" ? run.rest : requirement(run.rest), movedTo(cwd, ["--directory"], seen, tool.seen, run.seen), chain, depth + 1);
577
+ } else if ((PYTHON_INSTALLS.uv!.includes(sub ?? "") || (sub === "pip" && ["install", "sync"].includes(options(words, spec).rest[0] ?? ""))) && !previews("uv", sub, words)) report(context, "install", text, chain);
578
+ else if (sub === "build") report(context, "build", text, chain);
579
+ }
580
+
581
+ /**
582
+ * `poetry run`, `pdm run`, `pipenv run`, and `pipx run` run their command as
583
+ * given; `hatch run` and `hatch env run` first create and sync the
584
+ * environment, and `hatch run` takes leading `+`/`-` matrix selectors and an
585
+ * `env:` prefix. `poetry -C` moves the command; `pdm run` keeps its directory
586
+ * unless `--working-dir` names one, relative to the project root (`-p`, else
587
+ * the nearest `pyproject.toml`). Script names they look up in
588
+ * `pyproject.toml`, `hatch.toml`, or `Pipfile` are leaves.
589
+ */
590
+ function pythonProject(context: Context, name: "poetry" | "pdm" | "hatch" | "pipenv" | "pipx", args: string[], cwd: string, chain: string[], depth: number, text: string): void {
591
+ const spec = PYTHON_TOOLS[name];
592
+ const { rest, seen } = options(args, spec);
593
+ const sub = rest[0], words = rest.slice(1);
594
+ if (sub === "run" || (name === "hatch" && sub === "env" && words[0] === "run")) {
595
+ let run: { rest: string[]; seen: Map<string, string | true> };
596
+ if (name === "hatch" && sub === "run") {
597
+ let at = 0;
598
+ while (at < words.length && /^[+-]/.test(words[at]!) && words[at] !== "--") at++;
599
+ const command = words[at] === "--" ? words.slice(at + 1) : words.slice(at);
600
+ const prefix = command[0]?.indexOf(":") ?? -1;
601
+ run = { rest: prefix === -1 ? command : [command[0]!.slice(prefix + 1), ...command.slice(1)], seen: new Map() };
602
+ } else run = scriptOptions(sub === "run" ? words : words.slice(1), name === "hatch" ? PYTHON_TOOLS.hatchEnvRun : name === "pdm" ? PYTHON_TOOLS.pdmRun : spec);
603
+ if (!run.rest.length) return;
604
+ if (name === "hatch") report(context, "install", text, chain);
605
+ let directory = movedTo(cwd, name === "poetry" ? ["-C", "--directory"] : [], seen, run.seen);
606
+ const working = name === "pdm" ? run.seen.get("--working-dir") : undefined;
607
+ if (typeof working === "string") {
608
+ const project = run.seen.get("--project") ?? run.seen.get("-p") ?? seen.get("--project") ?? seen.get("-p");
609
+ directory = path.resolve(typeof project === "string" ? path.resolve(cwd, project) : packageRoot(context, cwd, "pyproject.toml"), working);
610
+ }
611
+ visit(context, name === "pipx" ? requirement(run.rest) : run.rest, directory, chain, depth + 1);
612
+ } else if (PYTHON_INSTALLS[name]?.includes(sub ?? "")) { if (!previews(name, sub, words)) report(context, "install", text, chain); }
613
+ else if (sub === "build" && name !== "pipenv" && name !== "pipx") report(context, "build", text, chain);
614
+ else if (name === "hatch" && sub === "test") report(context, "test", text, chain);
615
+ }
616
+
617
+ /**
618
+ * `python [options] -m <module> [args]` runs the module as its command would:
619
+ * `-m pytest` is a test run and `-m pip install` an install. `-m unittest`
620
+ * tests and `-m build` builds. Code (`-c`), standard input, and script files
621
+ * are leaves.
622
+ */
623
+ function python(context: Context, args: string[], cwd: string, chain: string[], depth: number, text: string): void {
624
+ for (let index = 0; index < args.length; index++) {
625
+ const word = args[index]!;
626
+ if (word === "--check-hash-based-pycs") { index++; continue; }
627
+ // A script file, `-` for standard input, or a long option such as `--version`.
628
+ if (!/^-[^-]/.test(word)) return;
629
+ for (let at = 1; at < word.length; at++) {
630
+ const flag = word[at]!;
631
+ if (!"cmWX".includes(flag)) continue;
632
+ // An option that takes a value takes the rest of its word, else the next word.
633
+ const value = at + 1 < word.length ? word.slice(at + 1) : args[++index];
634
+ if (flag === "c" || value === undefined) return;
635
+ if (flag === "m") {
636
+ if (value === "build") report(context, "build", text, chain);
637
+ else if (value === "unittest") report(context, "test", text, chain);
638
+ else visit(context, [value, ...args.slice(index + 1)], cwd, chain, depth + 1);
639
+ return;
640
+ }
641
+ break;
642
+ }
643
+ }
644
+ }
645
+
646
+ /** `coverage run -m <module>` runs the module as `python -m` does; a program file is a leaf. */
647
+ function coverageRun(context: Context, args: string[], cwd: string, chain: string[], depth: number, text: string): void {
648
+ const { rest, seen } = options(args, PYTHON_TOOLS.coverage);
649
+ if ((seen.has("-m") || seen.has("--module")) && rest.length) python(context, ["-m", ...rest], cwd, chain, depth, text);
650
+ }
651
+
652
+ /** `mise exec|x [tool@version...] -- <command>` runs its command, and `-c` a shell string, in the directory `-C` names. */
653
+ function mise(context: Context, args: string[], cwd: string, chain: string[], depth: number): void {
654
+ const { rest, seen } = options(args, MISE);
655
+ if (rest[0] !== "exec" && rest[0] !== "x") return;
656
+ const exec = scatteredOptions(rest.slice(1), MISE);
657
+ const directory = movedTo(cwd, ["-C", "--cd"], seen, exec.seen);
658
+ const call = exec.seen.get("-c") ?? exec.seen.get("--command");
659
+ if (typeof call === "string") visitShell(context, call, directory, chain, depth + 1);
660
+ const separator = exec.rest.indexOf("--");
661
+ if (separator !== -1 && separator + 1 < exec.rest.length) visit(context, exec.rest.slice(separator + 1), directory, chain, depth + 1);
662
+ }
663
+
272
664
  /** The checkout holding `directory`: this repository's root when it is inside it, else the nearest directory with a `.git`. */
273
665
  function checkoutOf(context: Context, directory: string): string {
274
666
  if (directory === context.root || directory.startsWith(`${context.root}${path.sep}`)) {