@oficiallyakshay/trash-panda 0.0.0-stage → 0.1.0

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,491 @@
1
+ /**
2
+ * src/rebuildables.mjs — the cleanup kinds beyond Chrome copies, repo copies and
3
+ * scratch. Each kind and what proves a folder safe to remove:
4
+ *
5
+ * - rebuildable folders: a linked worktree's ignored `node_modules` or Swift
6
+ * `.build`, with no process or open file inside, no unfinished work, git
7
+ * tracking nothing in it, and the package file plus lockfile committed and
8
+ * unchanged. A worktree no app session owns goes only when space is low.
9
+ * - test folders: `<pid>-<name>` folders directly inside a listed directory,
10
+ * once that pid is gone and no file is open inside.
11
+ * - module caches: hash-named folders inside a listed directory that no
12
+ * repository links to, no lockfile hash names and no process uses. The
13
+ * folder is renamed aside and checked again before it is deleted.
14
+ * - uv cache: `uv cache prune` (never forced) when nothing holds the cache lock.
15
+ * - old Playwright builds: builds no installed playwright's browsers.json names.
16
+ * - stale worktree records: `git worktree prune` of records whose folder is gone.
17
+ *
18
+ * A listed folder or a folder inside it is never followed through a link. Any
19
+ * failed probe means keep. Every sweep returns
20
+ * `{ removed, kept, errors, bytes, skipped }`; `apply: false` deletes nothing.
21
+ */
22
+
23
+ import { execFile } from "node:child_process";
24
+ import { createHash } from "node:crypto";
25
+ import { existsSync, lstatSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync } from "node:fs";
26
+ import { homedir } from "node:os";
27
+ import { dirname, isAbsolute, join, resolve } from "node:path";
28
+ import { promisify } from "node:util";
29
+ import { duBytes, freeBytes, openFilePaths, removeDirectChild, stillGoes } from "./claude-leftovers.mjs";
30
+ import { LSOF_BIN, dirHasLiveCwd, liveCwds } from "./worktree-liveness.mjs";
31
+
32
+ const execFileP = promisify(execFile);
33
+
34
+ const empty = () => ({ removed: [], kept: [], errors: 0, bytes: 0, skipped: null });
35
+ const inside = (p, root) => p === root || p.startsWith(`${root}/`);
36
+ const LOCKFILES = ["package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml", "bun.lock", "bun.lockb"];
37
+ const ASIDE = ".trash-panda-aside-";
38
+
39
+ export const UV_CANDIDATES = [join(homedir(), ".local/bin/uv"), join(homedir(), ".cargo/bin/uv"), "/opt/homebrew/bin/uv", "/usr/local/bin/uv"];
40
+ export const PLAYWRIGHT_ROOT = join(homedir(), "Library/Caches/ms-playwright");
41
+
42
+ export function findUv({ existsSyncImpl = existsSync } = {}) {
43
+ return UV_CANDIDATES.find((p) => existsSyncImpl(p)) ?? null;
44
+ }
45
+
46
+ /** True while `pid` is a running process (a process we may not signal still counts). */
47
+ export function isAlive(pid) {
48
+ try {
49
+ process.kill(pid, 0);
50
+ return true;
51
+ } catch (e) {
52
+ return e.code === "EPERM";
53
+ }
54
+ }
55
+
56
+ async function git(args, execImpl) {
57
+ const { stdout } = await execImpl("git", args, { timeout: 60_000, maxBuffer: 64 * 1024 * 1024 });
58
+ return String(stdout ?? "").trim();
59
+ }
60
+
61
+ // Paths compared case-insensitively: APFS is, so two spellings are one folder.
62
+ function pathKeys(p) {
63
+ const keys = [String(p).replace(/\/+$/, "").toLowerCase()];
64
+ try {
65
+ keys.push(realpathSync(p).toLowerCase());
66
+ } catch {
67
+ // gone — the literal path still counts
68
+ }
69
+ return keys;
70
+ }
71
+
72
+ /** Why a listed folder is refused, or null: it must be an absolute, existing, real directory. */
73
+ function refuseListed(dir) {
74
+ if (typeof dir !== "string" || !isAbsolute(dir)) return "not an absolute path";
75
+ let st;
76
+ try {
77
+ st = lstatSync(dir);
78
+ } catch {
79
+ return "missing";
80
+ }
81
+ if (st.isSymbolicLink()) return "a link";
82
+ return st.isDirectory() ? null : "not a directory";
83
+ }
84
+
85
+ const refuseChild = (ent) => (ent.isSymbolicLink() ? "a link" : ent.isDirectory() ? null : "not a directory");
86
+
87
+ /**
88
+ * Size a candidate, and on apply re-check it and delete it. `item.reason` says
89
+ * why it goes; a reason to stay goes to `kept`, never a throw.
90
+ */
91
+ async function take(out, item, { realRoot, apply, execImpl, ...extra }) {
92
+ try {
93
+ const bytes = await duBytes(item.path, { execImpl });
94
+ if (apply) {
95
+ if (!(await stillGoes(item))) {
96
+ out.kept.push({ path: item.path, reason: "changed before delete", ...extra });
97
+ return;
98
+ }
99
+ await removeDirectChild(item.path, realRoot);
100
+ }
101
+ out.removed.push({ path: item.path, bytes, reason: item.reason, ...extra });
102
+ out.bytes += bytes;
103
+ } catch (e) {
104
+ out.kept.push({ path: item.path, reason: e.message, ...extra });
105
+ out.errors += 1;
106
+ }
107
+ }
108
+
109
+ // ── rebuildable folders ─────────────────────────────────────────────────────
110
+
111
+ const isOwned = (wt, owned) => pathKeys(wt).some((k) => owned.has(k));
112
+
113
+ async function rebuildVerdict({ wt, name, rec, owned, lowSpace, cwds, open, execImpl }) {
114
+ if (!Array.isArray(cwds) || !Array.isArray(open)) return "lsof failed";
115
+ const folder = join(wt, name);
116
+ const st = lstatSync(folder);
117
+ if (st.isSymbolicLink()) return "a link";
118
+ if (!st.isDirectory()) return "not a directory";
119
+ if (rec.locked) return "locked";
120
+ if (rec.prunable) return "registration only";
121
+ if (dirHasLiveCwd(cwds, wt) !== false || open.some((o) => inside(o, wt))) return "in use";
122
+ try {
123
+ if (await git(["-C", wt, "status", "--porcelain", "--untracked-files=all"], execImpl)) return "unfinished: local changes";
124
+ } catch {
125
+ return "unfinished: local changes";
126
+ }
127
+ try {
128
+ if ((await git(["-C", wt, "rev-list", "--count", "HEAD", "--not", "--remotes"], execImpl)) !== "0") return "unfinished: commits on no remote";
129
+ } catch {
130
+ return "unfinished: commits on no remote";
131
+ }
132
+ try {
133
+ await git(["-C", wt, "check-ignore", "-q", name], execImpl);
134
+ } catch {
135
+ return "not ignored by git";
136
+ }
137
+ try {
138
+ if (await git(["-C", wt, "ls-files", "--", name], execImpl)) return "git tracks files in it";
139
+ } catch {
140
+ return "git tracks files in it";
141
+ }
142
+ const files = name === "node_modules" ? ["package.json", LOCKFILES.find((f) => existsSync(join(wt, f))) ?? "no-lockfile"] : ["Package.swift", "Package.resolved"];
143
+ for (const f of files) {
144
+ try {
145
+ await git(["-C", wt, "ls-files", "--error-unmatch", "--", f], execImpl);
146
+ if (await git(["-C", wt, "status", "--porcelain", "--", f], execImpl)) throw new Error("changed");
147
+ } catch {
148
+ return "package file or lockfile not committed and unchanged";
149
+ }
150
+ }
151
+ if (!lowSpace && !isOwned(wt, owned)) return "no owner and space is not low";
152
+ return true;
153
+ }
154
+
155
+ export async function sweepRebuildables({ repos, listedPaths = [], cwds, openPaths, lowSpace = false, apply = false, execImpl = execFileP }) {
156
+ const out = empty();
157
+ if (!Array.isArray(cwds) || !Array.isArray(openPaths)) {
158
+ out.skipped = "lsof failed";
159
+ return out;
160
+ }
161
+ const owned = new Set(listedPaths.flatMap(pathKeys));
162
+ for (const repo of new Map(repos.map((r) => [r.realRepo, r])).values()) {
163
+ for (const rec of repo.records) {
164
+ let wt;
165
+ try {
166
+ wt = realpathSync(rec.path);
167
+ } catch {
168
+ continue;
169
+ }
170
+ if (wt === repo.realRepo) continue;
171
+ for (const name of ["node_modules", ".build"]) {
172
+ const path = join(wt, name);
173
+ try {
174
+ lstatSync(path);
175
+ } catch {
176
+ continue;
177
+ }
178
+ const verdict = (c, o) => rebuildVerdict({ wt, name, rec, owned, lowSpace, cwds: c, open: o, execImpl });
179
+ const first = await verdict(cwds, openPaths);
180
+ if (first !== true) {
181
+ out.kept.push({ path, reason: first, repo: repo.realRepo });
182
+ continue;
183
+ }
184
+ const check = async () => verdict(await liveCwds({ execImpl }), await openFilePaths({ execImpl }));
185
+ const reason = `can be rebuilt from its committed lockfile, and ${isOwned(wt, owned) ? "the app owns its worktree" : "space is low"}`;
186
+ await take(out, { path, check, reason }, { realRoot: wt, apply, execImpl, repo: repo.realRepo });
187
+ }
188
+ }
189
+ }
190
+ return out;
191
+ }
192
+
193
+ // ── test folders ────────────────────────────────────────────────────────────
194
+
195
+ function testVerdict(path, pid, alive, open) {
196
+ if (!Array.isArray(open)) return "lsof failed";
197
+ if (alive(pid)) return `process ${pid} is running`;
198
+ return open.some((o) => inside(o, path)) ? "a process has a file open inside" : true;
199
+ }
200
+
201
+ export async function sweepTestFolders({ dirs, openPaths, apply = false, limit = Number.POSITIVE_INFINITY, alive = isAlive, execImpl = execFileP }) {
202
+ const out = empty();
203
+ if (!dirs?.length) return out;
204
+ if (!Array.isArray(openPaths)) {
205
+ out.skipped = "lsof failed";
206
+ return out;
207
+ }
208
+ for (const dir of dirs) {
209
+ const refused = refuseListed(dir);
210
+ if (refused) {
211
+ out.kept.push({ path: dir, reason: refused });
212
+ continue;
213
+ }
214
+ const realDir = realpathSync(dir);
215
+ for (const ent of readdirSync(realDir, { withFileTypes: true })) {
216
+ const m = /^(\d+)-./.exec(ent.name);
217
+ if (!m) continue;
218
+ const path = join(realDir, ent.name);
219
+ const pid = Number(m[1]);
220
+ const verdict = refuseChild(ent) ?? testVerdict(path, pid, alive, openPaths);
221
+ if (verdict !== true) {
222
+ out.kept.push({ path, reason: verdict });
223
+ } else if (out.removed.length >= limit) {
224
+ out.kept.push({ path, reason: "over this run's limit" });
225
+ } else {
226
+ const check = async () => testVerdict(path, pid, alive, await openFilePaths({ execImpl }));
227
+ await take(out, { path, check, reason: `process ${pid} is gone, and no process has a file open inside` }, { realRoot: realDir, apply, execImpl });
228
+ }
229
+ }
230
+ }
231
+ return out;
232
+ }
233
+
234
+ // ── module caches ───────────────────────────────────────────────────────────
235
+
236
+ function cacheVerdict(name, orig, cur, paths, cwds, open) {
237
+ if (!Array.isArray(cwds) || !Array.isArray(open)) return "lsof failed";
238
+ for (const p of paths) {
239
+ const link = join(p, "node_modules");
240
+ try {
241
+ if (lstatSync(link).isSymbolicLink() && inside(resolve(dirname(link), readlinkSync(link)), orig)) return "a repository links to it";
242
+ } catch {
243
+ // no node_modules there
244
+ }
245
+ }
246
+ for (const p of paths) {
247
+ for (const f of LOCKFILES) {
248
+ try {
249
+ if (createHash("sha256").update(readFileSync(join(p, f))).digest("hex").startsWith(name.toLowerCase())) return "a repository's lockfile hash needs it";
250
+ } catch {
251
+ // no such lockfile
252
+ }
253
+ }
254
+ }
255
+ return dirHasLiveCwd(cwds, cur) !== false || open.some((o) => inside(o, cur)) ? "in use, or an install runs in it" : true;
256
+ }
257
+
258
+ export async function sweepModuleCaches({ dirs, repos, cwds, openPaths, apply = false, execImpl = execFileP }) {
259
+ const out = empty();
260
+ if (!dirs?.length) return out;
261
+ if (!repos.length) {
262
+ out.skipped = "no repositories visited, so any cache could still be in use";
263
+ return out;
264
+ }
265
+ if (!Array.isArray(cwds) || !Array.isArray(openPaths)) {
266
+ out.skipped = "lsof failed";
267
+ return out;
268
+ }
269
+ const paths = [...new Set(repos.flatMap((r) => r.records.map((x) => x.path)))];
270
+ for (const dir of dirs) {
271
+ const refused = refuseListed(dir);
272
+ if (refused) {
273
+ out.kept.push({ path: dir, reason: refused });
274
+ continue;
275
+ }
276
+ const realDir = realpathSync(dir);
277
+ const itemFor = (name, orig, cur) => ({
278
+ path: cur,
279
+ reason: "no repository links to it, no lockfile hash needs it, and nothing uses it",
280
+ check: async () => cacheVerdict(name, orig, cur, paths, await liveCwds({ execImpl }), await openFilePaths({ execImpl })),
281
+ });
282
+ // A stopped run may have left a cache aside: put it back, or finish removing it.
283
+ for (const ent of readdirSync(realDir, { withFileTypes: true })) {
284
+ const hash = ent.name.startsWith(ASIDE) ? ent.name.slice(ASIDE.length) : "";
285
+ const m = /^[0-9a-f]{8,}$/i.test(hash) ? [ent.name, hash] : null;
286
+ if (!m) continue;
287
+ const aside = join(realDir, ent.name);
288
+ const orig = join(realDir, m[1]);
289
+ const refusedChild = refuseChild(ent);
290
+ if (refusedChild) {
291
+ out.kept.push({ path: aside, reason: refusedChild });
292
+ } else if (cacheVerdict(m[1], orig, aside, paths, cwds, openPaths) === true) {
293
+ await take(out, itemFor(m[1], orig, aside), { realRoot: realDir, apply, execImpl, restored: false });
294
+ } else if (existsSync(orig)) {
295
+ out.kept.push({ path: aside, reason: "a stopped run left it aside; its name is taken" });
296
+ } else {
297
+ if (apply) renameSync(aside, orig);
298
+ out.kept.push({ path: orig, reason: apply ? "a stopped run left it aside; put back" : "a stopped run left it aside; would be put back" });
299
+ }
300
+ }
301
+ for (const ent of readdirSync(realDir, { withFileTypes: true })) {
302
+ if (!/^[0-9a-f]{8,}$/i.test(ent.name)) continue;
303
+ const orig = join(realDir, ent.name);
304
+ const refusedChild = refuseChild(ent);
305
+ if (refusedChild) {
306
+ out.kept.push({ path: orig, reason: refusedChild });
307
+ continue;
308
+ }
309
+ try {
310
+ if (!lstatSync(join(orig, "node_modules")).isDirectory()) continue;
311
+ } catch {
312
+ continue;
313
+ }
314
+ const verdict = cacheVerdict(ent.name, orig, orig, paths, cwds, openPaths);
315
+ if (verdict !== true) {
316
+ out.kept.push({ path: orig, reason: verdict });
317
+ } else if (!apply) {
318
+ await take(out, itemFor(ent.name, orig, orig), { realRoot: realDir, apply, execImpl });
319
+ } else {
320
+ await removeAside(out, ent.name, orig, realDir, itemFor, execImpl);
321
+ }
322
+ }
323
+ }
324
+ return out;
325
+ }
326
+
327
+ /** Rename a cache aside, check it again, then delete it; put it back when the check fails. */
328
+ async function removeAside(out, name, orig, realDir, itemFor, execImpl) {
329
+ const aside = join(realDir, `${ASIDE}${name}`);
330
+ try {
331
+ const bytes = await duBytes(orig, { execImpl });
332
+ renameSync(orig, aside);
333
+ const item = itemFor(name, orig, aside);
334
+ if (!(await stillGoes(item))) {
335
+ renameSync(aside, orig);
336
+ out.kept.push({ path: orig, reason: "changed during the delete, put back" });
337
+ return;
338
+ }
339
+ await removeDirectChild(aside, realDir);
340
+ out.removed.push({ path: orig, bytes, reason: item.reason });
341
+ out.bytes += bytes;
342
+ } catch (e) {
343
+ out.kept.push({ path: orig, reason: e.message });
344
+ out.errors += 1;
345
+ }
346
+ }
347
+
348
+ // ── uv cache ────────────────────────────────────────────────────────────────
349
+
350
+ function parseLockHolders(stdout) {
351
+ const holders = [];
352
+ for (const line of String(stdout ?? "").split("\n")) {
353
+ if (line.startsWith("p")) holders.push({ pid: line.slice(1), command: "" });
354
+ else if (line.startsWith("c") && holders.length) holders.at(-1).command = line.slice(1);
355
+ }
356
+ return holders;
357
+ }
358
+
359
+ export async function pruneUvCache({ uvBin, apply = false, execImpl = execFileP }) {
360
+ const out = empty();
361
+ if (!uvBin) {
362
+ out.skipped = "uv not found";
363
+ return out;
364
+ }
365
+ let cacheDir;
366
+ try {
367
+ cacheDir = String((await execImpl(uvBin, ["cache", "dir"], { timeout: 60_000 })).stdout).trim();
368
+ if (!cacheDir) throw new Error("empty");
369
+ } catch {
370
+ out.skipped = "uv cache dir failed";
371
+ return out;
372
+ }
373
+ let lsofOut;
374
+ try {
375
+ lsofOut = (await execImpl(LSOF_BIN, ["-n", "-P", "-w", "-F", "pc", join(cacheDir, ".lock")], { timeout: 30_000 })).stdout;
376
+ } catch (e) {
377
+ // lsof exits 1 with no output when nobody holds the file
378
+ lsofOut = e?.stdout;
379
+ }
380
+ const holders = parseLockHolders(lsofOut);
381
+ if (holders.length) {
382
+ out.holders = holders;
383
+ out.skipped = `cache lock held by ${holders.map((h) => `${h.pid} ${h.command}`).join(", ")}; a long-running server installed with uv tool install holds no cache lock`;
384
+ return out;
385
+ }
386
+ const reason = "unused downloads are pruned, and no process holds the cache lock";
387
+ if (!apply) {
388
+ out.wouldPrune = true;
389
+ // Only a prune measures it.
390
+ out.removed.push({ path: cacheDir, bytes: null, reason });
391
+ return out;
392
+ }
393
+ const before = freeBytes(cacheDir);
394
+ try {
395
+ await execImpl(uvBin, ["cache", "prune"], { timeout: 600_000 });
396
+ } catch {
397
+ out.kept.push({ path: cacheDir, reason: "uv cache prune failed" });
398
+ out.errors += 1;
399
+ return out;
400
+ }
401
+ const after = freeBytes(cacheDir);
402
+ const gain = before === null || after === null ? 0 : Math.max(after - before, 0);
403
+ out.removed.push({ path: cacheDir, bytes: gain, reason, measured: true });
404
+ out.bytes += gain;
405
+ return out;
406
+ }
407
+
408
+ // ── old Playwright builds ───────────────────────────────────────────────────
409
+
410
+ export async function sweepPlaywright({ root, repos = [], openPaths, apply = false, execImpl = execFileP }) {
411
+ const out = empty();
412
+ if (!root || !existsSync(root)) return out;
413
+ const realRoot = realpathSync(root);
414
+ const needed = new Set();
415
+ const named = new Set();
416
+ let found = 0;
417
+ // false when the file exists but cannot be read
418
+ const addBrowsers = (file) => {
419
+ if (!existsSync(file)) return true;
420
+ try {
421
+ for (const b of JSON.parse(readFileSync(file, "utf8")).browsers) {
422
+ const prefix = String(b.name).replace(/-/g, "_");
423
+ named.add(prefix);
424
+ needed.add(`${prefix}-${b.revision}`);
425
+ }
426
+ } catch {
427
+ return false;
428
+ }
429
+ found += 1;
430
+ return true;
431
+ };
432
+ let links = [];
433
+ try {
434
+ links = readdirSync(join(realRoot, ".links")).map((f) => readFileSync(join(realRoot, ".links", f), "utf8").trim());
435
+ } catch {
436
+ // no links folder
437
+ }
438
+ const folders = [...links.filter((p) => existsSync(p)), ...repos.flatMap((r) => r.records.map((x) => join(x.path, "node_modules", "playwright-core")))];
439
+ for (const folder of folders) {
440
+ if (!addBrowsers(join(folder, "browsers.json"))) {
441
+ out.skipped = "an installed playwright could not be read";
442
+ return out;
443
+ }
444
+ }
445
+ if (!found) {
446
+ out.skipped = "no installed playwright found";
447
+ return out;
448
+ }
449
+ if (!Array.isArray(openPaths)) {
450
+ out.skipped = "lsof failed";
451
+ return out;
452
+ }
453
+ const verdict = (path, name, open) => {
454
+ if (!Array.isArray(open)) return "lsof failed";
455
+ if (needed.has(name)) return "needed by an installed playwright";
456
+ return open.some((o) => inside(o, path)) ? "in use" : true;
457
+ };
458
+ for (const ent of readdirSync(realRoot, { withFileTypes: true })) {
459
+ const m = !ent.name.startsWith(".") && ent.isDirectory() ? /^([a-z_]+)-(\d+)$/.exec(ent.name) : null;
460
+ if (!m || !named.has(m[1])) continue;
461
+ const path = join(realRoot, ent.name);
462
+ const first = verdict(path, ent.name, openPaths);
463
+ if (first !== true) {
464
+ out.kept.push({ path, reason: first });
465
+ continue;
466
+ }
467
+ const check = async () => verdict(path, ent.name, await openFilePaths({ execImpl }));
468
+ await take(out, { path, check, reason: "no installed Playwright needs it, and no process has a file open inside" }, { realRoot, apply, execImpl });
469
+ }
470
+ return out;
471
+ }
472
+
473
+ // ── stale worktree records ──────────────────────────────────────────────────
474
+
475
+ export async function pruneWorktreeRecords({ repos, apply = false, execImpl = execFileP }) {
476
+ const out = empty();
477
+ for (const { realRepo } of new Map(repos.map((r) => [r.realRepo, r])).values()) {
478
+ try {
479
+ // git prints the verbose lines on stderr
480
+ const { stdout, stderr } = await execImpl("git", ["-C", realRepo, "worktree", "prune", ...(apply ? [] : ["--dry-run"]), "--verbose"], { timeout: 60_000 });
481
+ for (const m of `${stdout ?? ""}\n${stderr ?? ""}`.matchAll(/^Removing worktrees\/([^:\n]+): *(.*)/gm)) {
482
+ // git's own reason; nothing measures a record
483
+ out.removed.push({ path: join(realRepo, ".git/worktrees", m[1]), bytes: null, reason: m[2], repo: realRepo });
484
+ }
485
+ } catch {
486
+ out.kept.push({ path: realRepo, reason: "git worktree prune failed", repo: realRepo });
487
+ out.errors += 1;
488
+ }
489
+ }
490
+ return out;
491
+ }