@a2f0/agent-tool 0.1.72 → 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,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
+ }
@@ -0,0 +1,303 @@
1
+ /** Developer caches outside any repository, for `space --machine`. */
2
+ import { spawnSync } from "node:child_process";
3
+ import { type Dirent, existsSync, lstatSync, readdirSync, rmSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { holdsProtected, isRepository, measure, protectedName } from "./candidates";
7
+ import { type Proc, selfAndAncestors } from "./processes";
8
+
9
+ export interface MachineItem {
10
+ readonly id: string;
11
+ readonly description: string;
12
+ bytes?: number;
13
+ /** Only reported: removing it is a judgment call or needs a person. */
14
+ readonly reportOnly: boolean;
15
+ skipped?: string;
16
+ result?: string;
17
+ apply?: () => string;
18
+ /** Why it must wait, given the running processes; rechecked just before it runs. */
19
+ guard?: (procs: Proc[]) => string | undefined;
20
+ }
21
+
22
+ /** What `--machine` needs from the host; tests substitute a fake one. */
23
+ export interface Host {
24
+ readonly home: string;
25
+ has(command: string): boolean;
26
+ /** Combined output of a read-only command, empty when it fails. */
27
+ output(command: string, args: string[]): string;
28
+ /** Runs a cleaning command; throws when it fails. */
29
+ run(command: string, args: string[]): string;
30
+ }
31
+
32
+ const HOST: Host = {
33
+ home: os.homedir(),
34
+ has: command => spawnSync("sh", ["-c", 'command -v "$1"', "sh", command], { encoding: "utf8" }).status === 0,
35
+ output: (command, args) => {
36
+ const result = spawnSync(command, args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
37
+ return `${result.stdout ?? ""}${result.stderr ?? ""}`;
38
+ },
39
+ run: (command, args) => {
40
+ const result = spawnSync(command, args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
41
+ if (result.status !== 0) throw new Error(`${command} ${args.join(" ")} exited ${result.status}: ${(result.stderr ?? "").trim().split("\n").pop()}`);
42
+ return (result.stdout ?? "").trim();
43
+ },
44
+ };
45
+
46
+ /** Running installs read the package caches, so those caches wait for them. */
47
+ // Matches the launcher forms too: `brew.rb`, `pnpm.cjs`, `npm-cli.js`, `yarn.js`.
48
+ // Options may come first (`bun --cwd /repo install`, `pnpm -C dir install`).
49
+ const OPTIONS = String.raw`(?:\s+-\S+(?:\s+[^\s-]\S*)?)*`;
50
+ // Anything that writes to a package cache: installs, updates, removals, and one-off runners.
51
+ const CACHE_WRITERS = "install|i|ci|add|update|up|upgrade|remove|rm|uninstall|reinstall|link|dedupe|fetch|x|dlx|exec";
52
+ export const INSTALLING = new RegExp(
53
+ String.raw`(^|[\s/])((bun|npm|npm-cli|pnpm|yarn|brew)(\.(?:c|m)?js|\.rb)?${OPTIONS}(\s+run\s+agent-tool\s+bun${OPTIONS})?\s+(${CACHE_WRITERS})|(bunx|npx|pnpx)(\.(?:c|m)?js)?)(\s|$)`,
54
+ );
55
+
56
+ /**
57
+ * DerivedData entries safe to delete: each project's build products and
58
+ * indexes. Keeps SourcePackages (Swift package clones someone may have
59
+ * edited), anything holding a repository, credentials, or a database, and
60
+ * everything when DerivedData itself is a symlink or a repository.
61
+ */
62
+ export function derivedDataRemovals(derived: string): string[] {
63
+ if (lstatSync(derived).isSymbolicLink() || isRepository(derived)) throw new Error(`${derived} is a symlink or a repository; clean it by hand`);
64
+ const keep = (entry: string, name: string) => name === "SourcePackages" || protectedName(name) || holdsProtected(entry, derived) !== undefined;
65
+ return readdirSync(derived, { withFileTypes: true }).flatMap(entry => projectRemovals(path.join(derived, entry.name), entry, keep));
66
+ }
67
+
68
+ /** What one DerivedData entry contributes: itself when it is a file, else its removable children. */
69
+ function projectRemovals(project: string, entry: Dirent, keep: (entry: string, name: string) => boolean): string[] {
70
+ if (!entry.isDirectory()) return keep(project, entry.name) ? [] : [project];
71
+ // A shared SourcePackages, a clone made straight into DerivedData, or a protected directory stays whole.
72
+ if (entry.name === "SourcePackages" || protectedName(entry.name) || isRepository(project)) return [];
73
+ const removals: string[] = [];
74
+ for (const child of readdirSync(project)) {
75
+ const entryPath = path.join(project, child);
76
+ // A package directory moved with -clonedSourcePackagesDirPath still holds clones.
77
+ if (!keep(entryPath, child)) removals.push(entryPath);
78
+ }
79
+ return removals;
80
+ }
81
+
82
+ type Guard = NonNullable<MachineItem["guard"]>;
83
+
84
+ /** Processes other than this one and its launchers, which `bunx ... space` itself would otherwise match as an install. */
85
+ function others(procs: Proc[], self = process.pid): Proc[] {
86
+ const mine = selfAndAncestors(procs, self);
87
+ return procs.filter(proc => !mine.has(proc.pid));
88
+ }
89
+
90
+ /** Package caches wait for any running install. */
91
+ const installing: Guard = list => {
92
+ const proc = list.find(candidate => INSTALLING.test(candidate.args));
93
+ return proc ? `an install is running (pid ${proc.pid})` : undefined;
94
+ };
95
+
96
+ /** DerivedData waits for Xcode builds. */
97
+ const building: Guard = list => {
98
+ const proc = list.find(candidate => candidate.name === "xcodebuild" || candidate.name === "Xcode");
99
+ return proc ? `${proc.name} is running (pid ${proc.pid})` : undefined;
100
+ };
101
+
102
+ /** A directory sized as a whole, when it exists. */
103
+ function dirItem(home: string, id: string, description: string, location: string, reportOnly: boolean, apply?: () => string, guard?: Guard): MachineItem[] {
104
+ if (!existsSync(location)) return [];
105
+ return [{ id, description: `${description} (${location.replace(home, "~")})`, reportOnly, bytes: measure([location]).get(location), apply, guard }];
106
+ }
107
+
108
+ /** Developer caches outside any repository, for `--machine`. */
109
+ export function machineItems(procs: Proc[], host: Host = HOST): MachineItem[] {
110
+ const { home } = host;
111
+ const items: MachineItem[] = [
112
+ ...derivedDataItem(home),
113
+ ...simulatorsItem(host),
114
+ ...homebrewItem(host),
115
+ ...packageCacheItems(host),
116
+ ...dirItem(
117
+ home,
118
+ "gradle-caches",
119
+ "Gradle caches; delete with Gradle stopped if Android builds can wait for a re-download",
120
+ path.join(home, ".gradle/caches"),
121
+ true,
122
+ ),
123
+ ...dirItem(home, "playwright-browsers", "Playwright browsers; old versions no project pins can go", path.join(home, "Library/Caches/ms-playwright"), true),
124
+ ...dirItem(
125
+ home,
126
+ "ios-device-support",
127
+ "iOS DeviceSupport; versions for devices no longer used can go",
128
+ path.join(home, "Library/Developer/Xcode/iOS DeviceSupport"),
129
+ true,
130
+ ),
131
+ ...dirItem(
132
+ home,
133
+ "simulator-devices",
134
+ "Simulator devices; `xcrun simctl erase` or delete ones no project uses",
135
+ path.join(home, "Library/Developer/CoreSimulator/Devices"),
136
+ true,
137
+ ),
138
+ ...snapshotsItem(host),
139
+ ...dockerItem(host),
140
+ ];
141
+ for (const item of items) item.skipped = item.guard?.(others(procs));
142
+ return items;
143
+ }
144
+
145
+ function derivedDataItem(home: string): MachineItem[] {
146
+ const derived = path.join(home, "Library/Developer/Xcode/DerivedData");
147
+ if (!existsSync(derived)) return [];
148
+ // A DerivedData that must not be touched sizes as nothing; applying it reports why.
149
+ let removable: string[] = [];
150
+ try {
151
+ removable = derivedDataRemovals(derived);
152
+ } catch {
153
+ /* reported by apply */
154
+ }
155
+ const sizes = measure(removable);
156
+ return [
157
+ {
158
+ id: "xcode-derived-data",
159
+ description: `Xcode DerivedData builds and indexes, keeping SourcePackages, repositories, and data files (${derived.replace(home, "~")})`,
160
+ reportOnly: false,
161
+ bytes: removable.reduce((sum, entry) => sum + (sizes.get(entry) ?? 0), 0),
162
+ // Recomputed at apply time: the tree may have changed since the report.
163
+ apply: () => {
164
+ for (const entry of derivedDataRemovals(derived)) rmSync(entry, { recursive: true, force: true });
165
+ return "cleaned";
166
+ },
167
+ guard: building,
168
+ },
169
+ ];
170
+ }
171
+
172
+ function simulatorsItem(host: Host): MachineItem[] {
173
+ if (!host.has("xcrun")) return [];
174
+ const listing = host.output("xcrun", ["simctl", "list", "devices", "unavailable"]);
175
+ const count = listing.split("\n").filter(line => /\(unavailable/.test(line)).length;
176
+ // Their app data returns if the runtime is reinstalled, so deleting them is the owner's call.
177
+ if (count === 0) return [];
178
+ return [
179
+ {
180
+ id: "unavailable-simulators",
181
+ description: `${count} simulators whose runtime is no longer installed; \`xcrun simctl delete unavailable\` removes them and their app data`,
182
+ reportOnly: true,
183
+ },
184
+ ];
185
+ }
186
+
187
+ function homebrewItem(host: Host): MachineItem[] {
188
+ const { has, run } = host;
189
+ if (!has("brew")) return [];
190
+ const match = /free approximately ([\d.]+)([KMGT]?B)/.exec(host.output("brew", ["cleanup", "-n"]));
191
+ const unit: Record<string, number> = { B: 1, KB: 1024, MB: 1024 ** 2, GB: 1024 ** 3, TB: 1024 ** 4 };
192
+ // brew cleanup removes downloads an install in progress is using.
193
+ if (!match) return [];
194
+ return [
195
+ {
196
+ id: "homebrew-cleanup",
197
+ description: "Old Homebrew versions and downloads (`brew cleanup`)",
198
+ reportOnly: false,
199
+ bytes: Number(match[1]) * unit[match[2]!]!,
200
+ apply: () => {
201
+ run("brew", ["cleanup"]);
202
+ return "cleaned";
203
+ },
204
+ guard: installing,
205
+ },
206
+ ];
207
+ }
208
+
209
+ /** The Bun, npm and pnpm caches, in that order. */
210
+ function packageCacheItems(host: Host): MachineItem[] {
211
+ const { home, has, run } = host;
212
+ const items: MachineItem[] = [];
213
+ if (has("bun")) {
214
+ const cache = host.output("bun", ["pm", "cache"]).trim().split("\n")[0];
215
+ if (cache) items.push(...dirItem(home, "bun-cache", "Bun install cache", cache, false, () => run("bun", ["pm", "cache", "rm"]) || "removed", installing));
216
+ }
217
+ if (has("npm")) {
218
+ items.push(
219
+ ...dirItem(
220
+ home,
221
+ "npm-cache",
222
+ "npm cache",
223
+ path.join(home, ".npm/_cacache"),
224
+ false,
225
+ () => {
226
+ run("npm", ["cache", "clean", "--force"]);
227
+ return "cleaned";
228
+ },
229
+ installing,
230
+ ),
231
+ );
232
+ }
233
+ if (has("pnpm")) {
234
+ items.push({
235
+ id: "pnpm-store",
236
+ description: "Packages no project references in the pnpm store (`pnpm store prune`)",
237
+ reportOnly: false,
238
+ apply: () => {
239
+ run("pnpm", ["store", "prune"]);
240
+ return "pruned";
241
+ },
242
+ guard: installing,
243
+ });
244
+ }
245
+ return items;
246
+ }
247
+
248
+ function snapshotsItem(host: Host): MachineItem[] {
249
+ if (!host.has("tmutil")) return [];
250
+ const snapshots = host
251
+ .output("tmutil", ["listlocalsnapshots", "/"])
252
+ .split("\n")
253
+ .filter(line => line.includes("com.apple")).length;
254
+ if (snapshots === 0) return [];
255
+ return [
256
+ {
257
+ id: "local-snapshots",
258
+ description: `${snapshots} Time Machine local snapshots hold deleted files' space until macOS thins them`,
259
+ reportOnly: true,
260
+ },
261
+ ];
262
+ }
263
+
264
+ function dockerItem(host: Host): MachineItem[] {
265
+ if (!host.has("docker")) return [];
266
+ return [
267
+ {
268
+ id: "docker",
269
+ description: "Docker images, containers, and volumes; `docker system df` sizes them, and pruning is the owner's call",
270
+ reportOnly: true,
271
+ },
272
+ ];
273
+ }
274
+
275
+ /** Why a guard holds its item back, given a fresh process list; a failure to list processes holds it back too. */
276
+ function guardReason(guard: NonNullable<MachineItem["guard"]>, discover: () => Proc[]): string | undefined {
277
+ try {
278
+ return guard(others(discover()));
279
+ } catch (error) {
280
+ return (error as Error).message;
281
+ }
282
+ }
283
+
284
+ /**
285
+ * Runs every machine item that is neither report-only nor waiting on a running
286
+ * process, listing processes afresh just before each guarded item.
287
+ * Returns the number that failed.
288
+ */
289
+ export function applyMachine(items: MachineItem[], discover: () => Proc[]): number {
290
+ let failures = 0;
291
+ for (const item of items) {
292
+ if (item.reportOnly || !item.apply) continue;
293
+ if (item.guard) item.skipped = guardReason(item.guard, discover);
294
+ if (item.skipped) continue;
295
+ try {
296
+ item.result = item.apply();
297
+ } catch (error) {
298
+ item.result = `failed: ${(error as Error).message}`;
299
+ failures++;
300
+ }
301
+ }
302
+ return failures;
303
+ }