@mmerterden/multi-agent-pipeline 23.0.0 → 23.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.
@@ -27,7 +27,13 @@
27
27
  * ended sessions are listed in the report under `orphans` as information, and
28
28
  * nothing here can signal a process. Unattended runs (--unattended or
29
29
  * MULTI_AGENT_UNATTENDED=1) keep to UNATTENDED_SAFE and never touch the Trash,
30
- * transcripts, worktrees, archives or device support.
30
+ * transcripts, worktrees, archives, device support or simulator runtimes.
31
+ *
32
+ * An item kept only because it was touched recently is measured and reported
33
+ * under `held`; --include-recent drops that age guard for one run (never
34
+ * unattended). Items in use, the current session's scratch and any session
35
+ * scratch touched within --scratch-hours (it may belong to another open
36
+ * session) stay held at any age. Folders the scan could not read are counted under `unreadable`.
31
37
  *
32
38
  * Deletion uses fs.rmSync, which unlinks a symlink instead of entering it.
33
39
  * Pipeline scratch under /tmp and per-task pipeline logs are delegated to
@@ -36,17 +42,25 @@
36
42
  *
37
43
  * Usage:
38
44
  * disk-cleaner.mjs [--dry-run] [--apply] [--only=a,b] [--skip=a,b]
39
- * [--trash] [--transcripts] [--unattended]
45
+ * [--trash] [--transcripts] [--unattended] [--include-recent]
40
46
  * [--log-days=N] [--archive-days=N] [--transcript-days=N]
41
47
  * [--scratch-hours=N] [--build-hours=N] [--orphan-minutes=N]
48
+ * [--runtime-days=N] [--depth=N] [--exclude=PATH]...
42
49
  * [--root=DIR]... [--tmp-root=DIR]... [--home=DIR]
43
50
  * [--report=FILE] [--json] [--list] [--top=N]
44
51
  *
52
+ * --root and --depth (defaults: the git repos under the usual dev folders,
53
+ * depth 8) also come from DISK_CLEANER_ROOTS (colon-separated) and
54
+ * DISK_CLEANER_DEPTH; --exclude from DISK_CLEANER_EXCLUDE (colon-separated).
55
+ * An excluded path, and any candidate that holds it, is kept.
56
+ *
45
57
  * Every category in the JSON report carries `top` (its largest items, real
46
58
  * paths and sizes, 5 unless --top says otherwise), `more` (how many items
47
59
  * `top` leaves out) and `kept` (how many items were kept, per reason). The
48
60
  * report also carries `reclaimableBytes` (categories whose tool is running
49
- * are measured but left out) and `disk.expectedFreeBytes`. --top=N also lists
61
+ * are measured but left out), `disk.expectedFreeBytes`, `held` (items, bytes,
62
+ * how many only age holds and their bytes, how many are in use) and
63
+ * `unreadable` (count and a sample). --top=N also lists
50
64
  * the top items under each row of the text table.
51
65
  *
52
66
  * Exit: 0 done, 1 one or more deletions failed, 2 usage error.
@@ -70,10 +84,11 @@ import { homedir, tmpdir } from "node:os";
70
84
  import { basename, dirname, join, sep } from "node:path";
71
85
  import { fileURLToPath, pathToFileURL } from "node:url";
72
86
 
73
- export const VERSION = "1.1.0";
87
+ export const VERSION = "1.2.0";
74
88
  const DAY_MS = 86_400_000;
75
89
  const HOUR_MS = 3_600_000;
76
90
  const MAX_WALK_DEPTH = 8;
91
+ const DEFAULT_RUNTIME_DAYS = 30;
77
92
  const KEEP_REPORTS = 20;
78
93
  const DEFAULT_TOP = 5;
79
94
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -116,6 +131,11 @@ export const DEV_CACHE_DIRS = [
116
131
 
117
132
  const WALK_SKIP = new Set([".git", "node_modules", ".build", "DerivedData", "Pods", "build"]);
118
133
 
134
+ // Never walked when a dev root contains them: app data, installed apps, media
135
+ // libraries and the user's own folders hold no project build output.
136
+ const DEV_WALK_PRUNE_HOME = ["Library", ".Trash", "Applications", ...PROTECTED_HOME];
137
+ const MEDIA_LIBRARY = /\.(photoslibrary|musiclibrary|tvlibrary)$/;
138
+
119
139
  // Session children that outlive their session: log watchers, a symbol upload
120
140
  // that never finished, and the shell wrapper Claude Code starts commands in.
121
141
  const ORPHAN_PATTERNS = [
@@ -134,6 +154,14 @@ function lstatOrNull(p) {
134
154
  }
135
155
  }
136
156
 
157
+ function nativeReal(p) {
158
+ try {
159
+ return realpathSync.native(p);
160
+ } catch {
161
+ return null;
162
+ }
163
+ }
164
+
137
165
  function realOrNull(p) {
138
166
  try {
139
167
  return realpathSync(p);
@@ -142,10 +170,15 @@ function realOrNull(p) {
142
170
  }
143
171
  }
144
172
 
145
- function listDir(dir) {
173
+ function noteDenied(ctx, dir, e) {
174
+ if (ctx?.denied && (e?.code === "EACCES" || e?.code === "EPERM")) ctx.denied.add(dir);
175
+ }
176
+
177
+ function listDir(dir, ctx) {
146
178
  try {
147
179
  return readdirSync(dir).map((n) => join(dir, n));
148
- } catch {
180
+ } catch (e) {
181
+ noteDenied(ctx, dir, e);
149
182
  return [];
150
183
  }
151
184
  }
@@ -271,6 +304,7 @@ export function makeContext(o = {}) {
271
304
  ];
272
305
  let psCache = null;
273
306
  let openCache = null;
307
+ let simCache = null;
274
308
  const ctx = {
275
309
  home,
276
310
  realHome: realOrNull(home) || home,
@@ -285,18 +319,25 @@ export function makeContext(o = {}) {
285
319
  archives: o.archiveDays ?? 90,
286
320
  transcripts: o.transcriptDays ?? 90,
287
321
  },
322
+ includeRecent: Boolean(o.includeRecent),
288
323
  scratchHours: o.scratchHours ?? 48,
289
324
  repoBuildHours: o.repoBuildHours ?? 12,
290
325
  tmpGraceMinutes: o.tmpGraceMinutes ?? 120,
291
326
  orphanMinutes: o.orphanMinutes ?? 30,
327
+ runtimeDays: o.runtimeDays ?? DEFAULT_RUNTIME_DAYS,
328
+ maxDepth: o.maxDepth ?? MAX_WALK_DEPTH,
329
+ excludes: (o.excludes || []).filter(Boolean).map((p) => nativeReal(p) || p),
330
+ denied: new Set(),
292
331
  run: o.run || realRun,
293
332
  du: o.du || duBytes,
294
333
  ps: () => (psCache ??= (o.ps || realPs)()),
295
334
  openPaths: () =>
296
335
  (openCache ??= (o.openPaths || (() => realOpenPaths(uid)))().map(normalizeTmp)),
336
+ simDevices: () => (simCache ??= [readSimDevices(ctx)])[0],
297
337
  resetProbes() {
298
338
  psCache = null;
299
339
  openCache = null;
340
+ simCache = null;
300
341
  },
301
342
  };
302
343
  return ctx;
@@ -382,28 +423,46 @@ function addPath(out, ctx, path, roots, extra = {}) {
382
423
  function childrenOf(ctx, out, roots, filter = () => true) {
383
424
  for (const root of roots) {
384
425
  if (!rootUsable(root, ctx, out)) continue;
385
- for (const p of listDir(root)) if (filter(p)) addPath(out, ctx, p, [root]);
426
+ for (const p of listDir(root, ctx)) if (filter(p)) addPath(out, ctx, p, [root]);
386
427
  }
387
428
  }
388
429
 
389
- function walk(dir, depth, visit) {
390
- if (depth > MAX_WALK_DEPTH) return;
430
+ function hold(out, path, reason, held, bytes) {
431
+ out.skipped.push(bytes == null ? { path, reason, held } : { path, reason, held, bytes });
432
+ }
433
+
434
+ /** Whether a dev-root walk stays out of `dir`. */
435
+ function devPruned(ctx, dir, name) {
436
+ if (MEDIA_LIBRARY.test(name)) return true;
437
+ return DEV_WALK_PRUNE_HOME.some(
438
+ (rel) => dir === join(ctx.home, rel) || dir === join(ctx.realHome, rel),
439
+ );
440
+ }
441
+
442
+ function walk(dir, visit, { ctx, maxDepth = MAX_WALK_DEPTH, prune } = {}, depth = 0) {
443
+ if (depth > maxDepth) return;
391
444
  let entries;
392
445
  try {
393
446
  entries = readdirSync(dir, { withFileTypes: true });
394
- } catch {
447
+ } catch (e) {
448
+ noteDenied(ctx, dir, e);
395
449
  return;
396
450
  }
397
451
  for (const e of entries) {
398
452
  const p = join(dir, e.name);
399
453
  if (e.isSymbolicLink()) continue;
400
454
  if (e.isDirectory()) {
401
- if (WALK_SKIP.has(e.name)) continue;
402
- walk(p, depth + 1, visit);
455
+ if (WALK_SKIP.has(e.name) || prune?.(p, e.name)) continue;
456
+ walk(p, visit, { ctx, maxDepth, prune }, depth + 1);
403
457
  } else if (e.isFile()) visit(p);
404
458
  }
405
459
  }
406
460
 
461
+ /** The age guard: false for every item when the run includes recent ones. */
462
+ function touchedWithin(ctx, mtimeMs, ms) {
463
+ return !ctx.includeRecent && ctx.now - mtimeMs < ms;
464
+ }
465
+
407
466
  function olderThan(path, ms, ctx) {
408
467
  const st = lstatOrNull(path);
409
468
  return Boolean(st) && ctx.now - st.mtimeMs > ms;
@@ -537,7 +596,7 @@ function worktreeCandidates(ctx, out) {
537
596
  const knownBases = bases.filter(
538
597
  (b) => ctx.run("git", ["-C", repo, "rev-parse", "--verify", "--quiet", b]).status === 0,
539
598
  );
540
- for (const wt of listDir(wtRoot)) {
599
+ for (const wt of listDir(wtRoot, ctx)) {
541
600
  const st = lstatOrNull(wt);
542
601
  if (!st || !st.isDirectory()) continue;
543
602
  if (st.isSymbolicLink()) {
@@ -582,9 +641,13 @@ function worktreeCandidates(ctx, out) {
582
641
  function dsStoreCandidates(ctx, out) {
583
642
  for (const root of ctx.devRoots) {
584
643
  if (!rootUsable(root, ctx, out)) continue;
585
- walk(root, 0, (p) => {
586
- if (basename(p) === ".DS_Store") addPath(out, ctx, p, [root]);
587
- });
644
+ walk(
645
+ root,
646
+ (p) => {
647
+ if (basename(p) === ".DS_Store") addPath(out, ctx, p, [root]);
648
+ },
649
+ { ctx, maxDepth: ctx.maxDepth, prune: (p, name) => devPruned(ctx, p, name) },
650
+ );
588
651
  }
589
652
  }
590
653
 
@@ -609,24 +672,26 @@ BUILD_SHAPE[".DerivedData"] = BUILD_SHAPE.DerivedData;
609
672
  function repoBuildCandidates(ctx, out) {
610
673
  const maxAge = ctx.repoBuildHours * HOUR_MS;
611
674
  const visit = (root, dir, depth) => {
612
- if (depth > MAX_WALK_DEPTH) return;
675
+ if (depth > ctx.maxDepth) return;
613
676
  let entries;
614
677
  try {
615
678
  entries = readdirSync(dir, { withFileTypes: true });
616
- } catch {
679
+ } catch (e) {
680
+ noteDenied(ctx, dir, e);
617
681
  return;
618
682
  }
619
683
  for (const e of entries) {
620
684
  if (!e.isDirectory() || e.isSymbolicLink()) continue;
621
685
  const p = join(dir, e.name);
686
+ if (devPruned(ctx, p, e.name)) continue;
622
687
  const shape = BUILD_SHAPE[e.name];
623
688
  if (shape) {
624
689
  if (!shape.some((n) => existsSync(join(p, n)))) {
625
690
  out.skipped.push({ path: p, reason: "does not look like build output" });
626
- } else if (ctx.now - newestMtime(p, 1) < maxAge) {
627
- out.skipped.push({ path: p, reason: "touched recently" });
628
691
  } else if (inUse(ctx, realOrNull(p) || p)) {
629
- out.skipped.push({ path: p, reason: "in use by a running process" });
692
+ hold(out, p, "in use by a running process", "live");
693
+ } else if (touchedWithin(ctx, newestMtime(p, 1), maxAge)) {
694
+ hold(out, p, "touched recently", "age");
630
695
  } else {
631
696
  addPath(out, ctx, p, [root]);
632
697
  }
@@ -644,26 +709,48 @@ function repoBuildCandidates(ctx, out) {
644
709
  function oldFiles(ctx, out, roots, maxAgeMs, match = () => true) {
645
710
  for (const root of roots) {
646
711
  if (!rootUsable(root, ctx, out)) continue;
647
- walk(root, 0, (p) => {
648
- if (match(p) && olderThan(p, maxAgeMs, ctx)) addPath(out, ctx, p, [root]);
649
- });
712
+ walk(
713
+ root,
714
+ (p) => {
715
+ if (match(p) && olderThan(p, maxAgeMs, ctx)) addPath(out, ctx, p, [root]);
716
+ },
717
+ { ctx },
718
+ );
719
+ }
720
+ }
721
+
722
+ // What an `xcodebuild -derivedDataPath` or a SwiftPM `--scratch-path` leaves in
723
+ // a temp folder, whatever the folder is called. Names are compared exactly:
724
+ // the volume is case-insensitive, and an iOS backup carries Manifest.db and
725
+ // Info.plist.
726
+ function looksLikeTmpBuild(p) {
727
+ let names;
728
+ try {
729
+ names = new Set(readdirSync(p));
730
+ } catch {
731
+ return false;
650
732
  }
733
+ const all = (...n) => n.every((x) => names.has(x));
734
+ if (names.has("ModuleCache.noindex") || all("Build", "Logs", "info.plist")) return true;
735
+ return names.has("build.db") && (names.has("workspace-state.json") || names.has("checkouts"));
651
736
  }
652
737
 
653
738
  function tmpBuildCandidates(ctx, out) {
654
739
  for (const root of ctx.tmpRoots) {
655
740
  if (!rootUsable(root, ctx, out)) continue;
656
- for (const p of listDir(root)) {
657
- if (!/^dd-/.test(basename(p))) continue;
741
+ for (const p of listDir(root, ctx)) {
742
+ const name = basename(p);
743
+ if (name.startsWith("claude-")) continue;
658
744
  const st = lstatOrNull(p);
659
745
  if (!st || !st.isDirectory()) continue;
660
746
  if (ctx.uid >= 0 && st.uid !== ctx.uid) continue;
661
- if (ctx.now - st.mtimeMs < ctx.tmpGraceMinutes * 60_000) {
662
- out.skipped.push({ path: p, reason: "touched recently" });
747
+ if (!/^dd-/.test(name) && !looksLikeTmpBuild(p)) continue;
748
+ if (inUse(ctx, realOrNull(p) || p)) {
749
+ hold(out, p, "in use by a running process", "live");
663
750
  continue;
664
751
  }
665
- if (inUse(ctx, realOrNull(p) || p)) {
666
- out.skipped.push({ path: p, reason: "in use by a running process" });
752
+ if (touchedWithin(ctx, st.mtimeMs, ctx.tmpGraceMinutes * 60_000)) {
753
+ hold(out, p, "touched recently", "age");
667
754
  continue;
668
755
  }
669
756
  addPath(out, ctx, p, [root]);
@@ -675,17 +762,20 @@ function claudeScratchCandidates(ctx, out) {
675
762
  for (const root of ctx.tmpRoots) {
676
763
  const base = join(root, `claude-${ctx.uid}`);
677
764
  if (!existsSync(base) || !rootUsable(base, ctx, out)) continue;
678
- for (const slug of listDir(base)) {
679
- for (const session of listDir(slug)) {
765
+ for (const slug of listDir(base, ctx)) {
766
+ for (const session of listDir(slug, ctx)) {
680
767
  const name = basename(session);
681
768
  if (!UUID.test(name)) continue;
682
769
  if (ctx.sessionId && name === ctx.sessionId) {
683
- out.skipped.push({ path: session, reason: "the current session" });
770
+ hold(out, session, "the current session", "live");
684
771
  continue;
685
772
  }
686
- if (ctx.now - newestMtime(session, 2) < ctx.scratchHours * HOUR_MS) continue;
687
773
  if (inUse(ctx, realOrNull(session) || session)) {
688
- out.skipped.push({ path: session, reason: "in use by a running process" });
774
+ hold(out, session, "in use by a running process", "live");
775
+ continue;
776
+ }
777
+ if (ctx.now - newestMtime(session, 2) < ctx.scratchHours * HOUR_MS) {
778
+ hold(out, session, "touched recently, may be another open session", "live");
689
779
  continue;
690
780
  }
691
781
  addPath(out, ctx, session, [base]);
@@ -699,20 +789,155 @@ function transcriptCandidates(ctx, out) {
699
789
  const roots = [H(ctx, ".claude", "projects"), H(ctx, ".codex", "sessions")];
700
790
  for (const root of roots) {
701
791
  if (!rootUsable(root, ctx, out)) continue;
702
- walk(root, 0, (p) => {
703
- if (!p.endsWith(".jsonl") || MEMORY_DIR.test(p)) return;
704
- if (ctx.sessionId && p.includes(ctx.sessionId)) {
705
- out.skipped.push({ path: p, reason: "the current session" });
706
- return;
707
- }
708
- if (!olderThan(p, maxAge, ctx)) return;
709
- if (inUse(ctx, realOrNull(p) || p)) {
710
- out.skipped.push({ path: p, reason: "in use by a running process" });
711
- return;
712
- }
713
- addPath(out, ctx, p, [root]);
792
+ walk(
793
+ root,
794
+ (p) => {
795
+ if (!p.endsWith(".jsonl") || MEMORY_DIR.test(p)) return;
796
+ if (ctx.sessionId && p.includes(ctx.sessionId)) {
797
+ out.skipped.push({ path: p, reason: "the current session" });
798
+ return;
799
+ }
800
+ if (!olderThan(p, maxAge, ctx)) return;
801
+ if (inUse(ctx, realOrNull(p) || p)) {
802
+ out.skipped.push({ path: p, reason: "in use by a running process" });
803
+ return;
804
+ }
805
+ addPath(out, ctx, p, [root]);
806
+ },
807
+ { ctx },
808
+ );
809
+ }
810
+ }
811
+
812
+ /** Every simulator device simctl knows, with its runtime id, or null when simctl fails. */
813
+ function readSimDevices(ctx) {
814
+ const r = ctx.run("xcrun", ["simctl", "list", "devices", "-j"], { timeout: 60_000 });
815
+ if (r.status !== 0) return null;
816
+ try {
817
+ const devices = [];
818
+ for (const [runtime, list] of Object.entries(JSON.parse(r.stdout).devices || {})) {
819
+ for (const d of list || []) devices.push({ ...d, runtime });
820
+ }
821
+ return { devices };
822
+ } catch {
823
+ return null;
824
+ }
825
+ }
826
+
827
+ function deviceBooted(ctx, udid) {
828
+ const sim = ctx.simDevices();
829
+ if (!sim) return true;
830
+ return sim.devices.some((d) => d.udid === udid && d.state !== "Shutdown");
831
+ }
832
+
833
+ function simDeviceCacheCandidates(ctx, out) {
834
+ const devicesRoot = realOrNull(H(ctx, "Library/Developer/CoreSimulator/Devices"));
835
+ if (!devicesRoot) return;
836
+ const sim = ctx.simDevices();
837
+ if (!sim) {
838
+ out.note = "could not list simulator devices, so every device cache was kept";
839
+ return;
840
+ }
841
+ for (const d of sim.devices) {
842
+ if (!d.dataPath || !d.udid) continue;
843
+ const caches = join(d.dataPath, "Library", "Caches");
844
+ const real = realOrNull(caches);
845
+ if (!real || !inside(real, devicesRoot)) continue;
846
+ if (d.state !== "Shutdown") {
847
+ hold(out, caches, "device is booted", "live");
848
+ continue;
849
+ }
850
+ if (!rootUsable(caches, ctx, out)) continue;
851
+ const label = `${d.name} (${String(d.udid).slice(0, 8)})`;
852
+ const recheck = (c) => (deviceBooted(c, d.udid) ? "device is booted" : null);
853
+ for (const p of listDir(caches, ctx)) addPath(out, ctx, p, [caches], { label, recheck });
854
+ }
855
+ }
856
+
857
+ function versionParts(v) {
858
+ return String(v)
859
+ .split(".")
860
+ .map((n) => Number.parseInt(n, 10) || 0);
861
+ }
862
+
863
+ export function compareVersions(a, b) {
864
+ const x = versionParts(a);
865
+ const y = versionParts(b);
866
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
867
+ const d = (x[i] || 0) - (y[i] || 0);
868
+ if (d) return d;
869
+ }
870
+ return 0;
871
+ }
872
+
873
+ function runtimePlatform(rt) {
874
+ return /SimRuntime\.([A-Za-z]+)-/.exec(rt.runtimeIdentifier || "")?.[1] || rt.platformIdentifier;
875
+ }
876
+
877
+ function bootedRuntimes(ctx) {
878
+ const sim = ctx.simDevices();
879
+ if (!sim) return null;
880
+ return new Set(sim.devices.filter((d) => d.state !== "Shutdown").map((d) => d.runtime));
881
+ }
882
+
883
+ /** Why a simulator runtime is kept, or null when it may be deleted. */
884
+ export function runtimeHoldReason(rt, ctx, newest, booted) {
885
+ if (rt.deletable !== true) return "not deletable";
886
+ if (!booted) return "could not list simulator devices";
887
+ if (booted.has(rt.runtimeIdentifier)) return "backs a booted device";
888
+ if (compareVersions(rt.version, newest.get(rt.platformIdentifier)) >= 0) {
889
+ return `newest ${runtimePlatform(rt)}`;
890
+ }
891
+ const used = Date.parse(rt.lastUsedAt || "");
892
+ if (!Number.isFinite(used)) return "last use unknown";
893
+ if (ctx.now - used < ctx.runtimeDays * DAY_MS) {
894
+ return `used in the last ${ctx.runtimeDays} days`;
895
+ }
896
+ return null;
897
+ }
898
+
899
+ function simRuntimeCandidates(ctx, out) {
900
+ const r = ctx.run("xcrun", ["simctl", "runtime", "list", "-j"], { timeout: 60_000 });
901
+ if (r.status !== 0) return;
902
+ let runtimes;
903
+ try {
904
+ runtimes = Object.values(JSON.parse(r.stdout) || {});
905
+ } catch {
906
+ return;
907
+ }
908
+ if (!runtimes.length) return;
909
+ const booted = bootedRuntimes(ctx);
910
+ const newest = new Map();
911
+ for (const rt of runtimes) {
912
+ const cur = newest.get(rt.platformIdentifier);
913
+ if (cur == null || compareVersions(rt.version, cur) > 0)
914
+ newest.set(rt.platformIdentifier, rt.version);
915
+ }
916
+ for (const rt of runtimes) {
917
+ const label = `${runtimePlatform(rt)} ${rt.version} (${rt.build})`;
918
+ const bytes = Number(rt.sizeBytes) || 0;
919
+ const reason = runtimeHoldReason(rt, ctx, newest, booted);
920
+ if (reason) {
921
+ const kind = reason === "backs a booted device" ? "live" : "policy";
922
+ hold(out, label, reason, kind, bytes);
923
+ continue;
924
+ }
925
+ out.candidates.push({
926
+ kind: "command",
927
+ cmd: "xcrun",
928
+ args: ["simctl", "runtime", "delete", rt.identifier],
929
+ path: label,
930
+ measure: [],
931
+ bytes,
932
+ recheck: (c) => {
933
+ const now = bootedRuntimes(c);
934
+ return !now || now.has(rt.runtimeIdentifier) ? "backs a booted device" : null;
935
+ },
714
936
  });
715
937
  }
938
+ if (out.candidates.length && !out.note) {
939
+ out.note = "CoreSimulator frees runtime space in the background; df right after can undercount";
940
+ }
716
941
  }
717
942
 
718
943
  /** Orphaned session children, for the report only: pid and command, nothing to act on. */
@@ -781,9 +1006,12 @@ export const CATEGORIES = [
781
1006
  unattended: true,
782
1007
  blocker: [XCODE, "Xcode or xcodebuild is running"],
783
1008
  discover: (ctx, out) =>
784
- childrenOf(ctx, out, [H(ctx, "Library/Developer/XCTestDevices")], (p) =>
785
- olderThan(p, ctx.repoBuildHours * HOUR_MS, ctx),
786
- ),
1009
+ childrenOf(ctx, out, [H(ctx, "Library/Developer/XCTestDevices")], (p) => {
1010
+ if (!touchedWithin(ctx, lstatOrNull(p)?.mtimeMs ?? 0, ctx.repoBuildHours * HOUR_MS))
1011
+ return true;
1012
+ hold(out, p, "touched recently", "age");
1013
+ return false;
1014
+ }),
787
1015
  },
788
1016
  {
789
1017
  id: "xcode-caches",
@@ -795,6 +1023,7 @@ export const CATEGORIES = [
795
1023
  H(ctx, "Library/Developer/Xcode/UserData/Previews"),
796
1024
  H(ctx, "Library/Developer/Xcode/UserData/IB Support"),
797
1025
  H(ctx, "Library/Developer/Xcode/DocumentationCache"),
1026
+ H(ctx, "Library/Developer/Xcode/DocumentationIndex"),
798
1027
  ]),
799
1028
  },
800
1029
  {
@@ -878,6 +1107,19 @@ export const CATEGORIES = [
878
1107
  discover: (ctx, out) =>
879
1108
  childrenOf(ctx, out, [H(ctx, "Library/Developer/CoreSimulator/Caches")]),
880
1109
  },
1110
+ {
1111
+ id: "sim-device-caches",
1112
+ label: "each shut-down simulator device's own system cache (data/Library/Caches)",
1113
+ unattended: true,
1114
+ discover: simDeviceCacheCandidates,
1115
+ },
1116
+ {
1117
+ id: "sim-runtimes",
1118
+ label:
1119
+ "simulator runtimes not used for the runtime age; never the newest per platform or a booted one",
1120
+ unattended: false,
1121
+ discover: simRuntimeCandidates,
1122
+ },
881
1123
  {
882
1124
  id: "spm-cache",
883
1125
  label: "SwiftPM package cache",
@@ -932,7 +1174,8 @@ export const CATEGORIES = [
932
1174
  },
933
1175
  {
934
1176
  id: "tmp-builds",
935
- label: "build leftovers in /tmp and $TMPDIR (dd-*)",
1177
+ label:
1178
+ "build leftovers in /tmp and $TMPDIR (dd-*, or shaped like DerivedData or SwiftPM output)",
936
1179
  unattended: true,
937
1180
  discover: tmpBuildCandidates,
938
1181
  },
@@ -1021,6 +1264,21 @@ export function selectCategories(sel = {}) {
1021
1264
 
1022
1265
  // ---------------------------------------------------------------- plan / apply
1023
1266
 
1267
+ function excludedBy(ctx, path) {
1268
+ const p = nativeReal(path) || path;
1269
+ return ctx.excludes.some((e) => p === e || inside(p, e) || inside(e, p));
1270
+ }
1271
+
1272
+ /** Move every candidate at, under or above an excluded path to the kept list. */
1273
+ function applyExcludes(ctx, out) {
1274
+ if (!ctx.excludes.length) return;
1275
+ out.candidates = out.candidates.filter((c) => {
1276
+ if (c.kind === "command" || !excludedBy(ctx, c.path)) return true;
1277
+ out.skipped.push({ path: c.path, reason: "excluded" });
1278
+ return false;
1279
+ });
1280
+ }
1281
+
1024
1282
  /** Measure every selected category. Deletes nothing. */
1025
1283
  export function plan(ctx, sel = {}) {
1026
1284
  const categories = [];
@@ -1031,27 +1289,49 @@ export function plan(ctx, sel = {}) {
1031
1289
  out.note = `${cat.blocker[1]}; measured, not applied`;
1032
1290
  }
1033
1291
  cat.discover(ctx, out);
1292
+ applyExcludes(ctx, out);
1034
1293
  const toMeasure = [];
1035
1294
  for (const c of out.candidates) {
1036
1295
  if (c.kind === "path" || c.kind === "worktree") toMeasure.push(c.path);
1037
1296
  else if (c.kind === "command") toMeasure.push(...c.measure);
1038
1297
  else if (c.kind === "delegate" && c.bytes == null) toMeasure.push(c.path);
1039
1298
  }
1299
+ const heldItems = out.skipped.filter((k) => k.held);
1300
+ for (const k of heldItems) if (k.bytes == null && existsSync(k.path)) toMeasure.push(k.path);
1040
1301
  const sizes = toMeasure.length ? ctx.du(toMeasure) : new Map();
1041
1302
  for (const c of out.candidates) {
1042
- if (c.kind === "command") c.bytes = c.measure.reduce((s, p) => s + (sizes.get(p) || 0), 0);
1043
- else if (c.bytes == null) c.bytes = sizes.get(c.path) ?? 0;
1303
+ if (c.kind === "command" && c.bytes == null) {
1304
+ c.bytes = c.measure.reduce((s, p) => s + (sizes.get(p) || 0), 0);
1305
+ } else if (c.bytes == null) c.bytes = sizes.get(c.path) ?? 0;
1044
1306
  c.category = cat.id;
1045
1307
  out.bytes += c.bytes;
1046
1308
  }
1309
+ out.held = { items: 0, bytes: 0, aged: 0, agedBytes: 0, live: 0 };
1310
+ for (const k of heldItems) {
1311
+ if (k.bytes == null) k.bytes = sizes.get(k.path) ?? 0;
1312
+ out.held.items++;
1313
+ out.held.bytes += k.bytes;
1314
+ if (k.held === "age") {
1315
+ out.held.aged++;
1316
+ out.held.agedBytes += k.bytes;
1317
+ } else if (k.held === "live") out.held.live++;
1318
+ }
1047
1319
  categories.push(out);
1048
1320
  }
1049
1321
  return {
1050
1322
  categories,
1051
1323
  totalBytes: categories.reduce((s, c) => s + c.bytes, 0),
1324
+ held: sumHeld(categories),
1325
+ unreadable: { count: ctx.denied.size, sample: [...ctx.denied].slice(0, 3) },
1052
1326
  };
1053
1327
  }
1054
1328
 
1329
+ function sumHeld(categories) {
1330
+ const total = { items: 0, bytes: 0, aged: 0, agedBytes: 0, live: 0 };
1331
+ for (const c of categories) for (const k of Object.keys(total)) total[k] += c.held[k];
1332
+ return total;
1333
+ }
1334
+
1055
1335
  function deletePath(ctx, c) {
1056
1336
  const g = guardPath(c.path, ctx, c.roots);
1057
1337
  if (!g.ok) return { ok: false, reason: g.reason };
@@ -1111,6 +1391,11 @@ export function applyPlan(ctx, planned) {
1111
1391
  }
1112
1392
  const delegates = new Map();
1113
1393
  for (const c of cat.candidates) {
1394
+ const why = c.recheck?.(ctx);
1395
+ if (why) {
1396
+ result.held.push({ category: cat.id, path: c.path, reason: why });
1397
+ continue;
1398
+ }
1114
1399
  let r;
1115
1400
  if (c.kind === "path") r = deletePath(ctx, c);
1116
1401
  else if (c.kind === "worktree") r = removeWorktree(ctx, c);
@@ -1142,7 +1427,7 @@ export function applyPlan(ctx, planned) {
1142
1427
  // ---------------------------------------------------------------- CLI
1143
1428
 
1144
1429
  function parseCli(argv) {
1145
- const o = { only: [], skip: [], tmpRoots: [], devRoots: [] };
1430
+ const o = { only: [], skip: [], tmpRoots: [], devRoots: [], excludes: [] };
1146
1431
  const num = (k, v) => {
1147
1432
  if (!/^\d+$/.test(v)) throw new Error(`${k} needs a whole number, got "${v}"`);
1148
1433
  return Number(v);
@@ -1165,6 +1450,19 @@ function parseCli(argv) {
1165
1450
  case "--list":
1166
1451
  o[k.slice(2)] = true;
1167
1452
  break;
1453
+ case "--include-recent":
1454
+ o.includeRecent = true;
1455
+ break;
1456
+ case "--exclude":
1457
+ if (!v) throw new Error("--exclude needs a path");
1458
+ o.excludes.push(v);
1459
+ break;
1460
+ case "--depth":
1461
+ o.depth = num(k, v);
1462
+ break;
1463
+ case "--runtime-days":
1464
+ o.runtimeDays = num(k, v);
1465
+ break;
1168
1466
  case "--only":
1169
1467
  case "--skip":
1170
1468
  o[k.slice(2)].push(...v.split(",").filter(Boolean));
@@ -1244,7 +1542,12 @@ export function categorySummary(c, top = DEFAULT_TOP) {
1244
1542
  const kept = {};
1245
1543
  for (const k of c.skipped) kept[k.reason] = (kept[k.reason] || 0) + 1;
1246
1544
  return {
1247
- top: sorted.slice(0, top).map((x) => ({ path: x.path, bytes: x.bytes, kind: x.kind })),
1545
+ top: sorted.slice(0, top).map((x) => ({
1546
+ path: x.path,
1547
+ bytes: x.bytes,
1548
+ kind: x.kind,
1549
+ ...(x.label ? { label: x.label } : {}),
1550
+ })),
1248
1551
  more: Math.max(0, sorted.length - top),
1249
1552
  kept,
1250
1553
  };
@@ -1273,7 +1576,9 @@ function printPlan(p, mode, disk, top = 0) {
1273
1576
  if (top > 0) {
1274
1577
  const s = categorySummary(c, top);
1275
1578
  for (const x of s.top)
1276
- lines.push(`${"".padEnd(18)} ${human(x.bytes).padStart(16)} ${x.path}`);
1579
+ lines.push(
1580
+ `${"".padEnd(18)} ${human(x.bytes).padStart(16)} ${x.label ? `${x.label} ` : ""}${x.path}`,
1581
+ );
1277
1582
  if (s.more) lines.push(`${"".padEnd(18)} ${"".padStart(16)} + ${s.more} more`);
1278
1583
  }
1279
1584
  }
@@ -1281,6 +1586,26 @@ function printPlan(p, mode, disk, top = 0) {
1281
1586
  return lines.join("\n");
1282
1587
  }
1283
1588
 
1589
+ function heldLines(p, includeRecent) {
1590
+ const out = [];
1591
+ const h = p.held;
1592
+ if (h.items) {
1593
+ const parts = [
1594
+ `${h.aged} by age only (${human(h.agedBytes)})`,
1595
+ `${h.live} in use`,
1596
+ `${h.items - h.aged - h.live} by a category rule`,
1597
+ ];
1598
+ const hint = h.aged && !includeRecent ? "; --include-recent includes the age-held ones" : "";
1599
+ out.push(`held back: ${h.items} items (${human(h.bytes)}): ${parts.join(", ")}${hint}`);
1600
+ }
1601
+ if (p.unreadable.count) {
1602
+ out.push(
1603
+ `unreadable: ${p.unreadable.count} folders (permission denied), so this report is incomplete; grant the terminal Full Disk Access to measure them`,
1604
+ );
1605
+ }
1606
+ return out;
1607
+ }
1608
+
1284
1609
  function summarizeSkips(p) {
1285
1610
  const out = [];
1286
1611
  for (const c of p.categories) {
@@ -1321,6 +1646,26 @@ export function main(argv, env = process.env) {
1321
1646
  }
1322
1647
  const unattended = Boolean(o.unattended) || env.MULTI_AGENT_UNATTENDED === "1";
1323
1648
  if (o.dryRun) o.apply = false;
1649
+ let depth = o.depth;
1650
+ if (depth == null && env.DISK_CLEANER_DEPTH) {
1651
+ if (!/^\d+$/.test(env.DISK_CLEANER_DEPTH)) {
1652
+ process.stderr.write("disk-cleaner: DISK_CLEANER_DEPTH needs a whole number\n");
1653
+ return 2;
1654
+ }
1655
+ depth = Number(env.DISK_CLEANER_DEPTH);
1656
+ }
1657
+ const home = o.home || homedir();
1658
+ const excludes = [];
1659
+ for (const raw of [...(env.DISK_CLEANER_EXCLUDE?.split(":") ?? []), ...o.excludes]) {
1660
+ if (!raw) continue;
1661
+ const expanded = raw === "~" ? home : raw.startsWith("~/") ? join(home, raw.slice(2)) : raw;
1662
+ const real = nativeReal(expanded);
1663
+ if (!real) {
1664
+ process.stderr.write(`disk-cleaner: --exclude path does not exist: ${raw}\n`);
1665
+ return 2;
1666
+ }
1667
+ excludes.push(real);
1668
+ }
1324
1669
  const ctx = makeContext({
1325
1670
  home: o.home,
1326
1671
  tmpRoots: o.tmpRoots.length ? o.tmpRoots : undefined,
@@ -1331,6 +1676,10 @@ export function main(argv, env = process.env) {
1331
1676
  scratchHours: o.scratchHours,
1332
1677
  repoBuildHours: o.buildHours,
1333
1678
  orphanMinutes: o.orphanMinutes,
1679
+ runtimeDays: o.runtimeDays,
1680
+ maxDepth: depth,
1681
+ excludes,
1682
+ includeRecent: unattended ? false : Boolean(o.includeRecent),
1334
1683
  ...(noProbes
1335
1684
  ? { ps: () => [], openPaths: () => [], run: () => ({ status: 127, stdout: "", stderr: "" }) }
1336
1685
  : {}),
@@ -1349,6 +1698,7 @@ export function main(argv, env = process.env) {
1349
1698
  version: VERSION,
1350
1699
  mode,
1351
1700
  unattended,
1701
+ includeRecent: ctx.includeRecent,
1352
1702
  startedAt: new Date(ctx.now).toISOString(),
1353
1703
  disk: {
1354
1704
  before,
@@ -1356,6 +1706,8 @@ export function main(argv, env = process.env) {
1356
1706
  },
1357
1707
  totalBytes: planned.totalBytes,
1358
1708
  reclaimableBytes: reclaimable(planned),
1709
+ held: planned.held,
1710
+ unreadable: planned.unreadable,
1359
1711
  categories: planned.categories.map((c) => ({
1360
1712
  id: c.id,
1361
1713
  label: c.label,
@@ -1363,6 +1715,7 @@ export function main(argv, env = process.env) {
1363
1715
  note: c.note,
1364
1716
  candidates: c.candidates.map((x) => ({ path: x.path, bytes: x.bytes, kind: x.kind })),
1365
1717
  skipped: c.skipped,
1718
+ held: c.held,
1366
1719
  blocked: c.blocked || null,
1367
1720
  ...categorySummary(c, o.top ?? DEFAULT_TOP),
1368
1721
  })),
@@ -1398,7 +1751,11 @@ export function main(argv, env = process.env) {
1398
1751
  if (o.json) {
1399
1752
  process.stdout.write(JSON.stringify(report, null, 2) + "\n");
1400
1753
  } else {
1401
- const lines = [printPlan(planned, mode, before, o.top || 0), ...summarizeSkips(planned)];
1754
+ const lines = [
1755
+ printPlan(planned, mode, before, o.top || 0),
1756
+ ...summarizeSkips(planned),
1757
+ ...heldLines(planned, ctx.includeRecent),
1758
+ ];
1402
1759
  if (report.orphans.length) {
1403
1760
  lines.push(
1404
1761
  `orphaned session processes: ${report.orphans.length} (information only; never stopped)`,
@@ -1411,7 +1768,9 @@ export function main(argv, env = process.env) {
1411
1768
  for (const f of applied.failures.slice(0, 10)) {
1412
1769
  lines.push(` failed ${f.category}: ${f.path} (${f.reason})`);
1413
1770
  }
1414
- for (const h of applied.held) lines.push(` held ${h.category}: ${h.reason}`);
1771
+ for (const h of applied.held) {
1772
+ lines.push(` held ${h.category}: ${h.reason}${h.path ? ` (${h.path})` : ""}`);
1773
+ }
1415
1774
  } else {
1416
1775
  lines.push("re-run with --apply to delete the listed items");
1417
1776
  }