@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.
package/src/setup.mjs ADDED
@@ -0,0 +1,428 @@
1
+ /**
2
+ * src/setup.mjs — the one-time wiring: a scheduled job, a session-start hook,
3
+ * and shared dependency folders for repos that can safely use them; and,
4
+ * apart from them, the Mac app's login item (`app on|off`).
5
+ *
6
+ * `setup` changes only what it names and writes down what it created in
7
+ * `<dir>/setup.json`; `remove` puts back exactly that. Nothing here is run by
8
+ * the cleanup itself, and every outside effect (launchctl, the live file) is
9
+ * injected so a test never touches the real machine.
10
+ */
11
+
12
+ import { execFileSync } from "node:child_process";
13
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
14
+ import { dirname, join } from "node:path";
15
+ import { readWorktreeRegistry } from "./claude-leftovers.mjs";
16
+ import { APP_NAME } from "./metrics.mjs";
17
+ import { readSettings, settingsPath } from "./settings.mjs";
18
+ import { dirHasLiveCwd, liveCwds } from "./worktree-liveness.mjs";
19
+
20
+ export const LABEL = "io.github.trash-panda.tick";
21
+ const JOB_PATH = "/usr/bin:/bin:/usr/sbin:/sbin";
22
+ // Runs with $0 = node and $1 = script; quietly nothing when either is gone.
23
+ const JOB_SCRIPT = '[ -x "$0" ] && [ -f "$1" ] || exit 0; exec "$0" "$1" tick';
24
+ const HOOK_TAIL = " session-start; exit 0";
25
+ const OUR_SCRIPT_RE = /claude-leftovers-cleanup\.mjs'$/;
26
+ const REGISTRY_REL = "Library/Application Support/Claude/git-worktrees.json";
27
+ const LOCKFILES = ["package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml", "bun.lock", "bun.lockb"];
28
+ const WANTED = ["node_modules"];
29
+
30
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
31
+ const quote = (s) => `'${String(s).replaceAll("'", "'\\''")}'`;
32
+ const xml = (s) => String(s).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
33
+ const jsonText = (v) => `${JSON.stringify(v, null, 2)}\n`;
34
+ export const plistPath = (home) => join(home, "Library", "LaunchAgents", `${LABEL}.plist`);
35
+ // The Mac app's login item: its own file, apart from the engine's job.
36
+ export const APP_LABEL = "io.github.trash-panda.app";
37
+ export const appPlistPath = (home) => join(home, "Library", "LaunchAgents", `${APP_LABEL}.plist`);
38
+
39
+ function readText(path) {
40
+ try {
41
+ return readFileSync(path, "utf8");
42
+ } catch {
43
+ return null;
44
+ }
45
+ }
46
+
47
+ function readJson(path) {
48
+ try {
49
+ return JSON.parse(readFileSync(path, "utf8"));
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
54
+
55
+ /** Write `text` to `path` (parent folders made) unless it is already there; true when it changed. */
56
+ function writeIfDifferent(path, text) {
57
+ if (readText(path) === text) return false;
58
+ mkdirSync(dirname(path), { recursive: true });
59
+ writeFileSync(path, text);
60
+ return true;
61
+ }
62
+
63
+ /** The job plist text: one tick every `tickSec`, launchd's own PATH, never kept alive. */
64
+ export function jobPlist({ nodePath, scriptPath, tickSec, dir }) {
65
+ const args = ["/bin/sh", "-c", JOB_SCRIPT, nodePath, scriptPath].map((a) => `\t\t<string>${xml(a)}</string>`).join("\n");
66
+ return `<?xml version="1.0" encoding="UTF-8"?>
67
+ <plist version="1.0">
68
+ <dict>
69
+ <key>Label</key>
70
+ <string>${LABEL}</string>
71
+ <key>ProgramArguments</key>
72
+ <array>
73
+ ${args}
74
+ </array>
75
+ <key>StartInterval</key>
76
+ <integer>${tickSec}</integer>
77
+ <key>EnvironmentVariables</key>
78
+ <dict>
79
+ <key>PATH</key>
80
+ <string>${JOB_PATH}</string>
81
+ </dict>
82
+ <key>ProcessType</key>
83
+ <string>Background</string>
84
+ <key>StandardOutPath</key>
85
+ <string>${xml(join(dir, "tick.log"))}</string>
86
+ <key>StandardErrorPath</key>
87
+ <string>${xml(join(dir, "tick.log"))}</string>
88
+ </dict>
89
+ </plist>
90
+ `;
91
+ }
92
+
93
+ /** The session-start hook command; ends quietly (exit 0) when node or the script is gone. */
94
+ export const hookCommand = (nodePath, scriptPath) => `[ -x ${quote(nodePath)} ] && [ -f ${quote(scriptPath)} ] && ${quote(nodePath)} ${quote(scriptPath)}${HOOK_TAIL}`;
95
+
96
+ const isOurs = (h) => isObject(h) && typeof h.command === "string" && h.command.endsWith(HOOK_TAIL) && OUR_SCRIPT_RE.test(h.command.slice(0, -HOOK_TAIL.length));
97
+
98
+ /** The real launchctl; `execImpl` is only swapped by a test. */
99
+ export function defaultLaunchctl(args, execImpl = execFileSync) {
100
+ execImpl("/bin/launchctl", args, { stdio: "ignore" });
101
+ }
102
+
103
+ /** Rebuild the live file through src/triggers.mjs; a failure there never fails setup. */
104
+ export async function defaultRefreshLive(opts, importImpl = () => import("./triggers.mjs")) {
105
+ try {
106
+ const { refreshLive } = await importImpl();
107
+ await refreshLive(opts);
108
+ } catch {
109
+ // the live file is a convenience; the next tick rebuilds it
110
+ }
111
+ }
112
+
113
+ /** `{ obj, problem }` for Claude's settings file: obj null when missing, problem when it is not safe to edit. */
114
+ function readClaude(path) {
115
+ const text = readText(path);
116
+ if (text === null) return { obj: null };
117
+ let obj;
118
+ try {
119
+ obj = JSON.parse(text);
120
+ } catch {
121
+ return { problem: `${path} is not valid JSON; left alone` };
122
+ }
123
+ if (!isObject(obj) || (obj.hooks !== undefined && !isObject(obj.hooks)) || (obj.hooks?.SessionStart !== undefined && !Array.isArray(obj.hooks.SessionStart))) {
124
+ return { problem: `${path} has an unexpected shape; left alone` };
125
+ }
126
+ return { obj };
127
+ }
128
+
129
+ /** Add or refresh our SessionStart entry in `obj`; `{ changed, created }` says what was made. */
130
+ function addHook(obj, command) {
131
+ const created = { hooks: false, sessionStart: false };
132
+ if (obj.hooks === undefined) {
133
+ obj.hooks = {};
134
+ created.hooks = true;
135
+ }
136
+ if (obj.hooks.SessionStart === undefined) {
137
+ obj.hooks.SessionStart = [];
138
+ created.sessionStart = true;
139
+ }
140
+ const ours = obj.hooks.SessionStart.flatMap((entry) => (isObject(entry) && Array.isArray(entry.hooks) ? entry.hooks : [])).filter(isOurs);
141
+ if (!ours.length) {
142
+ obj.hooks.SessionStart.push({ hooks: [{ type: "command", command }] });
143
+ return { changed: true, created };
144
+ }
145
+ const stale = ours.filter((h) => h.command !== command);
146
+ for (const h of stale) h.command = command;
147
+ return { changed: stale.length > 0, created };
148
+ }
149
+
150
+ /** Take our entry out of `obj`, and the keys setup made when now empty; true when anything went. */
151
+ function removeHook(obj, created) {
152
+ const list = obj.hooks?.SessionStart;
153
+ if (!Array.isArray(list)) return false;
154
+ let changed = false;
155
+ for (let i = list.length - 1; i >= 0; i--) {
156
+ const entry = list[i];
157
+ if (!isObject(entry) || !Array.isArray(entry.hooks)) continue;
158
+ const keep = entry.hooks.filter((h) => !isOurs(h));
159
+ if (keep.length === entry.hooks.length) continue;
160
+ changed = true;
161
+ if (keep.length) entry.hooks = keep;
162
+ else list.splice(i, 1);
163
+ }
164
+ if (changed && !list.length && created.sessionStart) delete obj.hooks.SessionStart;
165
+ if (changed && !Object.keys(obj.hooks).length && created.hooks) delete obj.hooks;
166
+ return changed;
167
+ }
168
+
169
+ /** The reason a repo may not share node_modules, or null when every check passes. */
170
+ function repoReason(repo, { cwds, launchAgentsDir, execImpl }) {
171
+ let real;
172
+ try {
173
+ real = realpathSync(repo);
174
+ } catch {
175
+ return "repo folder is missing";
176
+ }
177
+ const tracked = (names) => {
178
+ try {
179
+ return execImpl("git", ["ls-files", "--", ...names], { cwd: real, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).split("\n");
180
+ } catch {
181
+ return [];
182
+ }
183
+ };
184
+ if (!tracked(["package.json"]).includes("package.json")) return "package.json is not committed";
185
+ if (!tracked(LOCKFILES).some((f) => LOCKFILES.includes(f))) return "no lockfile is committed";
186
+ let modulesOk = false;
187
+ try {
188
+ modulesOk = lstatSync(join(real, "node_modules")).isDirectory();
189
+ } catch {
190
+ // no folder
191
+ }
192
+ if (!modulesOk) return "node_modules is not a real folder";
193
+ let ignore = "";
194
+ try {
195
+ ignore = execImpl("git", ["show", "HEAD:.gitignore"], { cwd: real, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
196
+ } catch {
197
+ // no committed .gitignore
198
+ }
199
+ if (!ignore.split("\n").some((l) => l.trim() === "node_modules" || l.trim() === "/node_modules")) return "the committed .gitignore has no node_modules line that ignores a link";
200
+ if (!Array.isArray(cwds)) return "cannot tell which sessions are open";
201
+ const worktrees = [join(repo, ".claude", "worktrees"), join(real, ".claude", "worktrees")];
202
+ const outside = cwds.filter((c) => !worktrees.some((w) => c === w || c.startsWith(`${w}/`)));
203
+ if (dirHasLiveCwd(outside, repo) || dirHasLiveCwd(outside, real)) return "a session is open in the main checkout";
204
+ let agents = [];
205
+ try {
206
+ agents = readdirSync(launchAgentsDir).filter((f) => f !== `${LABEL}.plist`);
207
+ } catch {
208
+ // no LaunchAgents folder
209
+ }
210
+ for (const f of agents) {
211
+ const text = readText(join(launchAgentsDir, f)) ?? "";
212
+ if (text.includes(repo) || text.includes(real)) return `a LaunchAgents file (${f}) names this repo`;
213
+ }
214
+ return null;
215
+ }
216
+
217
+ /**
218
+ * Link node_modules for each repo that passes every check. Returns
219
+ * `{ set: [{ repo, createdFile, createdWorktree }], skipped: [{ repo, reason }] }`.
220
+ */
221
+ export async function sharedPackages({ home, repos = [], cwds, launchAgentsDir = join(home, "Library", "LaunchAgents"), execImpl = execFileSync }) {
222
+ const reg = readWorktreeRegistry(join(home, REGISTRY_REL));
223
+ const fromRegistry = reg.ok ? reg.entries.map((e) => e.baseRepo).filter((r) => typeof r === "string") : [];
224
+ const all = [...new Set([...fromRegistry, ...repos])];
225
+ const live = cwds !== undefined ? cwds : all.length ? await liveCwds() : null;
226
+ const out = { set: [], skipped: [] };
227
+ for (const repo of all) {
228
+ const skip = (reason) => out.skipped.push({ repo, reason });
229
+ const reason = repoReason(repo, { cwds: live, launchAgentsDir, execImpl });
230
+ if (reason) {
231
+ skip(reason);
232
+ continue;
233
+ }
234
+ const file = join(realpathSync(repo), ".claude", "settings.local.json");
235
+ const text = readText(file);
236
+ let obj = {};
237
+ if (text !== null) {
238
+ try {
239
+ obj = JSON.parse(text);
240
+ } catch {
241
+ obj = null;
242
+ }
243
+ if (!isObject(obj)) {
244
+ skip(`${file} is not valid JSON; left alone`);
245
+ continue;
246
+ }
247
+ }
248
+ if (obj.worktree !== undefined && !isObject(obj.worktree)) {
249
+ skip(`worktree in ${file} is not an object; left alone`);
250
+ continue;
251
+ }
252
+ if (Object.hasOwn(obj.worktree ?? {}, "symlinkDirectories")) {
253
+ skip("symlinkDirectories is already set; left alone");
254
+ continue;
255
+ }
256
+ const createdWorktree = obj.worktree === undefined;
257
+ obj.worktree = { ...obj.worktree, symlinkDirectories: [...WANTED] };
258
+ writeIfDifferent(file, jsonText(obj));
259
+ out.set.push({ repo, createdFile: text === null, createdWorktree });
260
+ }
261
+ return out;
262
+ }
263
+
264
+ /** Put back what setup set in each repo: only the key, only while it is still ["node_modules"]. */
265
+ function undoShared(records) {
266
+ let changed = false;
267
+ for (const rec of records) {
268
+ const file = join(rec.repo, ".claude", "settings.local.json");
269
+ let obj;
270
+ try {
271
+ obj = JSON.parse(readFileSync(file, "utf8"));
272
+ } catch {
273
+ continue;
274
+ }
275
+ if (JSON.stringify(obj?.worktree?.symlinkDirectories) !== JSON.stringify(WANTED)) continue;
276
+ delete obj.worktree.symlinkDirectories;
277
+ if (rec.createdWorktree && !Object.keys(obj.worktree).length) delete obj.worktree;
278
+ if (rec.createdFile && !Object.keys(obj).length) rmSync(file);
279
+ else writeFileSync(file, jsonText(obj));
280
+ changed = true;
281
+ }
282
+ return changed;
283
+ }
284
+
285
+ const refuse = (problems) => ({ ok: false, changed: false, problems });
286
+
287
+ /** Wire the job, the hook and the shared packages; `{ ok, changed, problems }`. */
288
+ export async function setup({ home, dir, nodePath = process.execPath, scriptPath, uid = process.getuid(), launchctl = defaultLaunchctl, tickSec, refreshLiveImpl = defaultRefreshLive, repos, cwds, execImpl, launchAgentsDir }) {
289
+ const claudePath = join(home, ".claude", "settings.json");
290
+ const claude = readClaude(claudePath);
291
+ if (claude.problem) return refuse([claude.problem]);
292
+ const plist = plistPath(home);
293
+ const want = jobPlist({ nodePath, scriptPath, tickSec: tickSec ?? readSettings(settingsPath(dir)).settings.tickSec, dir });
294
+ const old = readText(plist);
295
+ let changed = false;
296
+ if (old !== want) {
297
+ mkdirSync(dirname(plist), { recursive: true });
298
+ writeFileSync(plist, want);
299
+ try {
300
+ await launchctl(["bootout", `gui/${uid}/${LABEL}`]);
301
+ } catch {
302
+ // not loaded yet
303
+ }
304
+ try {
305
+ await launchctl(["bootstrap", `gui/${uid}`, plist]);
306
+ } catch (e) {
307
+ if (old === null) rmSync(plist);
308
+ else writeFileSync(plist, old);
309
+ return refuse([`launchctl bootstrap failed: ${e.message}`]);
310
+ }
311
+ changed = true;
312
+ }
313
+ // Start in preview; an existing settings file is never touched.
314
+ if (!existsSync(settingsPath(dir))) changed = writeIfDifferent(settingsPath(dir), '{"preview": true}\n') || changed;
315
+
316
+ const obj = claude.obj ?? {};
317
+ const hook = addHook(obj, hookCommand(nodePath, scriptPath));
318
+ if (hook.changed) {
319
+ writeIfDifferent(claudePath, jsonText(obj));
320
+ changed = true;
321
+ }
322
+
323
+ const shared = await sharedPackages({ home, repos, cwds, launchAgentsDir, execImpl });
324
+ const setupFile = join(dir, "setup.json");
325
+ const prevRaw = readJson(setupFile);
326
+ const prev = isObject(prevRaw) ? prevRaw : {};
327
+ const was = isObject(prev.created) ? prev.created : {};
328
+ const kept = Array.isArray(prev.sharedPackages) ? prev.sharedPackages : [];
329
+ const record = {
330
+ format: 1,
331
+ command: [nodePath, scriptPath],
332
+ plist,
333
+ created: {
334
+ file: Boolean(was.file) || claude.obj === null,
335
+ hooks: Boolean(was.hooks) || hook.created.hooks,
336
+ sessionStart: Boolean(was.sessionStart) || hook.created.sessionStart,
337
+ },
338
+ sharedPackages: [...kept, ...shared.set.filter((s) => !kept.some((k) => k.repo === s.repo))],
339
+ };
340
+ if (writeIfDifferent(setupFile, jsonText(record))) changed = true;
341
+ if (changed) await refreshLiveImpl({ dir });
342
+ return { ok: true, changed, problems: [] };
343
+ }
344
+
345
+ /** Whether the job and the hook are there: `{ job: { installed, loaded }, hook: { installed } }`. Reads only. */
346
+ export function wiring({ home, uid, launchctl }) {
347
+ let loaded = true;
348
+ try {
349
+ launchctl(["print", `gui/${uid}/${LABEL}`]);
350
+ } catch {
351
+ loaded = false;
352
+ }
353
+ const { obj } = readClaude(join(home, ".claude", "settings.json"));
354
+ const entries = (obj?.hooks?.SessionStart ?? []).flatMap((entry) => (isObject(entry) && Array.isArray(entry.hooks) ? entry.hooks : []));
355
+ return { job: { installed: existsSync(plistPath(home)), loaded }, hook: { installed: entries.some(isOurs) } };
356
+ }
357
+
358
+ /**
359
+ * Add (`on`) or remove (`off`) the Mac app's login item, a LaunchAgents file
360
+ * that opens the app at login; `{ ok, changed, problems }`. The engine's job,
361
+ * hook and settings are never touched, so the engine runs with the app off.
362
+ */
363
+ export async function appLogin({ on, home, uid = process.getuid(), launchctl = defaultLaunchctl, appDirs = ["/Applications", join(home, "Applications")] }) {
364
+ const item = appPlistPath(home);
365
+ if (!on) {
366
+ if (!existsSync(item)) return { ok: true, changed: false, problems: [] };
367
+ try {
368
+ await launchctl(["bootout", `gui/${uid}/${APP_LABEL}`]);
369
+ } catch {
370
+ // not loaded
371
+ }
372
+ rmSync(item);
373
+ return { ok: true, changed: true, problems: [] };
374
+ }
375
+ const app = appDirs.map((d) => join(d, APP_NAME)).find((p) => existsSync(p));
376
+ if (!app) return refuse([`The app is not installed: no ${APP_NAME} in ${appDirs.join(" or ")}`]);
377
+ const args = ["/usr/bin/open", "-a", app].map((a) => `\t\t<string>${xml(a)}</string>`).join("\n");
378
+ const text = `<?xml version="1.0" encoding="UTF-8"?>
379
+ <plist version="1.0">
380
+ <dict>
381
+ <key>Label</key>
382
+ <string>${APP_LABEL}</string>
383
+ <key>ProgramArguments</key>
384
+ <array>
385
+ ${args}
386
+ </array>
387
+ <key>RunAtLoad</key>
388
+ <true/>
389
+ <key>ProcessType</key>
390
+ <string>Interactive</string>
391
+ </dict>
392
+ </plist>
393
+ `;
394
+ return { ok: true, changed: writeIfDifferent(item, text), problems: [] };
395
+ }
396
+
397
+ /** Undo `setup`: the job, our hook entry, what setup created, the shared packages, setup.json. */
398
+ export async function remove({ home, dir, uid = process.getuid(), launchctl = defaultLaunchctl, refreshLiveImpl = defaultRefreshLive }) {
399
+ const claudePath = join(home, ".claude", "settings.json");
400
+ const claude = readClaude(claudePath);
401
+ if (claude.problem) return refuse([claude.problem]);
402
+ const setupFile = join(dir, "setup.json");
403
+ const saved = readJson(setupFile);
404
+ const created = isObject(saved?.created) ? saved.created : {};
405
+ let changed = false;
406
+ const plist = plistPath(home);
407
+ if (existsSync(plist)) {
408
+ try {
409
+ await launchctl(["bootout", `gui/${uid}/${LABEL}`]);
410
+ } catch {
411
+ // not loaded
412
+ }
413
+ rmSync(plist);
414
+ changed = true;
415
+ }
416
+ if (claude.obj && removeHook(claude.obj, created)) {
417
+ if (created.file && !Object.keys(claude.obj).length) rmSync(claudePath);
418
+ else writeFileSync(claudePath, jsonText(claude.obj));
419
+ changed = true;
420
+ }
421
+ if (undoShared(Array.isArray(saved?.sharedPackages) ? saved.sharedPackages : [])) changed = true;
422
+ if (existsSync(setupFile)) {
423
+ rmSync(setupFile);
424
+ changed = true;
425
+ }
426
+ if (changed) await refreshLiveImpl({ dir });
427
+ return { ok: true, changed, problems: [] };
428
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * src/temp-entries.mjs — old test entries left in the macOS user temp folder,
3
+ * a small batch at a time.
4
+ *
5
+ * An entry is a candidate only when its name starts with a prefix the person
6
+ * lists (`tempPrefixes`, empty by default) and the birth and last change of it
7
+ * and of everything inside it are older than `tempMinAgeDays`. A name cannot prove who made an entry,
8
+ * so age is one more guard here, on a list the person writes. An entry stays
9
+ * while a process has a file open in it or it holds a `<pid>-*` child of a
10
+ * running process.
11
+ *
12
+ * Each removed entry makes file events, so a pass goes in batches with a pause
13
+ * between them, and stops when the file-event service (fseventsd) uses too much
14
+ * memory. A probe that fails stops the pass and keeps the batch. The run lock is
15
+ * held for the whole pass, so a pass also ends after `tempMaxBatches` batches
16
+ * and the next run goes on.
17
+ *
18
+ * Counts only: no size is read and no entry is listed.
19
+ */
20
+
21
+ import { execFile } from "node:child_process";
22
+ import { lstatSync, readdirSync, realpathSync } from "node:fs";
23
+ import { unlink } from "node:fs/promises";
24
+ import { join } from "node:path";
25
+ import { setTimeout as sleepMs } from "node:timers/promises";
26
+ import { promisify } from "node:util";
27
+ import { openFilePaths, removeDirectChild } from "./claude-leftovers.mjs";
28
+ import { isAlive } from "./rebuildables.mjs";
29
+
30
+ const execFileP = promisify(execFile);
31
+ const DAY_MS = 86_400_000;
32
+ const MB_IN = { B: 1 / 1024 ** 2, K: 1 / 1024, M: 1, G: 1024 };
33
+
34
+ export const TOP_BIN = "/usr/bin/top";
35
+ // The only shape the swept folder may resolve to.
36
+ export const TEMP_ROOT_RE = /^\/private\/var\/folders\/[^/]{2}\/[^/]+\/T$/;
37
+
38
+ /** fseventsd's memory in MB, or null when it cannot be read. top counts compressed pages; ps does not. */
39
+ export async function fseventsdMb({ execImpl = execFileP } = {}) {
40
+ try {
41
+ const { stdout } = await execImpl(TOP_BIN, ["-l", "1", "-stats", "command,mem"], { maxBuffer: 16 * 1024 * 1024, timeout: 60_000 });
42
+ const m = /^fseventsd\s+([\d.]+)([BKMG])[+-]?\s*$/m.exec(String(stdout));
43
+ return m ? Math.round(Number(m[1]) * MB_IN[m[2]]) : null;
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+
49
+ /**
50
+ * True when the birth and last change of the entry, and of everything inside it,
51
+ * are all before `cutoff`: a write deep in a folder does not touch the folder's
52
+ * own times. No link is followed; a folder that cannot be read throws.
53
+ */
54
+ function isOld(path, cutoff) {
55
+ const st = lstatSync(path);
56
+ if (Math.max(st.birthtimeMs, st.ctimeMs, st.mtimeMs) >= cutoff) return false;
57
+ return !st.isDirectory() || readdirSync(path).every((n) => isOld(join(path, n), cutoff));
58
+ }
59
+
60
+ /** True when a folder holds a `<pid>-*` child of a running process. */
61
+ const holdsLiveChild = (path, alive) =>
62
+ readdirSync(path).some((n) => {
63
+ const m = /^(\d+)-./.exec(n);
64
+ return m !== null && alive(Number(m[1]));
65
+ });
66
+
67
+ /** The names directly inside `root` that a process has a file open in. */
68
+ function namesInUse(openPaths, root) {
69
+ const names = new Set();
70
+ for (const p of openPaths) if (p.startsWith(`${root}/`)) names.add(p.slice(root.length + 1).split("/")[0]);
71
+ return names;
72
+ }
73
+
74
+ export async function sweepTempEntries({ root, rootRe = TEMP_ROOT_RE, settings, apply = false, now = Date.now(), alive = isAlive, sleep = sleepMs, uid = process.getuid(), execImpl = execFileP }) {
75
+ const out = { removed: [], kept: [], errors: 0, bytes: 0, skipped: null, removedCount: 0, inUse: 0, fseventsdMb: [] };
76
+ const prefixes = settings.tempPrefixes;
77
+ if (!prefixes.length) return out;
78
+ if (!root) return { ...out, skipped: "no user temp folder" };
79
+ let realRoot;
80
+ let names;
81
+ try {
82
+ realRoot = realpathSync(root);
83
+ if (!rootRe.test(realRoot)) return { ...out, skipped: "not the user temp folder" };
84
+ if (lstatSync(realRoot).uid !== uid) return { ...out, skipped: "the temp folder is not owned by this user" };
85
+ names = readdirSync(realRoot);
86
+ } catch (e) {
87
+ return { ...out, skipped: `the temp folder is unreadable: ${e.code}` };
88
+ }
89
+ out.startEntries = names.length;
90
+ out.byPrefix = Object.fromEntries(prefixes.map((p) => [p, { matched: 0, removed: 0 }]));
91
+ const matches = [];
92
+ for (const name of names) {
93
+ const prefix = prefixes.find((p) => name.startsWith(p));
94
+ if (prefix === undefined) continue;
95
+ out.byPrefix[prefix].matched += 1;
96
+ matches.push({ path: join(realRoot, name), name, prefix });
97
+ }
98
+ const cutoff = now - settings.tempMinAgeDays * DAY_MS;
99
+ // A preview shows what one run would take, in one look and with no pause.
100
+ const [size, batches] = apply ? [settings.tempBatchSize, settings.tempMaxBatches] : [settings.tempBatchSize * settings.tempMaxBatches, 1];
101
+ let next = 0;
102
+ for (let n = 0; n < batches; n++) {
103
+ const batch = [];
104
+ while (batch.length < size && next < matches.length) {
105
+ const entry = matches[next++];
106
+ try {
107
+ if (isOld(entry.path, cutoff)) batch.push(entry);
108
+ } catch {
109
+ // gone since the listing
110
+ }
111
+ }
112
+ if (!batch.length) break;
113
+ if (n > 0) await sleep(settings.tempBatchPauseSec * 1000);
114
+ const mb = await fseventsdMb({ execImpl });
115
+ out.fseventsdMb.push(mb);
116
+ if (apply && (mb === null || mb > settings.tempStopFseventsdMb)) {
117
+ out.skipped = mb === null ? "stopped: the memory of fseventsd could not be read" : `stopped: fseventsd uses ${mb} MB, above ${settings.tempStopFseventsdMb} MB`;
118
+ break;
119
+ }
120
+ const open = await openFilePaths({ execImpl });
121
+ if (!Array.isArray(open)) {
122
+ out.skipped = "stopped: open files could not be checked";
123
+ break;
124
+ }
125
+ const used = namesInUse(open, realRoot);
126
+ for (const { path, name, prefix } of batch) {
127
+ try {
128
+ // Every check again: the pause may have changed it.
129
+ if (!isOld(path, cutoff)) continue;
130
+ const isDir = lstatSync(path).isDirectory();
131
+ if (used.has(name) || (isDir && holdsLiveChild(path, alive))) {
132
+ out.inUse += 1;
133
+ continue;
134
+ }
135
+ if (apply) await (isDir ? removeDirectChild(path, realRoot) : unlink(path));
136
+ out.byPrefix[prefix].removed += 1;
137
+ out.removedCount += 1;
138
+ } catch (e) {
139
+ if (e.code !== "ENOENT") out.errors += 1;
140
+ }
141
+ }
142
+ }
143
+ out.endEntries = readdirSync(realRoot).length;
144
+ return out;
145
+ }
146
+
147
+ /** The report of one pass, or "" when nothing was looked at. */
148
+ export function tempReport(t, verb) {
149
+ if (!t.byPrefix) return "";
150
+ const counts = Object.entries(t.byPrefix).map(([p, c]) => `${p} ${c.removed} of ${c.matched}`).join(", ");
151
+ const memory = t.fseventsdMb.map((mb) => mb ?? "unread").join(", ") || "not read";
152
+ return `. Old temp entries: ${verb} ${t.removedCount} (${counts}), ${t.inUse} in use, ${t.errors} failed; temp folder entries: ${t.startEntries} at the start, ${t.endEntries} at the end; fseventsd MB before each batch: ${memory}`;
153
+ }