@a2f0/agent-tool 0.1.56 → 0.1.58

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,386 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { packageDirectories } from "../system/workspace";
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[] }
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"]),
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 or dependency install
38
+ * it reaches. Executables and script files are leaves: their contents are not
39
+ * inspected. Workspace filters resolve to every workspace package declaring
40
+ * the script, which can over-report but never misses one.
41
+ */
42
+ export function resolveStep(root: string, command: string[]): StepResolution {
43
+ const context: Context = { root, seen: new Set(), findings: [], errors: [] };
44
+ visit(context, command, root, [display(command)], 0);
45
+ return { findings: context.findings, errors: context.errors };
46
+ }
47
+
48
+ export function display(argv: string[]): string { return argv.map(arg => /^[\w@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replaceAll("'", "'\\''")}'`).join(" "); }
49
+ function report(context: Context, kind: StepFinding["kind"], runner: string, chain: string[]): void {
50
+ context.findings.push({ kind, runner, chain: chain.at(-1) === runner ? chain : [...chain, runner] });
51
+ }
52
+
53
+ /** Skip leading options, consuming the separate value of the ones that take one; returns the options seen. */
54
+ function options(argv: string[], spec: Tool): { rest: string[]; seen: Map<string, string | true> } {
55
+ const seen = new Map<string, string | true>();
56
+ let index = 0;
57
+ 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);
63
+ index++;
64
+ }
65
+ return { rest: argv.slice(index), seen };
66
+ }
67
+
68
+ /** `npx`, `bunx`, `bun x`, and `<manager> exec|dlx`: a command after an optional `--`, or a shell string given to `--call`. */
69
+ function execute(context: Context, args: string[], cwd: string, chain: string[], depth: number): void {
70
+ const { rest, seen } = options(args, TOOLS.exec);
71
+ const call = seen.get("--call") ?? seen.get("-c");
72
+ if (typeof call === "string") visitShell(context, call, cwd, chain, depth + 1);
73
+ const command = rest[0] === "--" ? rest.slice(1) : rest;
74
+ if (command.length) visit(context, command, cwd, chain, depth + 1);
75
+ }
76
+
77
+ /** `run [options] [--] <script> [args]`: a `--` before the script name only ends the manager's options. */
78
+ function scriptOptions(args: string[], spec: Tool): { rest: string[]; seen: Map<string, string | true> } {
79
+ const parsed = options(args, spec);
80
+ return parsed.rest[0] === "--" ? { rest: parsed.rest.slice(1), seen: parsed.seen } : parsed;
81
+ }
82
+
83
+ function directoryOption(cwd: string, seen: Map<string, string | true>): string {
84
+ for (const name of ["--cwd", "--prefix", "-C", "--dir"]) { const value = seen.get(name); if (typeof value === "string") return path.resolve(cwd, value); }
85
+ return cwd;
86
+ }
87
+ const workspaceScoped = (seen: Map<string, string | true>, spec: Tool) => [...seen.keys()].some(name => spec.workspaces.has(name));
88
+
89
+ function scripts(directory: string): Record<string, unknown> | null {
90
+ const file = path.join(directory, "package.json");
91
+ if (!existsSync(file)) return null;
92
+ try {
93
+ const value = JSON.parse(readFileSync(file, "utf8")) as { scripts?: unknown };
94
+ return value.scripts && typeof value.scripts === "object" && !Array.isArray(value.scripts) ? value.scripts as Record<string, unknown> : {};
95
+ } catch { return null; }
96
+ }
97
+
98
+ /**
99
+ * Run a package script as its manager would: `pre<name>`, the script with its
100
+ * arguments appended, then `post<name>`. An unknown name runs `fallback`, the
101
+ * executable or file of that name, when the manager does so.
102
+ */
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");
107
+ if (!existsSync(file)) return [...directories];
108
+ let patterns: unknown;
109
+ 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]; }
111
+ const list = (Array.isArray(patterns) ? patterns : []).filter((pattern): pattern is string => typeof pattern === "string");
112
+ const excluded = list.filter(pattern => pattern.startsWith("!")).map(pattern => new Bun.Glob(pattern.slice(1).replace(/\/$/, "")));
113
+ 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 })) {
115
+ 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));
117
+ }
118
+ }
119
+ return [...directories];
120
+ }
121
+
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 {
124
+ let current = directory;
125
+ while (!existsSync(path.join(current, "package.json")) && current !== context.root && current.startsWith(`${context.root}${path.sep}`)) current = path.dirname(current);
126
+ return current;
127
+ }
128
+
129
+ function runScript(context: Context, name: string, args: string[], directory: string, workspaces: boolean, chain: string[], depth: number, fallback: string[] | null): void {
130
+ const directories = workspaces ? workspaceDirectories(context).filter(dir => typeof scripts(dir)?.[name] === "string") : [packageRoot(context, directory)];
131
+ let found = false;
132
+ for (const dir of directories) {
133
+ const table = scripts(dir);
134
+ for (const script of [`pre${name}`, name, `post${name}`]) {
135
+ const body = table?.[script];
136
+ if (typeof body !== "string") continue;
137
+ if (script === name) found = true;
138
+ const key = `${dir}\0${script}`;
139
+ if (context.seen.has(key)) continue;
140
+ const manifest = path.relative(context.root, path.join(dir, "package.json")) || "package.json";
141
+ const text = script === name && args.length ? `${body} ${display(args)}` : body;
142
+ context.seen.add(key);
143
+ visitShell(context, text, dir, [...chain, `${manifest} scripts.${script}: ${text}`], depth + 1);
144
+ context.seen.delete(key);
145
+ }
146
+ }
147
+ if (!found && fallback) visit(context, fallback, directory, chain, depth + 1);
148
+ }
149
+
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; }
152
+ 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;
156
+ // `npx vitest@4` names the runner with a version selector.
157
+ const name = path.basename(argv[0]!).replace(/(?<=.)@[^@/]*$/, "");
158
+ const args = argv.slice(1);
159
+ const text = display(argv);
160
+ if (SHELLS.has(name)) {
161
+ const flagIndex = args.findIndex(arg => /^-[a-z]*c[a-z]*$/.test(arg));
162
+ if (flagIndex !== -1 && args[flagIndex + 1] !== undefined) visitShell(context, args[flagIndex + 1]!, cwd, chain, depth + 1);
163
+ } else if (name === "agent-tool" || ((name === "bun" || name === "node") && /(?:^|\/)agent-tool\/src\/index\.ts$/.test(args[0] ?? ""))) {
164
+ agentTool(context, name === "agent-tool" ? args : args.slice(1), cwd, chain, depth);
165
+ } else if (name === "bun") bun(context, args, cwd, chain, depth, text);
166
+ else if (name === "bunx" || name === "npx") execute(context, args, cwd, chain, depth);
167
+ 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); }
169
+ 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);
171
+ else if (name === "bundle" && args[0] === "exec") visit(context, args.slice(1), cwd, chain, depth + 1);
172
+ }
173
+
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]!;
179
+ if (value === "--") break;
180
+ if (value.startsWith("-")) { if (!value.includes("=") && TOOLS.turbo.values.has(value)) index++; continue; }
181
+ tasks.push(value);
182
+ }
183
+ return tasks;
184
+ }
185
+
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"] };
188
+ function subcommand(name: string, args: string[]): string | undefined {
189
+ const values = RUNNER_VALUES[name] ?? [];
190
+ for (let index = 0; index < args.length; index++) {
191
+ const value = args[index]!;
192
+ if (values.includes(value)) { index++; continue; }
193
+ if (value.startsWith("-") || (name === "cargo" && value.startsWith("+"))) continue;
194
+ return value;
195
+ }
196
+ return undefined;
197
+ }
198
+
199
+ function testRunner(name: string, args: string[]): boolean {
200
+ if (["jest", "vitest", "mocha", "ava", "maestro", "detox", "pytest", "rspec"].includes(name)) return true;
201
+ const first = subcommand(name, args);
202
+ if (name === "node") return args.some(arg => arg === "--test" || arg.startsWith("--test="));
203
+ if (["playwright", "deno", "go", "swift"].includes(name)) return first === "test";
204
+ 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";
208
+ return false;
209
+ }
210
+
211
+ function bun(context: Context, args: string[], cwd: string, chain: string[], depth: number, text: string): void {
212
+ const { rest, seen } = options(args, TOOLS.bun);
213
+ const directory = directoryOption(cwd, seen);
214
+ const sub = rest[0];
215
+ if (!sub) return;
216
+ if (sub === "test") report(context, "test", text, chain);
217
+ else if (INSTALLS.bun.includes(sub)) report(context, "install", text, chain);
218
+ else if (sub === "x") execute(context, rest.slice(1), directory, chain, depth);
219
+ else if (sub === "exec") { if (rest[1]) visitShell(context, rest[1], directory, chain, depth + 1); }
220
+ else if (sub === "run") {
221
+ const run = scriptOptions(rest.slice(1), TOOLS.bun);
222
+ const target = run.rest[0];
223
+ // Only a leading `--` separates the script's arguments; later ones belong to the script.
224
+ const forwarded = run.rest.slice(1);
225
+ 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);
226
+ }
227
+ // `bun <name>` runs a package script of that name, else a file or built-in.
228
+ else runScript(context, sub, rest.slice(1), directory, workspaceScoped(seen, TOOLS.bun), chain, depth, null);
229
+ }
230
+
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> } {
233
+ const separator = args.indexOf("--");
234
+ const before = separator === -1 ? args : args.slice(0, separator);
235
+ const seen = new Map<string, string | true>(), positional: string[] = [];
236
+ for (let index = 0; index < before.length; index++) {
237
+ const value = before[index]!;
238
+ 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);
243
+ }
244
+ return { rest: separator === -1 ? positional : [...positional, ...args.slice(separator)], seen };
245
+ }
246
+
247
+ function packageManager(context: Context, manager: "npm" | "pnpm" | "yarn", args: string[], cwd: string, chain: string[], depth: number, text: string): void {
248
+ const spec = TOOLS[manager];
249
+ const { rest, seen } = manager === "npm" ? npmOptions(args) : options(args, spec);
250
+ const directory = directoryOption(cwd, seen);
251
+ const workspaces = workspaceScoped(seen, spec);
252
+ const sub = rest[0];
253
+ // Arguments after `--` reach the script; the manager drops the separator itself.
254
+ const scriptArgs = (values: string[]) => { const at = values.indexOf("--"); return at === -1 ? values : [...values.slice(0, at), ...values.slice(at + 1)]; };
255
+ if (!sub) { if (manager === "yarn") report(context, "install", text, chain); }
256
+ else if (INSTALLS[manager].includes(sub)) report(context, "install", text, chain);
257
+ else if (["run", "run-script", "rum", "urn"].includes(sub)) {
258
+ const run = scriptOptions(rest.slice(1), spec);
259
+ 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);
260
+ } else if (["test", "t", "tst", "start", "stop", "restart"].includes(sub)) {
261
+ runScript(context, ["t", "tst"].includes(sub) ? "test" : sub, scriptArgs(rest.slice(1)), directory, workspaces, chain, depth, null);
262
+ } else if (["exec", "x", "dlx"].includes(sub)) {
263
+ // npm has already read `--call` wherever it appeared.
264
+ const call = seen.get("--call") ?? seen.get("-c");
265
+ if (manager === "npm" && typeof call === "string") visitShell(context, call, directory, chain, depth + 1);
266
+ execute(context, rest.slice(1), directory, chain, depth);
267
+ }
268
+ // pnpm and yarn run a script by its bare name, else an installed executable of that name.
269
+ else if (manager !== "npm") runScript(context, sub, rest.slice(1), directory, workspaces, chain, depth, rest);
270
+ }
271
+
272
+ /** The checkout holding `directory`: this repository's root when it is inside it, else the nearest directory with a `.git`. */
273
+ function checkoutOf(context: Context, directory: string): string {
274
+ if (directory === context.root || directory.startsWith(`${context.root}${path.sep}`)) {
275
+ for (let current = directory; current !== context.root; current = path.dirname(current)) if (existsSync(path.join(current, ".git"))) return current;
276
+ return context.root;
277
+ }
278
+ for (let current = directory; current !== path.dirname(current); current = path.dirname(current)) if (existsSync(path.join(current, ".git"))) return current;
279
+ return directory;
280
+ }
281
+
282
+ function agentTool(context: Context, input: string[], invokedIn: string, chain: string[], depth: number): void {
283
+ const args = [...input];
284
+ // `--repo` moves the command, and the run-group plans it resolves, to that checkout.
285
+ let cwd = invokedIn, repo: string | null = null;
286
+ 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); }
287
+ const text = display(["agent-tool", ...args]);
288
+ if (args[0] === "run-group" && args[1]) {
289
+ // Like the CLI, resolve the plan and run its steps from the root of the checkout `--repo` names.
290
+ const checkout = repo ? checkoutOf(context, repo) : context.root;
291
+ const plan = path.resolve(checkout, args[1]);
292
+ const relative = path.relative(context.root, plan);
293
+ let steps: { label: string; command: string[] }[];
294
+ try {
295
+ const value = JSON.parse(readFileSync(plan, "utf8")) as { steps?: unknown };
296
+ 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");
297
+ if (!Array.isArray(value.steps) || !value.steps.every(valid)) throw new Error("expected steps with a label and command");
298
+ steps = value.steps;
299
+ } catch (error) { context.errors.push(`Cannot read run-group plan ${relative} (${chain.join(" -> ")}): ${(error as Error).message}`); return; }
300
+ for (const step of steps) visit(context, step.command, checkout, [...chain, `${relative} step ${step.label}: ${display(step.command)}`], depth + 1);
301
+ } else if (args[0] === "run") {
302
+ const separator = args.indexOf("--");
303
+ if (separator !== -1) visit(context, args.slice(separator + 1), cwd, chain, depth + 1);
304
+ } else if (args[0] === "bun") {
305
+ if (args[1] === "test") report(context, "test", text, chain);
306
+ else if (["install", "add", "update", "remove"].includes(args[1] ?? "")) report(context, "install", text, chain);
307
+ 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); }
308
+ }
309
+ }
310
+
311
+ /**
312
+ * Split a shell string into simple commands at `&&`, `||`, `;`, `|`, `&`,
313
+ * newlines, and parentheses, honoring quotes; `cd <dir>` moves later commands.
314
+ * Command substitutions, functions, and loops are not interpreted.
315
+ */
316
+ function visitShell(context: Context, script: string, cwd: string, chain: string[], depth: number): void {
317
+ let directory = cwd;
318
+ // A `cd` inside parentheses ends with its subshell.
319
+ const outer: string[] = [];
320
+ const items = parseShell(script);
321
+ for (const [index, item] of items.entries()) {
322
+ if (item === "&") continue;
323
+ if (item === "(") { outer.push(directory); continue; }
324
+ if (item === ")") { directory = outer.pop() ?? directory; continue; }
325
+ const words = item;
326
+ // A backgrounded `cd dir &` runs in its own process and moves nothing after it.
327
+ if (words[0] === "cd" && items[index + 1] === "&") continue;
328
+ while (words.length && KEYWORDS.has(words[0]!)) words.shift();
329
+ if (!words.length || words[0] === "for" || words[0] === "case" || /\(\)$/.test(words[0]!)) continue;
330
+ if (words[0] === "cd") { if (words[1] && words[1] !== "-" && !words[1].startsWith("$")) directory = path.resolve(directory, words[1]); continue; }
331
+ visit(context, words, directory, chain, depth + 1);
332
+ }
333
+ }
334
+
335
+ export function splitShell(script: string): string[][] {
336
+ return parseShell(script).filter((item): item is string[] => Array.isArray(item));
337
+ }
338
+
339
+ /** Simple commands in order, with `(` and `)` marking where a subshell starts and ends and `&` following a backgrounded command. */
340
+ function parseShell(script: string): (string[] | "(" | ")" | "&")[] {
341
+ const commands: (string[] | "(" | ")" | "&")[] = [];
342
+ let words: string[] = [];
343
+ let word = "";
344
+ let quoted = false;
345
+ const endWord = () => { if (word || quoted) words.push(word); word = ""; quoted = false; };
346
+ const endCommand = () => { endWord(); const kept = dropRedirections(words); if (kept.length) commands.push(kept); words = []; };
347
+ for (let index = 0; index < script.length; index++) {
348
+ const char = script[index]!;
349
+ if (char === "\\" && index + 1 < script.length) { if (script[index + 1] !== "\n") word += script[index + 1]; index++; }
350
+ 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; }
351
+ else if (char === '"') {
352
+ let end = index + 1;
353
+ while (end < script.length && script[end] !== '"') {
354
+ if (script[end] === "\\" && end + 1 < script.length) { word += script[end + 1]; end += 2; } else { word += script[end]; end++; }
355
+ }
356
+ quoted = true; index = end;
357
+ } else if (char === "#" && !word && !quoted) { const end = script.indexOf("\n", index); index = end === -1 ? script.length : end - 1; }
358
+ else if (char === "$" && script[index + 1] === "(") {
359
+ // Keep a command substitution inside its word rather than splitting on its operators.
360
+ let level = 0, end = index + 1;
361
+ for (; end < script.length; end++) { if (script[end] === "(") level++; else if (script[end] === ")" && --level === 0) break; }
362
+ word += script.slice(index, end + 1); index = end;
363
+ } else if ("&|;\n()".includes(char)) {
364
+ // `2>&1` and `&>` are redirections, not separators.
365
+ if (char === "&" && (word.endsWith(">") || script[index + 1] === ">")) { word += char; continue; }
366
+ endCommand();
367
+ if (char === "(" || char === ")") commands.push(char);
368
+ else if ((char === "&" || char === "|") && script[index + 1] === char) index++;
369
+ else if (char === "&") commands.push("&");
370
+ } else if (char === " " || char === "\t") endWord();
371
+ else word += char;
372
+ }
373
+ endCommand();
374
+ return commands;
375
+ }
376
+
377
+ function dropRedirections(words: string[]): string[] {
378
+ const result: string[] = [];
379
+ for (let index = 0; index < words.length; index++) {
380
+ const value = words[index]!;
381
+ if (/^\d*(?:>>?|<|&>>?)(?:&\d*)?$/.test(value) && !/&\d+$/.test(value)) { index++; continue; }
382
+ if (/^\d*(?:>>?|<|&>>?)/.test(value)) continue;
383
+ result.push(value);
384
+ }
385
+ return result;
386
+ }
@@ -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]");