benignswarm 0.12.93 → 0.12.95

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,891 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, lstatSync, readdirSync, readlinkSync, realpathSync, rmSync, statfsSync, statSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { basename, dirname, join, relative, resolve } from "node:path";
5
+ export const DEFAULT_CACHE_BUDGET_GB = 40;
6
+ export const DEFAULT_CACHE_FLOOR_PCT = 15;
7
+ const GIB = 1024 ** 3;
8
+ export const DEFAULT_BUILD_PROCESS_NAMES = [
9
+ "cargo",
10
+ "rustc",
11
+ "rustdoc",
12
+ "clippy-driver",
13
+ "cc1",
14
+ "cc1plus",
15
+ "ld",
16
+ "lld",
17
+ "ld.lld",
18
+ "rust-lld",
19
+ "clang",
20
+ "gcc",
21
+ "c++",
22
+ "swiftc",
23
+ "xcodebuild",
24
+ "make",
25
+ "ninja",
26
+ "cmake",
27
+ "sccache",
28
+ ];
29
+ const PROTECTED_HOME_SUBDIRS = [".b9s", ".bschat", ".codex", ".claude", ".gemini", ".ssh", ".gnupg"];
30
+ const CARGO_VAR_PREFIX = /^(?:\$CARGO_TARGET_DIR|\$\{CARGO_TARGET_DIR\})(?:\/(.*))?$/;
31
+ function realpathSafe(p) {
32
+ try {
33
+ return realpathSync(p);
34
+ }
35
+ catch {
36
+ return resolve(p);
37
+ }
38
+ }
39
+ function isSameOrChild(candidate, parent) {
40
+ const c = realpathSafe(candidate);
41
+ const p = realpathSafe(parent);
42
+ return c === p || c.startsWith(p === "/" ? "/" : `${p}/`);
43
+ }
44
+ function isSameOrParent(candidate, child) {
45
+ const c = realpathSafe(candidate);
46
+ const ch = realpathSafe(child);
47
+ return c === ch || ch.startsWith(c === "/" ? "/" : `${c}/`);
48
+ }
49
+ function entryExists(p) {
50
+ try {
51
+ lstatSync(p);
52
+ return true;
53
+ }
54
+ catch {
55
+ return false;
56
+ }
57
+ }
58
+ function isProtectedPathWithMode(candidate, ctx, includeParents) {
59
+ const res = realpathSafe(candidate);
60
+ const abs = resolve(candidate);
61
+ const effectiveWorkdir = ctx.workdir ?? join(ctx.homeDir, "bschat");
62
+ for (const probe of [res, abs]) {
63
+ if (probe === "/" || probe === realpathSafe(ctx.homeDir) || probe === resolve(ctx.homeDir))
64
+ return true;
65
+ const base = basename(probe).toLowerCase();
66
+ if (base === ".git" || base === "evidence")
67
+ return true;
68
+ if (probe.split("/").some((seg) => seg === ".git" || seg === "evidence"))
69
+ return true;
70
+ for (const sub of PROTECTED_HOME_SUBDIRS) {
71
+ const protectedPath = join(ctx.homeDir, sub);
72
+ if (isSameOrChild(probe, protectedPath) || (includeParents && isSameOrParent(probe, protectedPath)))
73
+ return true;
74
+ }
75
+ if (isSameOrChild(probe, effectiveWorkdir) || (includeParents && isSameOrParent(probe, effectiveWorkdir)))
76
+ return true;
77
+ for (const wt of ctx.protectedWorktrees) {
78
+ if (isSameOrChild(probe, wt) || (includeParents && isSameOrParent(probe, wt)))
79
+ return true;
80
+ }
81
+ if (entryExists(join(probe, ".git")))
82
+ return true;
83
+ }
84
+ return false;
85
+ }
86
+ /** Ensures we never clean worktrees, home config dirs, evidence dirs, or root directories even if misdeclared. */
87
+ export function isProtectedCachePath(candidate, homeDir, workdir, protectedWorktrees) {
88
+ return isProtectedPathWithMode(candidate, { homeDir, workdir, protectedWorktrees }, true);
89
+ }
90
+ /** Checks whether a specific entry (or symlink target) inside a cache directory is itself a Git checkout, worktree, or protected folder. */
91
+ function isDirectlyProtectedEntry(candidate, ctx) {
92
+ return isProtectedPathWithMode(candidate, ctx, false);
93
+ }
94
+ /** Walks a directory (without crossing into symlinks or protected subtrees) to list every protected subtree inside it. */
95
+ function findDirectProtectedPaths(root, ctx) {
96
+ if (isDirectlyProtectedEntry(root, ctx))
97
+ return [root];
98
+ let rootSt;
99
+ try {
100
+ rootSt = lstatSync(root);
101
+ }
102
+ catch {
103
+ return [];
104
+ }
105
+ if (rootSt.isSymbolicLink() || !rootSt.isDirectory())
106
+ return [];
107
+ const found = [];
108
+ const stack = [root];
109
+ while (stack.length) {
110
+ const dir = stack.pop();
111
+ let entries;
112
+ try {
113
+ entries = readdirSync(dir);
114
+ }
115
+ catch {
116
+ // Fail closed on unreadable directories so hidden nested checkouts cannot be deleted blindly.
117
+ found.push(dir);
118
+ continue;
119
+ }
120
+ for (const name of entries) {
121
+ const child = join(dir, name);
122
+ if (isDirectlyProtectedEntry(child, ctx)) {
123
+ found.push(child);
124
+ continue;
125
+ }
126
+ let childSt;
127
+ try {
128
+ childSt = lstatSync(child);
129
+ }
130
+ catch {
131
+ continue;
132
+ }
133
+ if (!childSt.isSymbolicLink() && childSt.isDirectory()) {
134
+ stack.push(child);
135
+ }
136
+ }
137
+ }
138
+ return found.sort();
139
+ }
140
+ function relativeLabel(cacheRoot, target) {
141
+ return relative(cacheRoot, target) || ".";
142
+ }
143
+ /**
144
+ * Deletes `target` only after verifying no protected Git checkout, worktree, or reserved folder lies at
145
+ * or beneath it; otherwise retains protected subtrees intact and prunes only safe siblings up to budget.
146
+ */
147
+ function removePathSafely(target, cacheRoot, maxBytesToRemove, ctx) {
148
+ if (!entryExists(target)) {
149
+ return { removedBytes: 0, cleanedLabels: [], skippedProtected: [], fullyRemoved: true };
150
+ }
151
+ const label = relativeLabel(cacheRoot, target);
152
+ if (isDirectlyProtectedEntry(target, ctx)) {
153
+ return { removedBytes: 0, cleanedLabels: [], skippedProtected: [label], fullyRemoved: false };
154
+ }
155
+ let st;
156
+ try {
157
+ st = lstatSync(target);
158
+ }
159
+ catch {
160
+ return { removedBytes: 0, cleanedLabels: [], skippedProtected: [], fullyRemoved: !entryExists(target) };
161
+ }
162
+ if (st.isSymbolicLink() || !st.isDirectory()) {
163
+ const actual = st.isFile() ? st.size : 0;
164
+ rmSync(target, { force: true });
165
+ return { removedBytes: actual, cleanedLabels: [label], skippedProtected: [], fullyRemoved: true };
166
+ }
167
+ const protectedSubtrees = findDirectProtectedPaths(target, ctx);
168
+ if (protectedSubtrees.length === 0) {
169
+ const actual = measurePath(target).bytes;
170
+ rmSync(target, { recursive: true, force: true });
171
+ return { removedBytes: actual, cleanedLabels: [label], skippedProtected: [], fullyRemoved: true };
172
+ }
173
+ // Protected subtrees exist beneath this directory: never recursive-delete `target` as a whole.
174
+ let childNames;
175
+ try {
176
+ childNames = readdirSync(target);
177
+ }
178
+ catch {
179
+ return {
180
+ removedBytes: 0,
181
+ cleanedLabels: [],
182
+ skippedProtected: protectedSubtrees.map((p) => relativeLabel(cacheRoot, p)),
183
+ fullyRemoved: false,
184
+ };
185
+ }
186
+ const children = childNames
187
+ .map((name) => {
188
+ const childPath = join(target, name);
189
+ const m = measurePath(childPath);
190
+ return { childPath, mtimeMs: m.mtimeMs, bytes: m.bytes };
191
+ })
192
+ .sort((a, b) => a.mtimeMs - b.mtimeMs || a.childPath.localeCompare(b.childPath));
193
+ let removedBytes = 0;
194
+ const cleanedLabels = [];
195
+ const skippedSet = new Set();
196
+ for (const child of children) {
197
+ if (maxBytesToRemove - removedBytes <= 0)
198
+ break;
199
+ const sub = removePathSafely(child.childPath, cacheRoot, maxBytesToRemove - removedBytes, ctx);
200
+ removedBytes += sub.removedBytes;
201
+ cleanedLabels.push(...sub.cleanedLabels);
202
+ for (const s of sub.skippedProtected)
203
+ skippedSet.add(s);
204
+ }
205
+ for (const p of protectedSubtrees)
206
+ skippedSet.add(relativeLabel(cacheRoot, p));
207
+ return {
208
+ removedBytes,
209
+ cleanedLabels,
210
+ skippedProtected: [...skippedSet].sort(),
211
+ fullyRemoved: false,
212
+ };
213
+ }
214
+ function globSegmentToRegex(segment) {
215
+ const escaped = segment.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
216
+ return new RegExp(`^${escaped}$`);
217
+ }
218
+ /** Expands strictly declared cache patterns (`~/` or `$CARGO_TARGET_DIR`, with at most one final-segment `*`). */
219
+ export function expandDeclaredCacheSpec(rawPath, homeDir, env) {
220
+ let resolvedPattern;
221
+ const cargoMatch = CARGO_VAR_PREFIX.exec(rawPath);
222
+ if (cargoMatch) {
223
+ const cargoRoot = env.CARGO_TARGET_DIR?.trim();
224
+ if (!cargoRoot || !cargoRoot.startsWith("/"))
225
+ return [];
226
+ resolvedPattern = cargoMatch[1] ? join(cargoRoot, cargoMatch[1]) : cargoRoot;
227
+ }
228
+ else if (rawPath.startsWith("~/")) {
229
+ resolvedPattern = join(homeDir, rawPath.slice(2));
230
+ }
231
+ else if (rawPath.startsWith("/")) {
232
+ resolvedPattern = resolve(rawPath);
233
+ }
234
+ else {
235
+ return [];
236
+ }
237
+ const segs = resolvedPattern.split("/");
238
+ const last = segs[segs.length - 1] ?? "";
239
+ if (last.includes("*")) {
240
+ if (last.replace(/\*/g, "").length < 2)
241
+ return [];
242
+ const parent = dirname(resolvedPattern);
243
+ if (!existsSync(parent))
244
+ return [];
245
+ let entries;
246
+ try {
247
+ entries = readdirSync(parent);
248
+ }
249
+ catch {
250
+ return [];
251
+ }
252
+ const re = globSegmentToRegex(last);
253
+ const out = [];
254
+ for (const entry of entries.sort()) {
255
+ if (!re.test(entry))
256
+ continue;
257
+ const full = join(parent, entry);
258
+ try {
259
+ if (lstatSync(full).isDirectory())
260
+ out.push(full);
261
+ }
262
+ catch { /* vanished during scan */ }
263
+ }
264
+ return out;
265
+ }
266
+ try {
267
+ if (existsSync(resolvedPattern) && lstatSync(resolvedPattern).isDirectory())
268
+ return [resolvedPattern];
269
+ }
270
+ catch { /* ignore unreadable path */ }
271
+ return [];
272
+ }
273
+ /** Parses `ps -axo pid=,comm=,args=` output into candidate PIDs matching allowed build process names. */
274
+ export function parseBuildPsOutput(stdout, allowedNames, selfPid) {
275
+ const lowerAllowed = new Set([...allowedNames].map((n) => n.toLowerCase()));
276
+ const out = [];
277
+ for (const line of stdout.split("\n")) {
278
+ const m = /^\s*(\d+)\s+(\S+)(?:\s+(.*))?$/.exec(line);
279
+ if (!m)
280
+ continue;
281
+ const pid = Number(m[1]);
282
+ if (!Number.isInteger(pid) || pid <= 1 || pid === selfPid)
283
+ continue;
284
+ const commBase = basename(m[2]).toLowerCase();
285
+ const firstArg = (m[3] ?? "").trim().split(/\s+/)[0] ?? "";
286
+ const argBase = firstArg ? basename(firstArg).toLowerCase() : "";
287
+ const matched = lowerAllowed.has(commBase)
288
+ ? basename(m[2])
289
+ : lowerAllowed.has(argBase)
290
+ ? basename(firstArg)
291
+ : null;
292
+ if (matched)
293
+ out.push({ pid, command: matched });
294
+ }
295
+ return out;
296
+ }
297
+ /** Parses `lsof -F pcn` output into `{ pid -> paths[] }`. */
298
+ export function parseLsofOutput(stdout) {
299
+ const byPid = new Map();
300
+ let currentPid = -1;
301
+ for (const rawLine of stdout.split("\n")) {
302
+ if (!rawLine)
303
+ continue;
304
+ const tag = rawLine[0];
305
+ const val = rawLine.slice(1);
306
+ if (tag === "p") {
307
+ currentPid = Number(val);
308
+ if (Number.isInteger(currentPid) && !byPid.has(currentPid))
309
+ byPid.set(currentPid, []);
310
+ }
311
+ else if (tag === "n" && currentPid > 0 && val.startsWith("/")) {
312
+ byPid.get(currentPid).push(val);
313
+ }
314
+ }
315
+ return byPid;
316
+ }
317
+ function readLinuxProcPaths(pid) {
318
+ try {
319
+ const out = [];
320
+ const cwd = readlinkSync(`/proc/${pid}/cwd`);
321
+ if (cwd.startsWith("/"))
322
+ out.push(cwd);
323
+ const fdDir = `/proc/${pid}/fd`;
324
+ for (const fd of readdirSync(fdDir)) {
325
+ try {
326
+ const target = readlinkSync(join(fdDir, fd));
327
+ if (target.startsWith("/"))
328
+ out.push(target);
329
+ }
330
+ catch (err) {
331
+ const code = err.code;
332
+ if (code === "EACCES" || code === "EPERM")
333
+ return null;
334
+ }
335
+ }
336
+ return out;
337
+ }
338
+ catch {
339
+ return null;
340
+ }
341
+ }
342
+ export function defaultStatVolume(targetPath) {
343
+ const probed = realpathSafe(targetPath);
344
+ const st = statfsSync(probed);
345
+ const totalBytes = Number(st.blocks) * Number(st.bsize);
346
+ const freeBytes = Number(st.bavail) * Number(st.bsize);
347
+ const freePct = totalBytes > 0 ? (freeBytes / totalBytes) * 100 : 100;
348
+ let mount = "";
349
+ try {
350
+ const dfOut = execFileSync("df", ["-Pk", probed], { encoding: "utf8", timeout: 5_000, stdio: ["ignore", "pipe", "ignore"] });
351
+ const lines = dfOut.trim().split("\n");
352
+ if (lines.length >= 2) {
353
+ const cols = lines[lines.length - 1].trim().split(/\s+/);
354
+ if (cols.length >= 6)
355
+ mount = cols.slice(5).join(" ");
356
+ }
357
+ }
358
+ catch { /* fall back to st_dev */ }
359
+ if (!mount) {
360
+ try {
361
+ mount = `dev:${statSync(probed).dev}`;
362
+ }
363
+ catch {
364
+ mount = dirname(probed);
365
+ }
366
+ }
367
+ return { mount, freeBytes, totalBytes, freePct };
368
+ }
369
+ export function defaultProbeActiveBuildProcesses(allowedNames, selfPid = process.pid, platform = process.platform) {
370
+ let psOut = "";
371
+ try {
372
+ psOut = execFileSync("ps", ["-axo", "pid=,comm=,args="], { encoding: "utf8", timeout: 5_000, stdio: ["ignore", "pipe", "pipe"] });
373
+ }
374
+ catch {
375
+ return { processes: [], probeFailed: true };
376
+ }
377
+ const candidates = parseBuildPsOutput(psOut, allowedNames, selfPid);
378
+ if (!candidates.length)
379
+ return { processes: [], probeFailed: false };
380
+ const pidPaths = new Map();
381
+ const unresolved = [];
382
+ if (platform === "linux") {
383
+ for (const c of candidates) {
384
+ const paths = readLinuxProcPaths(c.pid);
385
+ if (paths !== null)
386
+ pidPaths.set(c.pid, paths);
387
+ else
388
+ unresolved.push(c);
389
+ }
390
+ }
391
+ else {
392
+ unresolved.push(...candidates);
393
+ }
394
+ let lsofFatal = false;
395
+ if (unresolved.length) {
396
+ try {
397
+ const out = execFileSync("lsof", ["-w", "-n", "-P", "-F", "pcn", "-p", unresolved.map((c) => c.pid).join(",")], {
398
+ encoding: "utf8",
399
+ timeout: 8_000,
400
+ stdio: ["ignore", "pipe", "pipe"],
401
+ });
402
+ for (const [pid, paths] of parseLsofOutput(out))
403
+ pidPaths.set(pid, paths);
404
+ }
405
+ catch (e) {
406
+ const err = e;
407
+ // `lsof -p ...` exits 1 if a pid vanished or lacked permission, while still emitting partial records to stdout.
408
+ if (typeof err.stdout === "string" && err.stdout.trim()) {
409
+ for (const [pid, paths] of parseLsofOutput(err.stdout))
410
+ pidPaths.set(pid, paths);
411
+ }
412
+ else if (err.code === "ENOENT" || unresolved.some((u) => processAlive(u.pid))) {
413
+ lsofFatal = true;
414
+ }
415
+ }
416
+ }
417
+ // Fail closed for any candidate PID that is still alive yet absent from pidPaths (e.g. partial lsof or EPERM),
418
+ // while retaining partial open-file records for the PIDs that were successfully inspected.
419
+ const processes = candidates.map((c) => {
420
+ const paths = pidPaths.get(c.pid);
421
+ const uninspected = paths === undefined && (lsofFatal || processAlive(c.pid));
422
+ return {
423
+ pid: c.pid,
424
+ command: c.command,
425
+ paths: paths ?? [],
426
+ ...(uninspected ? { uninspected: true } : {}),
427
+ };
428
+ });
429
+ return {
430
+ processes,
431
+ probeFailed: lsofFatal || processes.some((p) => p.uninspected),
432
+ };
433
+ }
434
+ function processAlive(pid) {
435
+ try {
436
+ process.kill(pid, 0);
437
+ return true;
438
+ }
439
+ catch {
440
+ return false;
441
+ }
442
+ }
443
+ /** Computes total logical size and most recent modification time under a directory without following symlinks. */
444
+ function measurePath(target) {
445
+ let bytes = 0;
446
+ let mtimeMs = 0;
447
+ const stack = [target];
448
+ while (stack.length) {
449
+ const current = stack.pop();
450
+ let st;
451
+ try {
452
+ st = lstatSync(current);
453
+ }
454
+ catch {
455
+ continue;
456
+ }
457
+ if (st.mtimeMs > mtimeMs)
458
+ mtimeMs = st.mtimeMs;
459
+ if (st.isSymbolicLink())
460
+ continue;
461
+ if (st.isFile()) {
462
+ bytes += st.size;
463
+ continue;
464
+ }
465
+ if (st.isDirectory()) {
466
+ let entries;
467
+ try {
468
+ entries = readdirSync(current);
469
+ }
470
+ catch {
471
+ continue;
472
+ }
473
+ for (const name of entries)
474
+ stack.push(join(current, name));
475
+ }
476
+ }
477
+ return { bytes, mtimeMs };
478
+ }
479
+ function detectTool(cacheDir, declaredTool) {
480
+ if (declaredTool === "cargo" || declaredTool === "generic")
481
+ return declaredTool;
482
+ if (existsSync(join(cacheDir, "CACHEDIR.TAG")) ||
483
+ existsSync(join(cacheDir, ".rustc_info.json")) ||
484
+ existsSync(join(cacheDir, ".cargo-lock")) ||
485
+ existsSync(join(cacheDir, "debug")) ||
486
+ existsSync(join(cacheDir, "release"))) {
487
+ return "cargo";
488
+ }
489
+ return "generic";
490
+ }
491
+ function collectCargoCandidates(cacheDir, ctx) {
492
+ const out = [];
493
+ const skippedProtected = [];
494
+ let topEntries;
495
+ try {
496
+ topEntries = readdirSync(cacheDir);
497
+ }
498
+ catch {
499
+ return { candidates: out, skippedProtected };
500
+ }
501
+ const metadataFiles = new Set(["CACHEDIR.TAG", ".rustc_info.json", ".cargo-lock"]);
502
+ for (const top of topEntries) {
503
+ if (metadataFiles.has(top))
504
+ continue;
505
+ const topPath = join(cacheDir, top);
506
+ if (isDirectlyProtectedEntry(topPath, ctx)) {
507
+ skippedProtected.push(relativeLabel(cacheDir, topPath));
508
+ continue;
509
+ }
510
+ let topSt;
511
+ try {
512
+ topSt = lstatSync(topPath);
513
+ }
514
+ catch {
515
+ continue;
516
+ }
517
+ if (!topSt.isDirectory() || topSt.isSymbolicLink())
518
+ continue;
519
+ // Look for `<profile>/incremental/*` and `<triple>/<profile>/incremental/*`.
520
+ const profileDirs = [{ rel: top, full: topPath }];
521
+ if (existsSync(join(topPath, "debug")) || existsSync(join(topPath, "release"))) {
522
+ try {
523
+ for (const sub of readdirSync(topPath)) {
524
+ const subPath = join(topPath, sub);
525
+ if (isDirectlyProtectedEntry(subPath, ctx)) {
526
+ skippedProtected.push(relativeLabel(cacheDir, subPath));
527
+ continue;
528
+ }
529
+ try {
530
+ if (!lstatSync(subPath).isSymbolicLink() && lstatSync(subPath).isDirectory())
531
+ profileDirs.push({ rel: join(top, sub), full: subPath });
532
+ }
533
+ catch { /* ignore */ }
534
+ }
535
+ }
536
+ catch { /* ignore */ }
537
+ }
538
+ for (const prof of profileDirs) {
539
+ const incDir = join(prof.full, "incremental");
540
+ if (existsSync(incDir) && !isDirectlyProtectedEntry(incDir, ctx)) {
541
+ try {
542
+ for (const unit of readdirSync(incDir)) {
543
+ const unitPath = join(incDir, unit);
544
+ if (isDirectlyProtectedEntry(unitPath, ctx)) {
545
+ skippedProtected.push(relativeLabel(cacheDir, unitPath));
546
+ continue;
547
+ }
548
+ const m = measurePath(unitPath);
549
+ if (m.bytes > 0 || entryExists(unitPath)) {
550
+ out.push({ path: unitPath, label: join(prof.rel, "incremental", unit), tier: 1, mtimeMs: m.mtimeMs, bytes: m.bytes });
551
+ }
552
+ }
553
+ }
554
+ catch { /* ignore */ }
555
+ }
556
+ }
557
+ const mTop = measurePath(topPath);
558
+ out.push({ path: topPath, label: top, tier: 2, mtimeMs: mTop.mtimeMs, bytes: mTop.bytes });
559
+ }
560
+ out.sort((a, b) => a.tier - b.tier || a.mtimeMs - b.mtimeMs || a.path.localeCompare(b.path));
561
+ return { candidates: out, skippedProtected };
562
+ }
563
+ function collectGenericCandidates(cacheDir) {
564
+ const out = [];
565
+ let topEntries;
566
+ try {
567
+ topEntries = readdirSync(cacheDir);
568
+ }
569
+ catch {
570
+ return out;
571
+ }
572
+ for (const name of topEntries) {
573
+ const full = join(cacheDir, name);
574
+ const m = measurePath(full);
575
+ out.push({ path: full, label: name, tier: 1, mtimeMs: m.mtimeMs, bytes: m.bytes });
576
+ }
577
+ out.sort((a, b) => a.mtimeMs - b.mtimeMs || a.path.localeCompare(b.path));
578
+ return out;
579
+ }
580
+ function activeUsersForCache(cacheDir, allowedProcesses, probe) {
581
+ const cacheReal = realpathSafe(cacheDir);
582
+ const cacheAbs = resolve(cacheDir);
583
+ const active = new Set();
584
+ const uninspected = new Set();
585
+ const lowerAllowed = new Set([...allowedProcesses].map((n) => n.toLowerCase()));
586
+ if (probe.probeFailed && probe.processes.length === 0) {
587
+ return {
588
+ inUse: true,
589
+ activeProcesses: ["unknown"],
590
+ probeIncomplete: true,
591
+ uninspectedProcesses: ["unknown"],
592
+ };
593
+ }
594
+ for (const proc of probe.processes) {
595
+ if (!lowerAllowed.has(proc.command.toLowerCase()))
596
+ continue;
597
+ for (const p of proc.paths) {
598
+ const pReal = realpathSafe(p);
599
+ if (isSameOrChild(p, cacheAbs) || isSameOrChild(pReal, cacheReal)) {
600
+ active.add(proc.command);
601
+ break;
602
+ }
603
+ }
604
+ if (proc.uninspected || (probe.probeFailed && proc.paths.length === 0)) {
605
+ uninspected.add(proc.command);
606
+ }
607
+ }
608
+ const probeIncomplete = uninspected.size > 0;
609
+ const combined = [...new Set([...active, ...uninspected])].sort();
610
+ return {
611
+ inUse: active.size > 0 || probeIncomplete,
612
+ activeProcesses: combined,
613
+ probeIncomplete,
614
+ uninspectedProcesses: [...uninspected].sort(),
615
+ };
616
+ }
617
+ /**
618
+ * Discovers ONLY explicitly declared build caches, checks usage by active build processes and per-volume
619
+ * free-space floors, cleans idle caches oldest-first when over budget or under the floor, and reports
620
+ * freed bytes and floor-breach build-running faults.
621
+ */
622
+ export function manageBuildCaches(input) {
623
+ const budgetGb = input.budgetGb ?? DEFAULT_CACHE_BUDGET_GB;
624
+ const floorPct = input.floorPct ?? DEFAULT_CACHE_FLOOR_PCT;
625
+ const budgetBytes = input.budgetBytesOverride ?? budgetGb * GIB;
626
+ const homeDir = input.ops?.homeDir ?? homedir();
627
+ const env = input.ops?.env ?? process.env;
628
+ const platform = input.ops?.platform ?? process.platform;
629
+ const selfPid = input.ops?.selfPid ?? process.pid;
630
+ const statVolume = input.ops?.statVolume ?? defaultStatVolume;
631
+ const probeActiveBuildProcesses = input.ops?.probeActiveBuildProcesses ??
632
+ ((names) => defaultProbeActiveBuildProcesses(names, selfPid, platform));
633
+ const specs = [];
634
+ for (const s of input.machineCaches ?? [])
635
+ specs.push({ spec: s, projects: [] });
636
+ for (const p of input.projects ?? []) {
637
+ for (const s of p.build_caches ?? [])
638
+ specs.push({ spec: s, projects: [p.name] });
639
+ }
640
+ // Expand only declared paths and deduplicate by canonical directory path.
641
+ const discoveredByReal = new Map();
642
+ const protectedWorktrees = input.protectedWorktrees ?? [];
643
+ const protectionCtx = { homeDir, workdir: input.workdir ?? null, protectedWorktrees };
644
+ for (const { spec, projects } of specs) {
645
+ for (const expanded of expandDeclaredCacheSpec(spec.path, homeDir, env)) {
646
+ if (isProtectedCachePath(expanded, homeDir, input.workdir ?? null, protectedWorktrees))
647
+ continue;
648
+ const real = realpathSafe(expanded);
649
+ let existing = discoveredByReal.get(real);
650
+ if (!existing) {
651
+ existing = { path: expanded, tool: spec.tool, processes: new Set(DEFAULT_BUILD_PROCESS_NAMES), projects: new Set() };
652
+ discoveredByReal.set(real, existing);
653
+ }
654
+ else if (existing.tool === "auto" && spec.tool !== "auto") {
655
+ existing.tool = spec.tool;
656
+ }
657
+ for (const proc of spec.processes)
658
+ existing.processes.add(proc);
659
+ for (const proj of projects)
660
+ existing.projects.add(proj);
661
+ }
662
+ }
663
+ const allAllowedProcs = new Set(DEFAULT_BUILD_PROCESS_NAMES);
664
+ for (const d of discoveredByReal.values())
665
+ for (const p of d.processes)
666
+ allAllowedProcs.add(p);
667
+ const processProbe = discoveredByReal.size > 0
668
+ ? probeActiveBuildProcesses(allAllowedProcs)
669
+ : { processes: [], probeFailed: false };
670
+ const volumeInitial = new Map();
671
+ const volumeFreed = new Map();
672
+ const cacheStates = [];
673
+ for (const d of [...discoveredByReal.values()].sort((a, b) => a.path.localeCompare(b.path))) {
674
+ const vol = statVolume(d.path);
675
+ if (!volumeInitial.has(vol.mount))
676
+ volumeInitial.set(vol.mount, vol);
677
+ const { bytes: sizeBefore, mtimeMs } = measurePath(d.path);
678
+ const tool = detectTool(d.path, d.tool);
679
+ const { inUse, activeProcesses, probeIncomplete, uninspectedProcesses } = activeUsersForCache(d.path, d.processes, processProbe);
680
+ const entry = {
681
+ path: d.path,
682
+ volume: vol.mount,
683
+ tool,
684
+ status: "ok",
685
+ size_bytes_before: sizeBefore,
686
+ size_bytes: sizeBefore,
687
+ removed_bytes: 0,
688
+ freed_bytes: 0,
689
+ in_use: inUse,
690
+ active_processes: activeProcesses,
691
+ ...(probeIncomplete ? { probe_incomplete: true, uninspected_processes: uninspectedProcesses } : {}),
692
+ };
693
+ cacheStates.push({ entry, projects: [...d.projects].sort(), mtimeMs, targetPath: d.path, tool });
694
+ }
695
+ const volumeEffectiveFreePct = (mount) => {
696
+ const init = volumeInitial.get(mount);
697
+ const freed = volumeFreed.get(mount) ?? 0;
698
+ const rep = cacheStates.find((c) => c.entry.volume === mount)?.targetPath;
699
+ const probeTarget = rep ? (existsSync(rep) ? rep : existsSync(dirname(rep)) ? dirname(rep) : mount) : mount;
700
+ const current = existsSync(probeTarget) ? statVolume(probeTarget) : init;
701
+ const estFree = Math.max(current.freeBytes, init.freeBytes + freed);
702
+ const total = current.totalBytes || init.totalBytes;
703
+ const pct = total > 0 ? (estFree / total) * 100 : 100;
704
+ const targetFree = Math.ceil((floorPct / 100) * total);
705
+ return { pct, neededBytes: Math.max(0, targetFree - estFree) };
706
+ };
707
+ const cleanCache = (state, reasonFloorBytes) => {
708
+ const e = state.entry;
709
+ if (!existsSync(state.targetPath))
710
+ return;
711
+ if (e.in_use) {
712
+ e.status = "skipped_in_use";
713
+ return;
714
+ }
715
+ let remaining = e.size_bytes;
716
+ let targetBytesToRemove = Math.max(remaining - budgetBytes, reasonFloorBytes);
717
+ if (targetBytesToRemove <= 0)
718
+ return;
719
+ const cleanedItems = [];
720
+ const skippedProtected = new Set(e.skipped_protected ?? []);
721
+ let removedHere = 0;
722
+ try {
723
+ const cargoCollected = state.tool === "cargo" ? collectCargoCandidates(state.targetPath, protectionCtx) : null;
724
+ const candidates = cargoCollected ? cargoCollected.candidates : collectGenericCandidates(state.targetPath);
725
+ if (cargoCollected) {
726
+ for (const s of cargoCollected.skippedProtected)
727
+ skippedProtected.add(s);
728
+ }
729
+ const removedRoots = new Set();
730
+ for (const cand of candidates) {
731
+ if (targetBytesToRemove <= 0)
732
+ break;
733
+ if ([...removedRoots].some((r) => isSameOrChild(cand.path, r)))
734
+ continue;
735
+ if (!entryExists(cand.path))
736
+ continue;
737
+ const removed = removePathSafely(cand.path, state.targetPath, targetBytesToRemove, protectionCtx);
738
+ if (removed.fullyRemoved && state.tool === "cargo" && cand.tier === 2) {
739
+ removedRoots.add(cand.path);
740
+ }
741
+ removedHere += removed.removedBytes;
742
+ remaining = Math.max(0, remaining - removed.removedBytes);
743
+ targetBytesToRemove -= removed.removedBytes;
744
+ cleanedItems.push(...removed.cleanedLabels);
745
+ for (const s of removed.skippedProtected)
746
+ skippedProtected.add(s);
747
+ }
748
+ // Fall back to removing the whole declared cache directory only when zero protected subtrees exist anywhere inside it.
749
+ if (entryExists(state.targetPath)) {
750
+ const protectedUnderRoot = findDirectProtectedPaths(state.targetPath, protectionCtx);
751
+ for (const p of protectedUnderRoot)
752
+ skippedProtected.add(relativeLabel(state.targetPath, p));
753
+ const afterPartial = measurePath(state.targetPath).bytes;
754
+ const stillOverBudget = afterPartial > budgetBytes;
755
+ const stillNeedsFloor = reasonFloorBytes > 0 && removedHere < reasonFloorBytes && afterPartial > 0;
756
+ if ((stillOverBudget || stillNeedsFloor) && protectedUnderRoot.length === 0) {
757
+ rmSync(state.targetPath, { recursive: true, force: true });
758
+ removedHere += afterPartial;
759
+ remaining = 0;
760
+ cleanedItems.push("(whole cache directory)");
761
+ }
762
+ else {
763
+ remaining = afterPartial;
764
+ }
765
+ }
766
+ else {
767
+ remaining = 0;
768
+ }
769
+ if (skippedProtected.size > 0) {
770
+ const list = [...skippedProtected].sort();
771
+ e.skipped_protected = list.length > 20 ? [...list.slice(0, 19), `(+${list.length - 19} more)`] : list;
772
+ }
773
+ if (removedHere > 0 || cleanedItems.length > 0) {
774
+ e.status = "cleaned";
775
+ e.removed_bytes += removedHere;
776
+ e.freed_bytes += removedHere;
777
+ e.size_bytes = remaining;
778
+ const combined = [...(e.cleaned_items ?? []), ...cleanedItems];
779
+ e.cleaned_items = combined.length > 20 ? [...combined.slice(0, 19), `(+${combined.length - 19} more)`] : combined;
780
+ volumeFreed.set(e.volume, (volumeFreed.get(e.volume) ?? 0) + removedHere);
781
+ }
782
+ else if (skippedProtected.size > 0 && e.removed_bytes === 0 && !(e.cleaned_items?.length)) {
783
+ e.status = "skipped_protected";
784
+ e.size_bytes = remaining;
785
+ }
786
+ else {
787
+ e.size_bytes = remaining;
788
+ }
789
+ }
790
+ catch (err) {
791
+ e.status = "error";
792
+ e.error = err.message.slice(0, 300);
793
+ }
794
+ };
795
+ // Pass 1: clean any cache exceeding the per-directory budget, unless a build is using it.
796
+ for (const state of cacheStates) {
797
+ if (state.entry.size_bytes > budgetBytes) {
798
+ if (state.entry.in_use) {
799
+ state.entry.status = "skipped_in_use";
800
+ if (state.entry.probe_incomplete) {
801
+ state.entry.error = `build process inspection incomplete (${(state.entry.uninspected_processes ?? ["unknown"]).join(", ")}); cleanup skipped without deleting`;
802
+ }
803
+ }
804
+ else {
805
+ cleanCache(state, 0);
806
+ }
807
+ }
808
+ }
809
+ // Pass 2: for volumes still below the free-space floor, clean idle declared caches oldest-first.
810
+ for (const [mount, init] of volumeInitial.entries()) {
811
+ const check = volumeEffectiveFreePct(mount);
812
+ if (init.freePct >= floorPct && check.pct >= floorPct)
813
+ continue;
814
+ const onVolume = cacheStates
815
+ .filter((s) => s.entry.volume === mount)
816
+ .sort((a, b) => a.mtimeMs - b.mtimeMs || a.entry.path.localeCompare(b.entry.path));
817
+ for (const state of onVolume) {
818
+ const nowVol = volumeEffectiveFreePct(mount);
819
+ if (nowVol.pct >= floorPct || nowVol.neededBytes <= 0)
820
+ break;
821
+ if (state.entry.in_use) {
822
+ state.entry.status = "skipped_in_use";
823
+ if (state.entry.probe_incomplete) {
824
+ state.entry.error = `build process inspection incomplete (${(state.entry.uninspected_processes ?? ["unknown"]).join(", ")}); cleanup skipped without deleting`;
825
+ }
826
+ continue;
827
+ }
828
+ cleanCache(state, nowVol.neededBytes);
829
+ }
830
+ }
831
+ // Pass 3: report volume metrics and raise faults for any volume still under floor while a build runs
832
+ // (or when incomplete/permission-failed process inspection blocks a required cache cleanup).
833
+ const volumes = [];
834
+ const faults = [];
835
+ for (const [mount, init] of [...volumeInitial.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
836
+ const freed = volumeFreed.get(mount) ?? 0;
837
+ const repPath = cacheStates.find((c) => c.entry.volume === mount)?.targetPath;
838
+ const probePath = repPath && existsSync(repPath) ? repPath : repPath && existsSync(dirname(repPath)) ? dirname(repPath) : mount;
839
+ const post = existsSync(probePath) ? statVolume(probePath) : init;
840
+ const effectiveFree = Math.max(post.freeBytes, init.freeBytes + freed);
841
+ const total = post.totalBytes || init.totalBytes;
842
+ const freePctAfter = total > 0 ? (effectiveFree / total) * 100 : 100;
843
+ const underFloor = freePctAfter < floorPct;
844
+ volumes.push({
845
+ mount,
846
+ free_bytes_before: init.freeBytes,
847
+ free_bytes: effectiveFree,
848
+ total_bytes: total,
849
+ free_pct_before: Number(init.freePct.toFixed(2)),
850
+ free_pct: Number(freePctAfter.toFixed(2)),
851
+ under_floor: underFloor,
852
+ freed_bytes: freed,
853
+ });
854
+ const inUseOnVol = cacheStates.filter((s) => s.entry.volume === mount && s.entry.in_use);
855
+ const incompleteSkippedOnVol = cacheStates.filter((s) => s.entry.volume === mount && s.entry.status === "skipped_in_use" && s.entry.probe_incomplete);
856
+ if (underFloor && inUseOnVol.length > 0) {
857
+ faults.push({
858
+ kind: "floor_breach",
859
+ volume: mount,
860
+ free_pct: Number(freePctAfter.toFixed(1)),
861
+ floor_pct: floorPct,
862
+ caches: inUseOnVol.map((s) => s.entry.path),
863
+ processes: [...new Set(inUseOnVol.flatMap((s) => s.entry.active_processes))].sort(),
864
+ projects: [...new Set(inUseOnVol.flatMap((s) => s.projects))].sort(),
865
+ reason: incompleteSkippedOnVol.length > 0
866
+ ? "volume below free-space floor while build process inspection was incomplete"
867
+ : "volume below free-space floor while declared build cache is in use",
868
+ });
869
+ }
870
+ else if (incompleteSkippedOnVol.length > 0) {
871
+ faults.push({
872
+ kind: "inspection_incomplete",
873
+ volume: mount,
874
+ free_pct: Number(freePctAfter.toFixed(1)),
875
+ floor_pct: floorPct,
876
+ caches: incompleteSkippedOnVol.map((s) => s.entry.path),
877
+ processes: [...new Set(incompleteSkippedOnVol.flatMap((s) => s.entry.uninspected_processes ?? s.entry.active_processes))].sort(),
878
+ projects: [...new Set(incompleteSkippedOnVol.flatMap((s) => s.projects))].sort(),
879
+ reason: "build process inspection incomplete (unknown usage); cleanup skipped without deleting",
880
+ });
881
+ }
882
+ }
883
+ return {
884
+ budget_gb: budgetGb,
885
+ floor_pct: floorPct,
886
+ checked_at: new Date().toISOString(),
887
+ caches: cacheStates.map((s) => s.entry),
888
+ volumes,
889
+ faults,
890
+ };
891
+ }