@a2f0/agent-tool 0.1.57 → 0.1.59

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.
@@ -0,0 +1,552 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { packageDirectories } from "../system/workspace";
4
+
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
+ export interface StepResolution { findings: StepFinding[]; errors: string[] }
8
+
9
+ const MAX_DEPTH = 32;
10
+ const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh"]);
11
+ const WRAPPERS = new Set(["exec", "command", "time", "nohup", "nice"]);
12
+ const KEYWORDS = new Set(["if", "then", "else", "elif", "do", "while", "until", "!", "{", "}", "fi", "done", "esac"]);
13
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
14
+
15
+ /** Per tool: options that take a separate value (`--name=value` needs no entry) and options that select workspaces. */
16
+ interface Tool { values: Set<string>; workspaces: Set<string> }
17
+ const tool = (values: string[], workspaces: string[] = []): Tool => ({ values: new Set(values), workspaces: new Set(workspaces) });
18
+ const TOOLS = {
19
+ bun: tool(["--cwd", "--filter", "-F", "--env-file", "--preload", "-r", "--config", "-c", "--shell", "--elide-lines"], ["--filter", "-F", "--workspaces"]),
20
+ npm: tool(["--prefix", "--workspace", "-w", "--registry", "--cache", "--userconfig", "-c", "--call", "-p", "--package"], ["--workspace", "-w", "--workspaces", "-ws"]),
21
+ pnpm: tool(["-C", "--dir", "--filter", "-F", "--reporter"], ["--filter", "-F", "--recursive", "-r"]),
22
+ yarn: tool(["--cwd"]),
23
+ 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", "--cwd", "--root-turbo-json", "--heap", "--team", "--token", "--api", "--login", "--trace", "--cpuprofile", "--remote-cache-timeout", "--cache-workers", "--pkg-inference-root"]),
25
+ } as const;
26
+ const INSTALLS: Record<"bun" | "npm" | "pnpm" | "yarn", string[]> = {
27
+ bun: ["install", "i", "add", "a", "update", "remove", "rm"],
28
+ npm: ["install", "i", "in", "ins", "inst", "insta", "instal", "isnt", "isnta", "isntal", "isntall", "add", "ci", "clean-install", "ic", "install-clean", "isntall-clean", "update", "up", "upgrade", "install-test", "it", "install-ci-test", "cit"],
29
+ pnpm: ["install", "i", "add", "update", "up", "upgrade", "install-test", "it"],
30
+ yarn: ["install", "add", "up", "upgrade", "upgrade-interactive"],
31
+ };
32
+
33
+ interface Context { root: string; seen: Set<string>; findings: StepFinding[]; errors: string[] }
34
+
35
+ /**
36
+ * Follow a declared push-gate step through package scripts, shell strings,
37
+ * and `agent-tool run-group` plans to every test runner, build, or dependency
38
+ * install it reaches. Executables and script files are leaves: their contents
39
+ * are not inspected. Workspace filters resolve to every workspace package
40
+ * declaring the script, which can over-report but never misses one. A command
41
+ * that both builds and tests, such as `cargo test`, is reported once, as a test.
42
+ */
43
+ export function resolveStep(root: string, command: string[]): StepResolution {
44
+ const context: Context = { root, seen: new Set(), findings: [], errors: [] };
45
+ visit(context, command, root, [display(command)], 0);
46
+ return { findings: context.findings, errors: context.errors };
47
+ }
48
+
49
+ export function display(argv: string[]): string { return argv.map(arg => /^[\w@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replaceAll("'", "'\\''")}'`).join(" "); }
50
+ function report(context: Context, kind: StepFinding["kind"], runner: string, chain: string[]): void {
51
+ context.findings.push({ kind, runner, chain: chain.at(-1) === runner ? chain : [...chain, runner] });
52
+ }
53
+
54
+ /** Skip leading options, consuming the separate value of the ones that take one; returns the options seen. */
55
+ function options(argv: string[], spec: Tool): { rest: string[]; seen: Map<string, string | true> } {
56
+ const seen = new Map<string, string | true>();
57
+ let index = 0;
58
+ while (index < argv.length && argv[index]!.startsWith("-") && argv[index] !== "--") {
59
+ const value = argv[index]!;
60
+ const equals = value.indexOf("=");
61
+ if (equals > 0) seen.set(value.slice(0, equals), value.slice(equals + 1));
62
+ else if (spec.values.has(value) && index + 1 < argv.length) { seen.set(value, argv[index + 1]!); index++; }
63
+ else seen.set(value, true);
64
+ index++;
65
+ }
66
+ return { rest: argv.slice(index), seen };
67
+ }
68
+
69
+ /** `npx`, `bunx`, `bun x`, and `<manager> exec|dlx`: a command after an optional `--`, or a shell string given to `--call`. */
70
+ function execute(context: Context, args: string[], cwd: string, chain: string[], depth: number): void {
71
+ const { rest, seen } = options(args, TOOLS.exec);
72
+ const call = seen.get("--call") ?? seen.get("-c");
73
+ if (typeof call === "string") visitShell(context, call, cwd, chain, depth + 1);
74
+ const command = rest[0] === "--" ? rest.slice(1) : rest;
75
+ if (command.length) visit(context, command, cwd, chain, depth + 1);
76
+ }
77
+
78
+ /** `run [options] [--] <script> [args]`: a `--` before the script name only ends the manager's options. */
79
+ function scriptOptions(args: string[], spec: Tool): { rest: string[]; seen: Map<string, string | true> } {
80
+ const parsed = options(args, spec);
81
+ return parsed.rest[0] === "--" ? { rest: parsed.rest.slice(1), seen: parsed.seen } : parsed;
82
+ }
83
+
84
+ function directoryOption(cwd: string, seen: Map<string, string | true>): string {
85
+ for (const name of ["--cwd", "--prefix", "-C", "--dir"]) { const value = seen.get(name); if (typeof value === "string") return path.resolve(cwd, value); }
86
+ return cwd;
87
+ }
88
+ const workspaceScoped = (seen: Map<string, string | true>, spec: Tool) => [...seen.keys()].some(name => spec.workspaces.has(name));
89
+
90
+ function scripts(directory: string): Record<string, unknown> | null {
91
+ const file = path.join(directory, "package.json");
92
+ if (!existsSync(file)) return null;
93
+ try {
94
+ const value = JSON.parse(readFileSync(file, "utf8")) as { scripts?: unknown };
95
+ return value.scripts && typeof value.scripts === "object" && !Array.isArray(value.scripts) ? value.scripts as Record<string, unknown> : {};
96
+ } catch { return null; }
97
+ }
98
+
99
+ /**
100
+ * Run a package script as its manager would: `pre<name>`, the script with its
101
+ * arguments appended, then `post<name>`. An unknown name runs `fallback`, the
102
+ * executable or file of that name, when the manager does so.
103
+ */
104
+ /** Workspace packages of the workspace rooted at `root` (the repository's by default), from `package.json` workspaces and pnpm's `pnpm-workspace.yaml`. */
105
+ function workspaceDirectories(context: Context, root = context.root): string[] {
106
+ const directories = new Set(packageDirectories(root));
107
+ const file = path.join(root, "pnpm-workspace.yaml");
108
+ if (!existsSync(file)) return [...directories];
109
+ let patterns: unknown;
110
+ try { patterns = (Bun.YAML.parse(readFileSync(file, "utf8")) as { packages?: unknown } | null)?.packages; }
111
+ catch (error) { context.errors.push(`Cannot read ${path.relative(context.root, file) || file}: ${(error as Error).message}`); return [...directories]; }
112
+ const list = (Array.isArray(patterns) ? patterns : []).filter((pattern): pattern is string => typeof pattern === "string");
113
+ const excluded = list.filter(pattern => pattern.startsWith("!")).map(pattern => new Bun.Glob(pattern.slice(1).replace(/\/$/, "")));
114
+ for (const pattern of list.filter(pattern => !pattern.startsWith("!"))) {
115
+ for (const match of new Bun.Glob(`${pattern.replace(/\/$/, "")}/package.json`).scanSync({ cwd: root, onlyFiles: true })) {
116
+ const relative = path.dirname(match);
117
+ if (!match.split("/").includes("node_modules") && !excluded.some(glob => glob.match(relative))) directories.add(path.join(root, relative));
118
+ }
119
+ }
120
+ return [...directories];
121
+ }
122
+
123
+ /** Package managers run scripts from the nearest `package.json` at or above the directory, within the repository. */
124
+ function packageRoot(context: Context, directory: string): string {
125
+ let current = directory;
126
+ while (!existsSync(path.join(current, "package.json")) && current !== context.root && current.startsWith(`${context.root}${path.sep}`)) current = path.dirname(current);
127
+ return current;
128
+ }
129
+
130
+ function runScript(context: Context, name: string, args: string[], directory: string, workspaces: boolean, chain: string[], depth: number, fallback: string[] | null): void {
131
+ const directories = workspaces ? workspaceDirectories(context).filter(dir => typeof scripts(dir)?.[name] === "string") : [packageRoot(context, directory)];
132
+ let found = false;
133
+ for (const dir of directories) {
134
+ const table = scripts(dir);
135
+ for (const script of [`pre${name}`, name, `post${name}`]) {
136
+ const body = table?.[script];
137
+ if (typeof body !== "string") continue;
138
+ if (script === name) found = true;
139
+ const key = `${dir}\0${script}`;
140
+ if (context.seen.has(key)) continue;
141
+ const manifest = path.relative(context.root, path.join(dir, "package.json")) || "package.json";
142
+ const text = script === name && args.length ? `${body} ${display(args)}` : body;
143
+ context.seen.add(key);
144
+ visitShell(context, text, dir, [...chain, `${manifest} scripts.${script}: ${text}`], depth + 1);
145
+ context.seen.delete(key);
146
+ }
147
+ }
148
+ if (!found && fallback) visit(context, fallback, directory, chain, depth + 1);
149
+ }
150
+
151
+ function visit(context: Context, input: string[], cwd: string, chain: string[], depth: number): void {
152
+ if (depth > MAX_DEPTH) { context.errors.push(`Resolution deeper than ${MAX_DEPTH} levels: ${chain.join(" -> ")}`); return; }
153
+ const argv = [...input];
154
+ while (argv.length && (ASSIGNMENT.test(argv[0]!) || WRAPPERS.has(argv[0]!))) argv.shift();
155
+ if (argv[0] === "env") { argv.shift(); while (argv.length && (argv[0]!.startsWith("-") || ASSIGNMENT.test(argv[0]!))) argv.shift(); }
156
+ if (!argv.length) return;
157
+ // `npx vitest@4` names the runner with a version selector.
158
+ const name = path.basename(argv[0]!).replace(/(?<=.)@[^@/]*$/, "");
159
+ const args = argv.slice(1);
160
+ const text = display(argv);
161
+ if (SHELLS.has(name)) {
162
+ const flagIndex = args.findIndex(arg => /^-[a-z]*c[a-z]*$/.test(arg));
163
+ if (flagIndex !== -1 && args[flagIndex + 1] !== undefined) visitShell(context, args[flagIndex + 1]!, cwd, chain, depth + 1);
164
+ } else if (name === "agent-tool" || ((name === "bun" || name === "node") && /(?:^|\/)agent-tool\/src\/index\.ts$/.test(args[0] ?? ""))) {
165
+ agentTool(context, name === "agent-tool" ? args : args.slice(1), cwd, chain, depth);
166
+ } else if (name === "bun") bun(context, args, cwd, chain, depth, text);
167
+ else if (name === "bunx" || name === "npx") execute(context, args, cwd, chain, depth);
168
+ else if (name === "npm" || name === "pnpm" || name === "yarn") packageManager(context, name, args, cwd, chain, depth, text);
169
+ else if (name === "turbo") turbo(context, args, cwd, chain, text);
170
+ else if (testRunner(name, args)) report(context, "test", text, chain);
171
+ else if (builds(name, args)) report(context, "build", text, chain);
172
+ else if (["pod", "bundle", "pip", "pip3"].includes(name) && args[0] === "install") report(context, "install", text, chain);
173
+ else if (name === "bundle" && args[0] === "exec") visit(context, args.slice(1), cwd, chain, depth + 1);
174
+ }
175
+
176
+ /* Options, per tool, that take a separate value, so `--profile release` or `-x build` is never read as a subcommand or task. */
177
+ 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"]);
178
+ 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"]);
179
+ 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"]);
180
+ 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"]);
181
+ const RUNNER_VALUES: Record<string, ReadonlySet<string>> = {
182
+ go: new Set(["-C"]), cargo: new Set(["-C", "--config", "-Z", "--color"]), deno: new Set(["--config", "-c"]), swift: new Set(["--package-path"]),
183
+ vite: new Set(["-c", "--config", "--base", "-l", "--logLevel", "-m", "--mode", "--configLoader", "-f", "--filter"]),
184
+ astro: new Set(["--root", "--config", "--site", "--base", "--mode"]),
185
+ webpack: WEBPACK_VALUES, "webpack-cli": WEBPACK_VALUES, docker: DOCKER_VALUES, "docker-compose": DOCKER_VALUES,
186
+ };
187
+
188
+ /** The positional words before any `--`, skipping options and the separate values of those in `takesValue`. */
189
+ function positionals(args: string[], takesValue: ReadonlySet<string>): string[] {
190
+ const words: string[] = [];
191
+ for (let index = 0; index < args.length; index++) {
192
+ const value = args[index]!;
193
+ if (value === "--") break;
194
+ if (value.startsWith("-")) { if (takesValue.has(value)) index++; continue; }
195
+ words.push(value);
196
+ }
197
+ return words;
198
+ }
199
+
200
+ /** The first positional word, after global options such as `go -C dir` or `cargo +nightly -Z flag`. */
201
+ function subcommand(name: string, args: string[]): string | undefined {
202
+ const takesValue = RUNNER_VALUES[name] ?? new Set();
203
+ for (let index = 0; index < args.length; index++) {
204
+ const value = args[index]!;
205
+ if (takesValue.has(value)) { index++; continue; }
206
+ if (value.startsWith("-") || (name === "cargo" && value.startsWith("+"))) continue;
207
+ return value;
208
+ }
209
+ return undefined;
210
+ }
211
+
212
+ /** xcodebuild's actions: positional words other than `NAME=value` build settings. */
213
+ const xcodebuildActions = (args: string[]) => positionals(args, XCODEBUILD_VALUES).filter(word => !word.includes("="));
214
+ /** Gradle task paths such as `test` or `:app:testDebugUnitTest`. */
215
+ const gradleTask = (pattern: string) => new RegExp(`^(?::?[\\w-]+:)*(?:${pattern})$`, "i");
216
+ const GRADLE_TEST = gradleTask("test\\w*");
217
+ const GRADLE_BUILD = gradleTask("assemble\\w*|build(?:Needed|Dependents)?|bundle\\w*|install\\w*");
218
+
219
+ function testRunner(name: string, args: string[]): boolean {
220
+ if (["jest", "vitest", "mocha", "ava", "maestro", "detox", "pytest", "rspec"].includes(name)) return true;
221
+ const first = subcommand(name, args);
222
+ if (name === "node") return args.some(arg => arg === "--test" || arg.startsWith("--test="));
223
+ if (["playwright", "deno", "go", "swift"].includes(name)) return first === "test";
224
+ if (name === "cargo") return first === "test" || first === "nextest";
225
+ if (name === "gradle" || name === "gradlew") return positionals(args, GRADLE_VALUES).some(task => GRADLE_TEST.test(task));
226
+ if (name === "xcodebuild") return xcodebuildActions(args).some(action => action === "test" || action === "test-without-building");
227
+ if (/^python[\d.]*$/.test(name)) return args[0] === "-m" && args[1] === "pytest";
228
+ return false;
229
+ }
230
+
231
+ /** webpack-cli subcommands that serve, inspect, or scaffold instead of bundling; any other first word is a build or an entry. */
232
+ 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"]);
233
+ /** xcodebuild options that only list, report, export, or resolve; without one, xcodebuild builds (its default action). */
234
+ 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"]);
235
+
236
+ /**
237
+ * Bundlers, framework builds, native compilers, and image builds. Static
238
+ * checks are not builds: `tsc` (whether `--noEmit` or `-b`), `cargo
239
+ * check|clippy|fmt`, linters, and formatters.
240
+ */
241
+ function builds(name: string, args: string[]): boolean {
242
+ if (name === "rollup" || name === "tsup") return true;
243
+ if (name === "esbuild") return args.some(arg => arg === "--bundle" || /^--out(?:file|dir)(?:=|$)/.test(arg));
244
+ const first = subcommand(name, args);
245
+ if (name === "webpack" || name === "webpack-cli") return !WEBPACK_OTHER.has(first ?? "");
246
+ if (["vite", "next", "astro", "electrobun", "swift", "go"].includes(name)) return first === "build";
247
+ if (name === "cargo") return ["build", "b", "run", "r"].includes(first ?? "");
248
+ // `expo run:ios|android` compiles the native app before launching it.
249
+ if (name === "expo") return first === "export" || /^(?:export|run):/.test(first ?? "");
250
+ if (name === "gradle" || name === "gradlew") return positionals(args, GRADLE_VALUES).some(task => GRADLE_BUILD.test(task));
251
+ if (name === "xcodebuild") {
252
+ if (args.some(arg => XCODEBUILD_OTHER.has(arg))) return false;
253
+ const actions = xcodebuildActions(args);
254
+ // Without an action, xcodebuild builds.
255
+ return !actions.length || actions.some(action => action !== "clean" && action !== "installsrc");
256
+ }
257
+ if (name === "docker-compose") return first === "build";
258
+ if (name === "docker") {
259
+ const [command, sub] = positionals(args, DOCKER_VALUES);
260
+ return command === "build" || ((command === "image" || command === "builder" || command === "compose") && sub === "build") || (command === "buildx" && ["build", "b", "bake"].includes(sub ?? ""));
261
+ }
262
+ return false;
263
+ }
264
+
265
+ /** turbo's subcommands that run no tasks. */
266
+ const TURBO_COMMANDS = new Set(["prune", "ls", "info", "query", "gen", "generate", "login", "logout", "link", "unlink", "daemon", "telemetry", "bin", "completion", "scan", "boundaries", "devtools", "docs", "config"]);
267
+
268
+ /** The tasks a `turbo` command runs: those after `run` or `watch`, or bare task names. */
269
+ function turboTasks(args: string[]): string[] {
270
+ const words = positionals(args, TOOLS.turbo.values);
271
+ if (words[0] === "run" || words[0] === "watch") return words.slice(1);
272
+ return TURBO_COMMANDS.has(words[0] ?? "") ? [] : words;
273
+ }
274
+
275
+ /** The value of `--name value` or `--name=value` before any `--`. */
276
+ function optionValue(args: string[], name: string): string | undefined {
277
+ for (let index = 0; index < args.length && args[index] !== "--"; index++) {
278
+ const value = args[index]!;
279
+ if (value === name) return args[index + 1];
280
+ if (value.startsWith(`${name}=`)) return value.slice(name.length + 1);
281
+ }
282
+ return undefined;
283
+ }
284
+
285
+ interface TurboConfig { file: string; section: string; tasks: Record<string, unknown>; extends: boolean }
286
+
287
+ function readTurboConfig(context: Context, file: string): TurboConfig | null {
288
+ const relative = path.relative(context.root, file) || file;
289
+ try {
290
+ const value: unknown = Bun.JSONC.parse(readFileSync(file, "utf8"));
291
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("expected an object");
292
+ // turbo 2 names the section `tasks`; turbo 1 named it `pipeline`.
293
+ const section = "tasks" in value ? "tasks" : "pipeline";
294
+ const tasks = (value as Record<string, unknown>)[section] ?? {};
295
+ if (!tasks || typeof tasks !== "object" || Array.isArray(tasks)) throw new Error(`expected ${section} to be an object`);
296
+ return { file: relative, section, tasks: tasks as Record<string, unknown>, extends: "extends" in value };
297
+ } catch (error) { context.errors.push(`Cannot read ${relative}: ${(error as Error).message}`); return null; }
298
+ }
299
+
300
+ function declaresWorkspaces(directory: string): boolean {
301
+ if (existsSync(path.join(directory, "pnpm-workspace.yaml"))) return true;
302
+ try { return (JSON.parse(readFileSync(path.join(directory, "package.json"), "utf8")) as { workspaces?: unknown }).workspaces !== undefined; } catch { return false; }
303
+ }
304
+
305
+ const turboFile = (directory: string) => ["turbo.json", "turbo.jsonc"].map(name => path.join(directory, name)).find(file => existsSync(file));
306
+
307
+ /**
308
+ * Every turbo configuration that can define a task: the root one, then each
309
+ * workspace package's. The root one is `--root-turbo-json` when given (read
310
+ * from the directory turbo starts in and from the repository root, wherever it
311
+ * exists), else the nearest at or above the directory turbo starts in
312
+ * (`--cwd`) without `extends`.
313
+ */
314
+ function turboConfigs(context: Context, args: string[], cwd: string): TurboConfig[] {
315
+ const loaded = new Map<string, TurboConfig | null>();
316
+ const load = (file: string) => { if (!loaded.has(file)) loaded.set(file, readTurboConfig(context, file)); return loaded.get(file)!; };
317
+ const start = path.resolve(cwd, optionValue(args, "--cwd") ?? ".");
318
+ const explicit = optionValue(args, "--root-turbo-json");
319
+ const roots: string[] = [];
320
+ if (explicit !== undefined) {
321
+ roots.push(...new Set([path.resolve(start, explicit), path.resolve(context.root, explicit)].filter(file => existsSync(file))));
322
+ if (!roots.length) context.errors.push(`Cannot read ${explicit} (--root-turbo-json): no such file.`);
323
+ } else for (let current = start; ; current = path.dirname(current)) {
324
+ const file = turboFile(current);
325
+ if (file && load(file) && !load(file)!.extends) { roots.push(file); break; }
326
+ if (current === context.root || !current.startsWith(`${context.root}${path.sep}`)) break;
327
+ }
328
+ // Packages come from the workspace turbo runs in, the nearest at or above where it starts that declares
329
+ // workspaces, and from the repository's. A workspace root is a workspace directory too, but its
330
+ // turbo.json is a root configuration, not a package's.
331
+ const workspaceRoots = new Set([context.root]);
332
+ for (let current = start; current.startsWith(`${context.root}${path.sep}`); current = path.dirname(current)) {
333
+ if (declaresWorkspaces(current)) { workspaceRoots.add(current); break; }
334
+ }
335
+ const packages = [...workspaceRoots].flatMap(root => workspaceDirectories(context, root).filter(directory => !workspaceRoots.has(directory))).flatMap(directory => turboFile(directory) ?? []);
336
+ return [...new Set([...roots, ...packages])].flatMap(file => load(file) ?? []);
337
+ }
338
+
339
+ /**
340
+ * `turbo run <task...>` runs its tasks and, unless `--only`, every task they
341
+ * depend on in turbo.json: `^name`, `name`, and `package#name` all run tasks
342
+ * named `name`. A dependency's definitions in the root and every package
343
+ * configuration are followed together, which can over-report but never misses
344
+ * one. The package scripts turbo runs for each task are not followed.
345
+ */
346
+ function turbo(context: Context, args: string[], cwd: string, chain: string[], text: string): void {
347
+ const queue = turboTasks(args).map(task => ({ task, hops: [] as string[] }));
348
+ if (!queue.length) return;
349
+ const separator = args.indexOf("--");
350
+ const configs = (separator === -1 ? args : args.slice(0, separator)).includes("--only") ? [] : turboConfigs(context, args, cwd);
351
+ const found: Partial<Record<"test" | "build", string[]>> = {};
352
+ const seen = new Set<string>();
353
+ while (queue.length) {
354
+ const { task, hops } = queue.shift()!;
355
+ const name = task.slice(task.lastIndexOf("#") + 1);
356
+ if (seen.has(name)) continue;
357
+ seen.add(name);
358
+ if (/^test/.test(name)) found.test ??= hops;
359
+ else if (/^build/.test(name)) found.build ??= hops;
360
+ for (const config of configs) {
361
+ for (const [key, definition] of Object.entries(config.tasks)) {
362
+ if (key.slice(key.lastIndexOf("#") + 1) !== name) continue;
363
+ const dependsOn = (definition as { dependsOn?: unknown } | null)?.dependsOn;
364
+ // `$TURBO_EXTENDS$` and turbo 1's `$ENV` entries name no task.
365
+ for (const dependency of Array.isArray(dependsOn) ? dependsOn : []) {
366
+ if (typeof dependency === "string" && !dependency.startsWith("$")) queue.push({ task: dependency.replace(/^\^/, ""), hops: [...hops, `${config.file} ${config.section}.${key}.dependsOn: ${dependency}`] });
367
+ }
368
+ }
369
+ }
370
+ }
371
+ const kind = found.test ? "test" : found.build ? "build" : null;
372
+ if (kind) context.findings.push({ kind, runner: text, chain: [...(chain.at(-1) === text ? chain : [...chain, text]), ...found[kind]!] });
373
+ }
374
+
375
+ function bun(context: Context, args: string[], cwd: string, chain: string[], depth: number, text: string): void {
376
+ const { rest, seen } = options(args, TOOLS.bun);
377
+ const directory = directoryOption(cwd, seen);
378
+ const sub = rest[0];
379
+ if (!sub) return;
380
+ if (sub === "test") report(context, "test", text, chain);
381
+ // The bundler is built in, so `bun build` never runs a package script of that name.
382
+ else if (sub === "build") report(context, "build", text, chain);
383
+ else if (INSTALLS.bun.includes(sub)) report(context, "install", text, chain);
384
+ else if (sub === "x") execute(context, rest.slice(1), directory, chain, depth);
385
+ else if (sub === "exec") { if (rest[1]) visitShell(context, rest[1], directory, chain, depth + 1); }
386
+ else if (sub === "run") {
387
+ const run = scriptOptions(rest.slice(1), TOOLS.bun);
388
+ const target = run.rest[0];
389
+ // Only a leading `--` separates the script's arguments; later ones belong to the script.
390
+ const forwarded = run.rest.slice(1);
391
+ if (target) runScript(context, target, forwarded[0] === "--" ? forwarded.slice(1) : forwarded, directoryOption(directory, run.seen), workspaceScoped(seen, TOOLS.bun) || workspaceScoped(run.seen, TOOLS.bun), chain, depth, run.rest);
392
+ }
393
+ // `bun <name>` runs a package script of that name, else a file or built-in.
394
+ else runScript(context, sub, rest.slice(1), directory, workspaceScoped(seen, TOOLS.bun), chain, depth, null);
395
+ }
396
+
397
+ /** npm reads its own options anywhere before `--`, so `npm run check --workspaces` selects workspaces. */
398
+ function npmOptions(args: string[]): { rest: string[]; seen: Map<string, string | true> } {
399
+ const separator = args.indexOf("--");
400
+ const before = separator === -1 ? args : args.slice(0, separator);
401
+ const seen = new Map<string, string | true>(), positional: string[] = [];
402
+ for (let index = 0; index < before.length; index++) {
403
+ const value = before[index]!;
404
+ if (!value.startsWith("-")) { positional.push(value); continue; }
405
+ const equals = value.indexOf("=");
406
+ if (equals > 0) seen.set(value.slice(0, equals), value.slice(equals + 1));
407
+ else if (TOOLS.npm.values.has(value) && index + 1 < before.length) seen.set(value, before[++index]!);
408
+ else seen.set(value, true);
409
+ }
410
+ return { rest: separator === -1 ? positional : [...positional, ...args.slice(separator)], seen };
411
+ }
412
+
413
+ function packageManager(context: Context, manager: "npm" | "pnpm" | "yarn", args: string[], cwd: string, chain: string[], depth: number, text: string): void {
414
+ const spec = TOOLS[manager];
415
+ const { rest, seen } = manager === "npm" ? npmOptions(args) : options(args, spec);
416
+ const directory = directoryOption(cwd, seen);
417
+ const workspaces = workspaceScoped(seen, spec);
418
+ const sub = rest[0];
419
+ // Arguments after `--` reach the script; the manager drops the separator itself.
420
+ const scriptArgs = (values: string[]) => { const at = values.indexOf("--"); return at === -1 ? values : [...values.slice(0, at), ...values.slice(at + 1)]; };
421
+ if (!sub) { if (manager === "yarn") report(context, "install", text, chain); }
422
+ else if (INSTALLS[manager].includes(sub)) report(context, "install", text, chain);
423
+ else if (["run", "run-script", "rum", "urn"].includes(sub)) {
424
+ const run = scriptOptions(rest.slice(1), spec);
425
+ if (run.rest[0]) runScript(context, run.rest[0], scriptArgs(run.rest.slice(1)), directoryOption(directory, run.seen), workspaces || workspaceScoped(run.seen, spec), chain, depth, manager === "npm" ? null : run.rest);
426
+ } else if (["test", "t", "tst", "start", "stop", "restart"].includes(sub)) {
427
+ runScript(context, ["t", "tst"].includes(sub) ? "test" : sub, scriptArgs(rest.slice(1)), directory, workspaces, chain, depth, null);
428
+ } else if (["exec", "x", "dlx"].includes(sub)) {
429
+ // npm has already read `--call` wherever it appeared.
430
+ const call = seen.get("--call") ?? seen.get("-c");
431
+ if (manager === "npm" && typeof call === "string") visitShell(context, call, directory, chain, depth + 1);
432
+ execute(context, rest.slice(1), directory, chain, depth);
433
+ }
434
+ // pnpm and yarn run a script by its bare name, else an installed executable of that name.
435
+ else if (manager !== "npm") runScript(context, sub, rest.slice(1), directory, workspaces, chain, depth, rest);
436
+ }
437
+
438
+ /** The checkout holding `directory`: this repository's root when it is inside it, else the nearest directory with a `.git`. */
439
+ function checkoutOf(context: Context, directory: string): string {
440
+ if (directory === context.root || directory.startsWith(`${context.root}${path.sep}`)) {
441
+ for (let current = directory; current !== context.root; current = path.dirname(current)) if (existsSync(path.join(current, ".git"))) return current;
442
+ return context.root;
443
+ }
444
+ for (let current = directory; current !== path.dirname(current); current = path.dirname(current)) if (existsSync(path.join(current, ".git"))) return current;
445
+ return directory;
446
+ }
447
+
448
+ function agentTool(context: Context, input: string[], invokedIn: string, chain: string[], depth: number): void {
449
+ const args = [...input];
450
+ // `--repo` moves the command, and the run-group plans it resolves, to that checkout.
451
+ let cwd = invokedIn, repo: string | null = null;
452
+ while (args[0] === "--repo" || args[0] === "--config") { if (args[0] === "--repo" && args[1]) { cwd = path.resolve(cwd, args[1]); repo = cwd; } args.splice(0, 2); }
453
+ const text = display(["agent-tool", ...args]);
454
+ if (args[0] === "run-group" && args[1]) {
455
+ // Like the CLI, resolve the plan and run its steps from the root of the checkout `--repo` names.
456
+ const checkout = repo ? checkoutOf(context, repo) : context.root;
457
+ const plan = path.resolve(checkout, args[1]);
458
+ const relative = path.relative(context.root, plan);
459
+ let steps: { label: string; command: string[] }[];
460
+ try {
461
+ const value = JSON.parse(readFileSync(plan, "utf8")) as { steps?: unknown };
462
+ const valid = (step: unknown): step is { label: string; command: string[] } => !!step && typeof (step as { label?: unknown }).label === "string" && Array.isArray((step as { command?: unknown }).command) && ((step as { command: unknown[] }).command).every(arg => typeof arg === "string");
463
+ if (!Array.isArray(value.steps) || !value.steps.every(valid)) throw new Error("expected steps with a label and command");
464
+ steps = value.steps;
465
+ } catch (error) { context.errors.push(`Cannot read run-group plan ${relative} (${chain.join(" -> ")}): ${(error as Error).message}`); return; }
466
+ for (const step of steps) visit(context, step.command, checkout, [...chain, `${relative} step ${step.label}: ${display(step.command)}`], depth + 1);
467
+ } else if (args[0] === "run") {
468
+ const separator = args.indexOf("--");
469
+ if (separator !== -1) visit(context, args.slice(separator + 1), cwd, chain, depth + 1);
470
+ } else if (args[0] === "bun") {
471
+ if (args[1] === "test") report(context, "test", text, chain);
472
+ else if (["install", "add", "update", "remove"].includes(args[1] ?? "")) report(context, "install", text, chain);
473
+ else if (args[1] === "x" && args[2]) { const separator = args.indexOf("--"); visit(context, [args[2], ...(separator === -1 ? [] : args.slice(separator + 1))], cwd, chain, depth + 1); }
474
+ }
475
+ }
476
+
477
+ /**
478
+ * Split a shell string into simple commands at `&&`, `||`, `;`, `|`, `&`,
479
+ * newlines, and parentheses, honoring quotes; `cd <dir>` moves later commands.
480
+ * Command substitutions, functions, and loops are not interpreted.
481
+ */
482
+ function visitShell(context: Context, script: string, cwd: string, chain: string[], depth: number): void {
483
+ let directory = cwd;
484
+ // A `cd` inside parentheses ends with its subshell.
485
+ const outer: string[] = [];
486
+ const items = parseShell(script);
487
+ for (const [index, item] of items.entries()) {
488
+ if (item === "&") continue;
489
+ if (item === "(") { outer.push(directory); continue; }
490
+ if (item === ")") { directory = outer.pop() ?? directory; continue; }
491
+ const words = item;
492
+ // A backgrounded `cd dir &` runs in its own process and moves nothing after it.
493
+ if (words[0] === "cd" && items[index + 1] === "&") continue;
494
+ while (words.length && KEYWORDS.has(words[0]!)) words.shift();
495
+ if (!words.length || words[0] === "for" || words[0] === "case" || /\(\)$/.test(words[0]!)) continue;
496
+ if (words[0] === "cd") { if (words[1] && words[1] !== "-" && !words[1].startsWith("$")) directory = path.resolve(directory, words[1]); continue; }
497
+ visit(context, words, directory, chain, depth + 1);
498
+ }
499
+ }
500
+
501
+ export function splitShell(script: string): string[][] {
502
+ return parseShell(script).filter((item): item is string[] => Array.isArray(item));
503
+ }
504
+
505
+ /** Simple commands in order, with `(` and `)` marking where a subshell starts and ends and `&` following a backgrounded command. */
506
+ function parseShell(script: string): (string[] | "(" | ")" | "&")[] {
507
+ const commands: (string[] | "(" | ")" | "&")[] = [];
508
+ let words: string[] = [];
509
+ let word = "";
510
+ let quoted = false;
511
+ const endWord = () => { if (word || quoted) words.push(word); word = ""; quoted = false; };
512
+ const endCommand = () => { endWord(); const kept = dropRedirections(words); if (kept.length) commands.push(kept); words = []; };
513
+ for (let index = 0; index < script.length; index++) {
514
+ const char = script[index]!;
515
+ if (char === "\\" && index + 1 < script.length) { if (script[index + 1] !== "\n") word += script[index + 1]; index++; }
516
+ else if (char === "'") { const end = script.indexOf("'", index + 1); word += script.slice(index + 1, end === -1 ? undefined : end); quoted = true; index = end === -1 ? script.length : end; }
517
+ else if (char === '"') {
518
+ let end = index + 1;
519
+ while (end < script.length && script[end] !== '"') {
520
+ if (script[end] === "\\" && end + 1 < script.length) { word += script[end + 1]; end += 2; } else { word += script[end]; end++; }
521
+ }
522
+ quoted = true; index = end;
523
+ } else if (char === "#" && !word && !quoted) { const end = script.indexOf("\n", index); index = end === -1 ? script.length : end - 1; }
524
+ else if (char === "$" && script[index + 1] === "(") {
525
+ // Keep a command substitution inside its word rather than splitting on its operators.
526
+ let level = 0, end = index + 1;
527
+ for (; end < script.length; end++) { if (script[end] === "(") level++; else if (script[end] === ")" && --level === 0) break; }
528
+ word += script.slice(index, end + 1); index = end;
529
+ } else if ("&|;\n()".includes(char)) {
530
+ // `2>&1` and `&>` are redirections, not separators.
531
+ if (char === "&" && (word.endsWith(">") || script[index + 1] === ">")) { word += char; continue; }
532
+ endCommand();
533
+ if (char === "(" || char === ")") commands.push(char);
534
+ else if ((char === "&" || char === "|") && script[index + 1] === char) index++;
535
+ else if (char === "&") commands.push("&");
536
+ } else if (char === " " || char === "\t") endWord();
537
+ else word += char;
538
+ }
539
+ endCommand();
540
+ return commands;
541
+ }
542
+
543
+ function dropRedirections(words: string[]): string[] {
544
+ const result: string[] = [];
545
+ for (let index = 0; index < words.length; index++) {
546
+ const value = words[index]!;
547
+ if (/^\d*(?:>>?|<|&>>?)(?:&\d*)?$/.test(value) && !/&\d+$/.test(value)) { index++; continue; }
548
+ if (/^\d*(?:>>?|<|&>>?)/.test(value)) continue;
549
+ result.push(value);
550
+ }
551
+ return result;
552
+ }
@@ -7,6 +7,7 @@ import { viewCurrentBranchPr } from "../git/currentBranchPr";
7
7
  import { assert, clean, currentBranch, flag, git, head, mutateGit, oid, output, read, repository } from "./core";
8
8
  import { pullRequest } from "./pr";
9
9
  import { assertStrictBaseFreshness } from "../pr/baseFreshness";
10
+ import { baseHealthCommand } from "./baseHealth";
10
11
 
11
12
  export function repoCommand(args: string[]): number {
12
13
  const action = args.shift();
@@ -21,6 +22,7 @@ export function repoCommand(args: string[]): number {
21
22
  const fetchedBaseOid = fetch ? resolveFreshBaseRef(baseRepo, baseBranch) : undefined;
22
23
  output({ repo: repo.nameWithOwner, defaultBranch: repo.defaultBranchRef.name, branch, headOid: head(), clean: !git(["status", "--porcelain=v1", "--untracked-files=all"]), pr: pr ?? null, baseRepo, baseBranch, liveBaseOid: remoteBranchHead(resolveRepositoryGitUrl(baseRepo), baseBranch), ...(fetch ? { fetchedBaseOid } : {}) }); return 0;
23
24
  }
25
+ if (action === "base-health") return baseHealthCommand(args);
24
26
  const apply = flag(args, "--apply");
25
27
  const keep = flag(args, "--keep-branch");
26
28
  assert(action === "cleanup" && args.length === 2 && /^\d+$/.test(args[0]!), "Usage: repo cleanup <PR-number> <shipped-head> [--apply] [--keep-branch]");