@a2f0/agent-tool 0.1.71 → 0.1.73

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,228 @@
1
+ /** Which ignored paths in a repository are regenerable, and which must be kept. */
2
+ import { spawnSync } from "node:child_process";
3
+ import { existsSync, lstatSync, type Stats } from "node:fs";
4
+ import path from "node:path";
5
+ import { isolatedGit } from "../system/checkouts";
6
+
7
+ /** Git bound to the repository it is asked about, whatever the caller's environment. */
8
+ function git(root: string, args: string[]): { ok: boolean; stdout: string } {
9
+ const result = isolatedGit(root, args);
10
+ return { ok: result.status === 0, stdout: result.stdout };
11
+ }
12
+
13
+ export const TIERS = ["caches", "builds", "deps"] as const;
14
+ export type Tier = (typeof TIERS)[number];
15
+
16
+ /** Tool and test caches: rebuilt on the next run at little cost. */
17
+ const CACHE_NAMES = new Set([
18
+ ".turbo",
19
+ ".parcel-cache",
20
+ ".eslintcache",
21
+ ".stylelintcache",
22
+ "coverage",
23
+ ".nyc_output",
24
+ "test-results",
25
+ "playwright-report",
26
+ "blob-report",
27
+ "__pycache__",
28
+ ".pytest_cache",
29
+ ".mypy_cache",
30
+ ".ruff_cache",
31
+ ]);
32
+ /** Build outputs: rebuilt by the repository's build, which can take minutes. */
33
+ const BUILD_NAMES = new Set(["dist", "build", "out", ".next", ".nuxt", ".output", ".svelte-kit", ".expo", ".gradle", ".build", "DerivedData"]);
34
+ /** Installed dependencies: restored by the repository's documented install. */
35
+ const DEPS_NAMES = new Set(["node_modules", ".venv"]);
36
+ /** Regenerable children of ignored directories that are themselves kept by a lighter tier. */
37
+ const NESTED: Record<string, Array<[string, Tier]>> = {
38
+ node_modules: [
39
+ [".cache", "caches"],
40
+ [".vite", "caches"],
41
+ ],
42
+ ".next": [["cache", "caches"]],
43
+ // .wrangler/state holds local D1, KV, and R2 data; only tmp is disposable.
44
+ ".wrangler": [["tmp", "caches"]],
45
+ vendor: [["bundle", "deps"]],
46
+ };
47
+
48
+ /** The tier a git-ignored path belongs to, or undefined when it is not known to be regenerable. */
49
+ function classify(rel: string, root: string): Tier | undefined {
50
+ const name = path.posix.basename(rel);
51
+ const parent = path.join(root, path.posix.dirname(rel));
52
+ if (CACHE_NAMES.has(name)) return "caches";
53
+ // Small, but deleting one makes the next typecheck start from scratch.
54
+ if (BUILD_NAMES.has(name) || name.endsWith(".tsbuildinfo")) return "builds";
55
+ if (name === "target" && existsSync(path.join(parent, "Cargo.toml"))) return "builds";
56
+ if (DEPS_NAMES.has(name)) return "deps";
57
+ if (name === "Pods" && existsSync(path.join(parent, "Podfile"))) return "deps";
58
+ // Bundler's install path, ignored on its own beside a tracked vendor/.
59
+ if (name === "bundle" && path.posix.basename(path.posix.dirname(rel)) === "vendor") return "deps";
60
+ return undefined;
61
+ }
62
+
63
+ /** Ignored paths from `git status --porcelain=v1 -z --ignored`, without trailing slashes. */
64
+ export function parseIgnored(porcelain: string): string[] {
65
+ return porcelain
66
+ .split("\0")
67
+ .filter(entry => entry.startsWith("!! "))
68
+ .map(entry => entry.slice(3).replace(/\/$/, ""));
69
+ }
70
+
71
+ export interface Candidate {
72
+ readonly path: string;
73
+ readonly tier: Tier;
74
+ bytes: number;
75
+ }
76
+
77
+ /** Names that mark a tree as holding work or data rather than regenerable output. */
78
+ // `.env*` covers `.envrc` and `.env-production` as well as `.env.local`.
79
+ const PROTECTED = [".git", ".env*", ".secrets", "*.sqlite", "*.sqlite3", "*.db"];
80
+ const TEMPLATE = /\.(example|sample|template)$/;
81
+ /**
82
+ * The llbuild databases Xcode (`Build/Intermediates.noindex/XCBuildData/build.db`, in DerivedData
83
+ * or a `build/` directory) and SwiftPM (`.build/build.db`) write beside their output.
84
+ */
85
+ const BUILD_DATABASES = ["*/XCBuildData/build.db", "*/.build/build.db"];
86
+
87
+ /** Whether one path component is protected, by the same patterns `find` applies below. */
88
+ export function protectedName(name: string): boolean {
89
+ if (TEMPLATE.test(name)) return false;
90
+ return PROTECTED.some(pattern =>
91
+ pattern.startsWith("*.") ? name.endsWith(pattern.slice(1)) : pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern,
92
+ );
93
+ }
94
+
95
+ /** A working tree (`.git` inside) or a bare repository (`HEAD`, `objects`, `refs`). */
96
+ export function isRepository(directory: string): boolean {
97
+ return (
98
+ existsSync(path.join(directory, ".git")) ||
99
+ (existsSync(path.join(directory, "HEAD")) && existsSync(path.join(directory, "objects")) && existsSync(path.join(directory, "refs")))
100
+ );
101
+ }
102
+
103
+ /** The first repository at or under `directory`, undefined when there is none; throws when it cannot search. */
104
+ function findRepository(directory: string): string | undefined {
105
+ if (isRepository(directory)) return directory;
106
+ const result = spawnSync("find", [directory, "(", "-name", ".git", "-o", "-name", "HEAD", ")", "-print"], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
107
+ if (result.status !== 0) throw new Error(`could not search ${directory} for repositories`);
108
+ for (const found of result.stdout.split("\n").filter(Boolean)) {
109
+ if (path.basename(found) === ".git") return path.dirname(found);
110
+ if (isRepository(path.dirname(found))) return path.dirname(found);
111
+ }
112
+ return undefined;
113
+ }
114
+
115
+ /**
116
+ * Why a directory must be kept because a repository, credentials, or a local
117
+ * database is somewhere inside it; undefined when nothing is. Paths in the
118
+ * reason are relative to `base`.
119
+ */
120
+ export function holdsProtected(directory: string, base: string): string | undefined {
121
+ const protectedFile = spawnSync(
122
+ "find",
123
+ [
124
+ directory,
125
+ "(",
126
+ ...PROTECTED.flatMap((name, index) => [...(index ? ["-o"] : []), "-name", name]),
127
+ ")",
128
+ "!",
129
+ "-name",
130
+ "*.example",
131
+ "!",
132
+ "-name",
133
+ "*.sample",
134
+ "!",
135
+ "-name",
136
+ "*.template",
137
+ // Build systems' own dependency databases are build output, not local data.
138
+ ...BUILD_DATABASES.flatMap(pattern => ["!", "-path", pattern]),
139
+ "-print",
140
+ "-quit",
141
+ ],
142
+ { encoding: "utf8" },
143
+ );
144
+ if (protectedFile.status !== 0) return "could not search for protected files";
145
+ const found = protectedFile.stdout.trim();
146
+ if (found !== "") return `contains ${path.relative(base, found)}`;
147
+ let repository: string | undefined;
148
+ try {
149
+ repository = findRepository(directory);
150
+ } catch {
151
+ return "could not search for repositories";
152
+ }
153
+ if (repository) return `contains repository ${path.relative(base, repository) || "."}`;
154
+ return undefined;
155
+ }
156
+
157
+ /** Why one directory on the way to a candidate, or the candidate itself, rules it out; checked in this order. */
158
+ function componentReason(root: string, current: string, part: string): string | undefined {
159
+ let stats: Stats;
160
+ try {
161
+ stats = lstatSync(current);
162
+ } catch {
163
+ return "missing";
164
+ }
165
+ if (stats.isSymbolicLink()) return "symlink";
166
+ // A nested clone above the candidate owns it (an ignored node_modules that is a repository).
167
+ if (isRepository(current)) return `inside repository ${path.relative(root, current)}`;
168
+ // An ignored `.secrets/build` is still inside credentials.
169
+ if (protectedName(part)) return `inside ${path.relative(root, current)}`;
170
+ return undefined;
171
+ }
172
+
173
+ /** Why a path must not be removed, or undefined when it is safe to. */
174
+ export function unsafeReason(root: string, rel: string): string | undefined {
175
+ if (rel === "" || path.isAbsolute(rel) || rel.split("/").some(part => part === ".." || part === "." || part === ".git")) return "outside the repository";
176
+ let current = root;
177
+ for (const part of rel.split("/")) {
178
+ current = path.join(current, part);
179
+ const reason = componentReason(root, current, part);
180
+ if (reason) return reason;
181
+ }
182
+ const held = holdsProtected(current, root);
183
+ if (held) return held;
184
+ // Checked here, not only at scan time: a file can be force-added between scan and removal.
185
+ // Literal: a path name that looks like pathspec magic (`:(glob)x`) names only itself.
186
+ const tracked = git(root, ["--literal-pathspecs", "ls-files", "-z", "--", rel]);
187
+ if (!tracked.ok) return "could not list tracked files";
188
+ if (tracked.stdout !== "") return "tracked";
189
+ if (!git(root, ["check-ignore", "-q", "--", rel]).ok) return "not ignored";
190
+ return undefined;
191
+ }
192
+
193
+ /** Ignored, untracked, regenerable paths in one repository. */
194
+ export function findCandidates(root: string): Candidate[] {
195
+ const status = git(root, ["status", "--porcelain=v1", "-z", "--ignored=traditional", "--untracked-files=normal"]);
196
+ if (!status.ok) throw new Error("git status failed");
197
+ const found: Candidate[] = [];
198
+ for (const rel of parseIgnored(status.stdout)) {
199
+ const tier = classify(rel, root);
200
+ if (tier) found.push({ path: rel, tier, bytes: 0 });
201
+ const nested = NESTED[path.posix.basename(rel)];
202
+ for (const [child, childTier] of nested ?? []) {
203
+ const childRel = `${rel}/${child}`;
204
+ if (existsSync(path.join(root, childRel))) found.push({ path: childRel, tier: childTier, bytes: 0 });
205
+ }
206
+ }
207
+ return found.filter(candidate => unsafeReason(root, candidate.path) === undefined);
208
+ }
209
+
210
+ /** Kilobyte-accurate sizes from du, which counts each hard link once per call. */
211
+ export function measure(paths: string[]): Map<string, number> {
212
+ const sizes = new Map<string, number>();
213
+ for (let start = 0; start < paths.length; start += 200) {
214
+ const batch = paths.slice(start, start + 200);
215
+ const result = spawnSync("du", ["-sk", "--", ...batch], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
216
+ for (const line of (result.stdout ?? "").split("\n")) {
217
+ const match = /^(\d+)\t(.*)$/.exec(line);
218
+ if (match) sizes.set(match[2]!, Number(match[1]) * 1024);
219
+ }
220
+ }
221
+ return sizes;
222
+ }
223
+
224
+ /** Candidates in the chosen tiers, without paths inside another chosen path. */
225
+ export function selected(candidates: Candidate[], tiers: ReadonlySet<Tier>): Candidate[] {
226
+ const chosen = candidates.filter(candidate => tiers.has(candidate.tier)).toSorted((a, b) => a.path.length - b.path.length);
227
+ return chosen.filter((candidate, index) => !chosen.slice(0, index).some(other => candidate.path.startsWith(`${other.path}/`)));
228
+ }
@@ -0,0 +1,325 @@
1
+ /**
2
+ * `agent-tool space`: dry-run-first disk cleanup for one repository, a matrix
3
+ * workspace and its checkouts, and optionally this machine's developer caches.
4
+ *
5
+ * In a repository it removes only paths that git reports as ignored and
6
+ * untracked, whose names mark them as regenerable output, that are not
7
+ * symlinks or nested repositories, in repositories no other process is
8
+ * working in. It never runs `git clean`, never touches tracked or untracked
9
+ * (unignored) files, and never deletes clones.
10
+ */
11
+ import { rmSync, statfsSync, writeSync } from "node:fs";
12
+ import path from "node:path";
13
+ import { type Candidate, findCandidates, measure, selected, TIERS, type Tier, unsafeReason } from "./candidates";
14
+ import { applyMachine, type MachineItem, machineItems } from "./machine";
15
+ import { busyRoots, type Proc, processes } from "./processes";
16
+ import { resolveTargets, type Target } from "./targets";
17
+
18
+ interface RepoReport {
19
+ readonly name: string;
20
+ readonly root: string;
21
+ busy?: Array<{ pid: number; name: string; cwd: string }>;
22
+ error?: string;
23
+ candidates: Candidate[];
24
+ removed?: string[];
25
+ failed?: Array<{ path: string; error: string }>;
26
+ }
27
+
28
+ export interface Options {
29
+ readonly names: string[];
30
+ readonly tiers: Set<Tier>;
31
+ readonly apply: boolean;
32
+ readonly json: boolean;
33
+ readonly machine: boolean;
34
+ readonly includeBusy: boolean;
35
+ }
36
+
37
+ export const SPACE_USAGE = `Usage: agent-tool space [checkout-or-path...] [--builds] [--deps] [--machine] [--include-busy] [--apply] [--json]
38
+
39
+ Reports regenerable, git-ignored, untracked paths and removes them with --apply.
40
+ From a matrix workspace it covers the workspace and every checkout, or the
41
+ named checkouts; elsewhere, the repository holding the working directory.
42
+
43
+ (default) caches: .turbo, .parcel-cache, .eslintcache, .stylelintcache, coverage,
44
+ .nyc_output, test-results, playwright-report, blob-report, __pycache__,
45
+ .pytest_cache, .mypy_cache, .ruff_cache, node_modules/.cache and .vite,
46
+ .next/cache, .wrangler/tmp
47
+ --builds also build outputs: dist, build, out, .next, .nuxt, .output, .svelte-kit,
48
+ .expo, .gradle, .build, DerivedData, *.tsbuildinfo, Cargo's target
49
+ --deps also installed dependencies: node_modules, .venv, Pods, vendor/bundle
50
+ --machine also developer caches outside repositories (DerivedData, brew, bun, npm)
51
+ --include-busy clean repositories other processes are working in
52
+ --apply remove what the report lists; without it nothing changes
53
+ --json JSON output for agents`;
54
+
55
+ type Switches = Record<"apply" | "json" | "machine" | "includeBusy", boolean>;
56
+
57
+ /** The boolean options, by the field each sets. */
58
+ const SWITCHES = new Map<string, keyof Switches>([
59
+ ["--apply", "apply"],
60
+ ["--json", "json"],
61
+ ["--machine", "machine"],
62
+ ["--include-busy", "includeBusy"],
63
+ ]);
64
+
65
+ /** The options that add a tier to the default caches. */
66
+ const TIER_OPTIONS = new Map<string, Tier>([
67
+ ["--builds", "builds"],
68
+ ["--deps", "deps"],
69
+ ]);
70
+
71
+ export function parseOptions(argv: string[]): Options {
72
+ const names: string[] = [];
73
+ const tiers = new Set<Tier>(["caches"]);
74
+ const switches: Switches = { apply: false, json: false, machine: false, includeBusy: false };
75
+ for (const arg of argv) {
76
+ const field = SWITCHES.get(arg);
77
+ const tier = TIER_OPTIONS.get(arg);
78
+ if (field) switches[field] = true;
79
+ else if (tier) tiers.add(tier);
80
+ else if (arg.startsWith("-")) throw new Error(`unknown option ${arg}\n\n${SPACE_USAGE}`);
81
+ else names.push(arg);
82
+ }
83
+ return { names, tiers, ...switches };
84
+ }
85
+
86
+ function size(bytes: number | undefined): string {
87
+ if (bytes === undefined) return "?";
88
+ const units = ["B", "KiB", "MiB", "GiB", "TiB"];
89
+ let value = bytes,
90
+ unit = 0;
91
+ while (value >= 1024 && unit < units.length - 1) {
92
+ value /= 1024;
93
+ unit++;
94
+ }
95
+ return `${value.toFixed(unit > 1 ? 1 : 0)} ${units[unit]}`;
96
+ }
97
+
98
+ /** Bytes one tier would free, counting a nested path once with its parent. */
99
+ function tierBytes(candidates: Candidate[], tier: Tier): number {
100
+ return selected(candidates, new Set([tier])).reduce((sum, candidate) => sum + candidate.bytes, 0);
101
+ }
102
+
103
+ /** Bytes each tier would free across every repository. */
104
+ function tierTotals(repos: RepoReport[]): Record<Tier, number> {
105
+ const totals: Record<Tier, number> = { caches: 0, builds: 0, deps: 0 };
106
+ for (const tier of TIERS) for (const repo of repos) totals[tier] += tierBytes(repo.candidates, tier);
107
+ return totals;
108
+ }
109
+
110
+ /** The busy processes reported for a repository; undefined when there are none. */
111
+ function workersOf(procs: Proc[] | undefined): RepoReport["busy"] {
112
+ return procs?.map(({ pid, name, cwd }) => ({ pid, name, cwd: cwd ?? "(unreadable)" }));
113
+ }
114
+
115
+ function free(directory: string): number {
116
+ const stats = statfsSync(directory);
117
+ return stats.bavail * stats.bsize;
118
+ }
119
+
120
+ const PRINT = (text: string) => {
121
+ writeSync(1, `${text}\n`);
122
+ };
123
+
124
+ /**
125
+ * One cleanup run: report, and with --apply remove. Returns 1 when a repository
126
+ * could not be scanned or a removal failed, else 0; throws on a usage error or
127
+ * when processes cannot be listed.
128
+ */
129
+ export function space(argv: string[], cwd = process.cwd(), discover: () => Proc[] = processes, print: (text: string) => void = PRINT): number {
130
+ if (argv.includes("--help") || argv.includes("-h")) {
131
+ print(SPACE_USAGE);
132
+ return 0;
133
+ }
134
+ const options = parseOptions(argv);
135
+ const { workspace, targets } = resolveTargets(cwd, options.names);
136
+ const volume = workspace ?? targets[0]?.root ?? cwd;
137
+ const before = free(volume);
138
+ const procs = listProcesses(discover, options.includeBusy);
139
+ const busy = busyRoots(
140
+ procs,
141
+ targets.map(target => target.root),
142
+ );
143
+
144
+ const repos: RepoReport[] = targets.map(target => scanRepo(target, busy));
145
+ const machine = options.machine ? machineItems(procs) : [];
146
+
147
+ // A repository that could not be scanned was not cleaned: report it as a failure.
148
+ let failures = repos.filter(repo => repo.error).length;
149
+ if (options.apply) {
150
+ failures += cleanRepos(repos, targets, options, discover);
151
+ // --include-busy covers repositories only: package caches and DerivedData always wait for installs and builds.
152
+ failures += applyMachine(machine, discover);
153
+ }
154
+ const after = options.apply ? free(volume) : undefined;
155
+
156
+ const report: Report = { options, workspace, before, after, totals: tierTotals(repos), repos, machine };
157
+ print(options.json ? jsonReport(report) : textReport(report));
158
+ return failures > 0 ? 1 : 0;
159
+ }
160
+
161
+ /** Everything one run found and did, as both reports print it. */
162
+ interface Report {
163
+ readonly options: Options;
164
+ readonly workspace: string | undefined;
165
+ readonly before: number;
166
+ readonly after: number | undefined;
167
+ readonly totals: Record<Tier, number>;
168
+ readonly repos: RepoReport[];
169
+ readonly machine: MachineItem[];
170
+ }
171
+
172
+ /** The process list; with --include-busy a failure to list them counts as no processes. */
173
+ function listProcesses(discover: () => Proc[], includeBusy: boolean): Proc[] {
174
+ try {
175
+ return discover();
176
+ } catch (error) {
177
+ if (!includeBusy) throw error;
178
+ return [];
179
+ }
180
+ }
181
+
182
+ /** One repository's candidates, each sized, and the processes working in it. */
183
+ function scanRepo(target: Target, busy: Map<string, Proc[]>): RepoReport {
184
+ const report: RepoReport = { ...target, candidates: [] };
185
+ report.busy = workersOf(busy.get(target.root));
186
+ try {
187
+ report.candidates = findCandidates(target.root);
188
+ } catch (error) {
189
+ report.error = (error as Error).message;
190
+ }
191
+ // du counts a directory once per call, so a nested cache measured alongside its parent
192
+ // would read as empty: measure outer paths and nested ones in separate calls.
193
+ const nested = (candidate: Candidate) => report.candidates.some(other => candidate.path.startsWith(`${other.path}/`));
194
+ for (const group of [report.candidates.filter(candidate => !nested(candidate)), report.candidates.filter(nested)]) {
195
+ const sizes = measure(group.map(candidate => path.join(target.root, candidate.path)));
196
+ for (const candidate of group) candidate.bytes = sizes.get(path.join(target.root, candidate.path)) ?? 0;
197
+ }
198
+ return report;
199
+ }
200
+
201
+ /** Removes the chosen tiers from every scanned repository that is not busy; returns the number of failed removals. */
202
+ function cleanRepos(repos: RepoReport[], targets: Target[], options: Options, discover: () => Proc[]): number {
203
+ let failures = 0;
204
+ for (const repo of repos) {
205
+ if (repo.error) continue;
206
+ // Scans and earlier removals take a while; judge each repository from a fresh process list.
207
+ if (!options.includeBusy) {
208
+ let procs: Proc[];
209
+ try {
210
+ procs = discover();
211
+ } catch (error) {
212
+ // Earlier repositories were cleaned already: report this one as not cleaned, and the run's removals.
213
+ repo.error = `not cleaned: ${(error as Error).message}`;
214
+ // The scan-time list is stale and the repository was not judged busy: only the error stands.
215
+ repo.busy = undefined;
216
+ failures++;
217
+ continue;
218
+ }
219
+ repo.busy = workersOf(
220
+ busyRoots(
221
+ procs,
222
+ targets.map(target => target.root),
223
+ ).get(repo.root),
224
+ );
225
+ if (repo.busy) continue;
226
+ }
227
+ failures += removeCandidates(repo, options.tiers);
228
+ }
229
+ return failures;
230
+ }
231
+
232
+ /** Removes one repository's chosen candidates, rechecking each first; returns the number that failed. */
233
+ function removeCandidates(repo: RepoReport, tiers: Set<Tier>): number {
234
+ const removed: string[] = [];
235
+ const failed: Array<{ path: string; error: string }> = [];
236
+ repo.removed = removed;
237
+ repo.failed = failed;
238
+ for (const candidate of selected(repo.candidates, tiers)) {
239
+ // Re-check at removal time: the tree may have changed since the scan.
240
+ const reason = unsafeReason(repo.root, candidate.path);
241
+ if (reason) {
242
+ if (reason !== "missing") failed.push({ path: candidate.path, error: reason });
243
+ continue;
244
+ }
245
+ try {
246
+ rmSync(path.join(repo.root, candidate.path), { recursive: true, force: true });
247
+ removed.push(candidate.path);
248
+ } catch (error) {
249
+ failed.push({ path: candidate.path, error: (error as Error).message });
250
+ }
251
+ }
252
+ return failed.length;
253
+ }
254
+
255
+ function jsonReport({ options, workspace, before, after, totals, repos, machine }: Report): string {
256
+ return JSON.stringify(
257
+ {
258
+ applied: options.apply,
259
+ workspace: workspace ?? null,
260
+ tiers: [...options.tiers],
261
+ free: { before, ...(after !== undefined && { after }) },
262
+ totals,
263
+ // A repository that could not be scanned reports its error, as the text report does, not also a busy skip.
264
+ repos: repos.map(repo => ({ ...repo, skipped: repo.busy && !repo.error && !options.includeBusy ? "busy" : undefined })),
265
+ ...(options.machine && { machine: machine.map(({ apply: _apply, ...item }) => item) }),
266
+ },
267
+ null,
268
+ 2,
269
+ );
270
+ }
271
+
272
+ function textReport({ options, workspace, before, after, totals, repos, machine }: Report): string {
273
+ const lines = [`Space cleanup ${options.apply ? "(applied)" : "(dry run)"}: ${size(before)} free${workspace ? ` in matrix workspace ${workspace}` : ""}`];
274
+ for (const repo of repos) lines.push(...repoLines(repo, options));
275
+ if (options.machine) {
276
+ lines.push("\nmachine");
277
+ for (const item of machine) lines.push(` ${size(item.bytes).padStart(10)} ${item.description}: ${machineState(item, options.apply)}`);
278
+ }
279
+ lines.push(
280
+ `\nTotals: caches ${size(totals.caches)}, builds ${size(totals.builds)}${options.tiers.has("builds") ? "" : " (--builds)"}, deps ${size(totals.deps)}${options.tiers.has("deps") ? "" : " (--deps)"}`,
281
+ );
282
+ if (after !== undefined) lines.push(`Free: ${size(before)} -> ${size(after)}`);
283
+ else lines.push("Nothing changed; rerun with --apply to remove the listed tiers.");
284
+ return lines.join("\n");
285
+ }
286
+
287
+ /** One repository's section: its status, per-tier sizes, largest chosen paths, and failures. */
288
+ function repoLines(repo: RepoReport, options: Options): string[] {
289
+ const chosen = selected(repo.candidates, options.tiers);
290
+ const perTier = TIERS.map(tier => `${tier} ${size(tierBytes(repo.candidates, tier))}`).join(", ");
291
+ const lines = [`\n${repo.name}${repoStatus(repo, options.includeBusy)}\n ${perTier}`];
292
+ for (const candidate of chosen.toSorted((a, b) => b.bytes - a.bytes).slice(0, 8))
293
+ lines.push(
294
+ ` ${options.apply && repo.removed?.includes(candidate.path) ? "removed" : candidate.tier.padEnd(7)} ${size(candidate.bytes).padStart(10)} ${candidate.path}`,
295
+ );
296
+ if (chosen.length > 8) lines.push(` ... and ${chosen.length - 8} more`);
297
+ for (const failure of repo.failed ?? []) lines.push(` FAILED ${failure.path}: ${failure.error}`);
298
+ return lines;
299
+ }
300
+
301
+ function repoStatus(repo: RepoReport, includeBusy: boolean): string {
302
+ if (repo.error) return ` error: ${repo.error}`;
303
+ if (!repo.busy || includeBusy) return "";
304
+ const shown = repo.busy
305
+ .slice(0, 3)
306
+ .map(proc => `${proc.name} ${proc.pid}`)
307
+ .join(", ");
308
+ return ` skipped, busy: ${shown}${repo.busy.length > 3 ? ", ..." : ""}`;
309
+ }
310
+
311
+ function machineState(item: MachineItem, apply: boolean): string {
312
+ if (item.reportOnly) return "review";
313
+ if (item.skipped) return `skipped (${item.skipped})`;
314
+ return item.result ?? (apply ? "" : "would clean");
315
+ }
316
+
317
+ /** The CLI entry: a run's exit status, or 2 with the message on stderr when it cannot run. */
318
+ export function spaceCommand(argv: string[]): number {
319
+ try {
320
+ return space(argv);
321
+ } catch (error) {
322
+ writeSync(2, `${(error as Error).message}\n`);
323
+ return 2;
324
+ }
325
+ }