@mmerterden/multi-agent-pipeline 20.41.0 → 20.43.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/CHANGELOG.md +56 -0
- package/README.md +8 -6
- package/README.tr.md +8 -6
- package/docs/architecture.md +3 -3
- package/docs/ecosystem.md +50 -13
- package/docs/facts.json +9 -9
- package/docs/features.md +9 -4
- package/install/claude.mjs +34 -1
- package/install/templates/claude-hooks.json +12 -1
- package/manifest.json +117 -90
- package/package.json +3 -2
- package/pipeline/commands/multi-agent/autopilot/SKILL.md +11 -0
- package/pipeline/commands/multi-agent/clean-disk/SKILL.md +134 -0
- package/pipeline/commands/multi-agent/review-priority/SKILL.md +143 -0
- package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
- package/pipeline/commands/multi-agent/sync/SKILL.md +4 -4
- package/pipeline/lib/args.mjs +131 -4
- package/pipeline/lib/bg-launch.mjs +5 -2
- package/pipeline/lib/credential-store.sh +11 -1
- package/pipeline/lib/hook-once.mjs +134 -0
- package/pipeline/lib/isotonic.mjs +73 -0
- package/pipeline/lib/low-disk.mjs +154 -0
- package/pipeline/lib/mcp-schema-load.mjs +90 -0
- package/pipeline/lib/md2confluence-v3.py +8 -7
- package/pipeline/lib/model-dispatch.sh +26 -2
- package/pipeline/lib/normalize-text.mjs +135 -0
- package/pipeline/lib/outbound-gate.mjs +21 -3
- package/pipeline/lib/plan-todos.sh +17 -4
- package/pipeline/lib/redact.mjs +12 -3
- package/pipeline/lib/risky-settings.mjs +198 -0
- package/pipeline/lib/route-state.sh +1 -0
- package/pipeline/lib/secret-patterns.generated.mjs +6 -2
- package/pipeline/lib/session-usage.mjs +232 -0
- package/pipeline/lib/source-digest.mjs +211 -0
- package/pipeline/lib/tdd-evidence.mjs +250 -17
- package/pipeline/lib/untrusted-fence.mjs +132 -1
- package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
- package/pipeline/multi-agent-refs/cross-cli-contract.md +5 -5
- package/pipeline/multi-agent-refs/features/cost-analysis.md +37 -2
- package/pipeline/multi-agent-refs/features/doctor.md +66 -4
- package/pipeline/multi-agent-refs/features/model-fallback.md +25 -0
- package/pipeline/multi-agent-refs/features/plan-todos.md +4 -0
- package/pipeline/multi-agent-refs/features/review-priority.md +123 -0
- package/pipeline/multi-agent-refs/features/unattended-gates.md +5 -3
- package/pipeline/multi-agent-refs/features/usage-reporting.md +4 -2
- package/pipeline/multi-agent-refs/help/en.md +3 -1
- package/pipeline/multi-agent-refs/help/tr.md +3 -1
- package/pipeline/multi-agent-refs/outside-the-pipeline.md +6 -0
- package/pipeline/multi-agent-refs/phases/phase-1-plan.md +1 -1
- package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
- package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -2
- package/pipeline/multi-agent-refs/phases/phase-5-report.md +2 -0
- package/pipeline/multi-agent-refs/progress-contract.md +3 -1
- package/pipeline/multi-agent-refs/review-priority/rules/example.md +137 -0
- package/pipeline/office/toolkit.json +1 -1
- package/pipeline/rules/outside-the-pipeline.md +1 -1
- package/pipeline/schemas/doctor-report.schema.json +47 -0
- package/pipeline/schemas/plan-todos.schema.json +29 -1
- package/pipeline/schemas/prefs.schema.json +81 -0
- package/pipeline/schemas/route-config.schema.json +51 -0
- package/pipeline/schemas/secret-patterns.json +17 -1
- package/pipeline/schemas/toolkit-path-params.json +15 -1
- package/pipeline/scripts/_cost-advise.mjs +357 -0
- package/pipeline/scripts/_cost-budget.mjs +78 -0
- package/pipeline/scripts/_cost.mjs +29 -0
- package/pipeline/scripts/_decode_text.py +107 -0
- package/pipeline/scripts/_guard-probe.mjs +406 -0
- package/pipeline/scripts/_guard_rules.py +206 -0
- package/pipeline/scripts/_memory-policy.mjs +1 -25
- package/pipeline/scripts/_retrieval.mjs +148 -2
- package/pipeline/scripts/_secret-scan.mjs +6 -1
- package/pipeline/scripts/_stack-routing.mjs +1 -0
- package/pipeline/scripts/_test-gaming.mjs +346 -0
- package/pipeline/scripts/agent-guard.py +8 -1
- package/pipeline/scripts/argv-secret-scan.mjs +2 -1
- package/pipeline/scripts/autopilot-loop.mjs +407 -0
- package/pipeline/scripts/autopilot-runner.mjs +38 -25
- package/pipeline/scripts/capture-resume.sh +9 -1
- package/pipeline/scripts/cost-analyze.mjs +66 -4
- package/pipeline/scripts/cost-budget-check.mjs +5 -13
- package/pipeline/scripts/disk-cleaner.mjs +1432 -0
- package/pipeline/scripts/doctor.mjs +302 -47
- package/pipeline/scripts/evidence-gate.mjs +90 -0
- package/pipeline/scripts/gate-ledger.mjs +76 -21
- package/pipeline/scripts/gc-tmp.sh +5 -0
- package/pipeline/scripts/guard-probe-known-holes.json +3 -0
- package/pipeline/scripts/learnings-ledger.mjs +16 -12
- package/pipeline/scripts/note-agent-event.mjs +2 -0
- package/pipeline/scripts/note-mcp-failure.mjs +9 -2
- package/pipeline/scripts/note-skill-use.mjs +4 -1
- package/pipeline/scripts/pre-commit-check.sh +2 -2
- package/pipeline/scripts/pre-push-check.sh +8 -1
- package/pipeline/scripts/priority-review.mjs +912 -0
- package/pipeline/scripts/publish-staged.mjs +324 -0
- package/pipeline/scripts/route-learn.mjs +628 -0
- package/pipeline/scripts/run-scope-guard.mjs +55 -1
- package/pipeline/scripts/scan-agent-config.sh +1 -1
- package/pipeline/scripts/statusline.mjs +309 -0
- package/pipeline/scripts/test-integrity-gate.mjs +97 -2
- package/pipeline/scripts/triage-memory.mjs +12 -4
- package/pipeline/scripts/uninstall.mjs +1 -0
- package/pipeline/skills/.skill-manifest.json +17 -5
- package/pipeline/skills/.skills-index.json +36 -3
- package/pipeline/skills/shared/README.md +9 -6
- package/pipeline/skills/shared/core/multi-agent-clean-disk/SKILL.md +34 -0
- package/pipeline/skills/shared/core/multi-agent-review-priority/SKILL.md +36 -0
- package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +4 -4
- package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
- package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +111 -0
- package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +62 -0
- package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +1432 -0
- package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
- package/pipeline/skills/skill-copies.json +4 -0
- package/pipeline/skills/skills-index.md +5 -2
|
@@ -0,0 +1,1432 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* @file disk-cleaner.mjs - frees disk space on a macOS developer machine by
|
|
4
|
+
* deleting regenerable data from a fixed category allowlist, and nothing else.
|
|
5
|
+
*
|
|
6
|
+
* Measure first: the default run is a dry run that lists every candidate with
|
|
7
|
+
* its size and category, writes a JSON report and deletes nothing. `--apply`
|
|
8
|
+
* deletes the listed candidates; each category can be left out with --skip.
|
|
9
|
+
*
|
|
10
|
+
* Safety rules, enforced on every candidate at plan time and again right
|
|
11
|
+
* before it is deleted:
|
|
12
|
+
* - a symlink is never followed and never deleted; a category root that is a
|
|
13
|
+
* symlink is skipped whole
|
|
14
|
+
* - the real path must sit strictly inside one of the category's roots
|
|
15
|
+
* - never under ~/Documents, ~/Desktop, ~/Downloads, ~/Pictures, ~/Movies,
|
|
16
|
+
* ~/Music, iCloud Drive or CloudStorage, keychains, ~/.ssh, credential
|
|
17
|
+
* folders, or a memory folder under ~/.claude/projects
|
|
18
|
+
* - never a directory that is a git working tree, except a worktree under
|
|
19
|
+
* <repo>/.claude/worktrees that is clean, merged and not in use, removed
|
|
20
|
+
* through `git worktree remove`
|
|
21
|
+
* - never a file the user does not own, and never a path an open file
|
|
22
|
+
* handle or a running command line points into
|
|
23
|
+
*
|
|
24
|
+
* The Trash and old session transcripts are opt-in (--trash, --transcripts):
|
|
25
|
+
* the Trash holds the user's own files, and resume and past-session search
|
|
26
|
+
* read the transcripts. Processes are never stopped: orphaned children of
|
|
27
|
+
* ended sessions are listed in the report under `orphans` as information, and
|
|
28
|
+
* nothing here can signal a process. Unattended runs (--unattended or
|
|
29
|
+
* MULTI_AGENT_UNATTENDED=1) keep to UNATTENDED_SAFE and never touch the Trash,
|
|
30
|
+
* transcripts, worktrees, archives or device support.
|
|
31
|
+
*
|
|
32
|
+
* Deletion uses fs.rmSync, which unlinks a symlink instead of entering it.
|
|
33
|
+
* Pipeline scratch under /tmp and per-task pipeline logs are delegated to
|
|
34
|
+
* gc-tmp.sh and prune-logs.sh when those are installed, so their own grace
|
|
35
|
+
* windows and resumable-run rules apply.
|
|
36
|
+
*
|
|
37
|
+
* Usage:
|
|
38
|
+
* disk-cleaner.mjs [--dry-run] [--apply] [--only=a,b] [--skip=a,b]
|
|
39
|
+
* [--trash] [--transcripts] [--unattended]
|
|
40
|
+
* [--log-days=N] [--archive-days=N] [--transcript-days=N]
|
|
41
|
+
* [--scratch-hours=N] [--build-hours=N] [--orphan-minutes=N]
|
|
42
|
+
* [--root=DIR]... [--tmp-root=DIR]... [--home=DIR]
|
|
43
|
+
* [--report=FILE] [--json] [--list] [--top=N]
|
|
44
|
+
*
|
|
45
|
+
* Every category in the JSON report carries `top` (its largest items, real
|
|
46
|
+
* paths and sizes, 5 unless --top says otherwise), `more` (how many items
|
|
47
|
+
* `top` leaves out) and `kept` (how many items were kept, per reason). The
|
|
48
|
+
* report also carries `reclaimableBytes` (categories whose tool is running
|
|
49
|
+
* are measured but left out) and `disk.expectedFreeBytes`. --top=N also lists
|
|
50
|
+
* the top items under each row of the text table.
|
|
51
|
+
*
|
|
52
|
+
* Exit: 0 done, 1 one or more deletions failed, 2 usage error.
|
|
53
|
+
*
|
|
54
|
+
* @module disk-cleaner
|
|
55
|
+
*/
|
|
56
|
+
|
|
57
|
+
import { spawnSync } from "node:child_process";
|
|
58
|
+
import {
|
|
59
|
+
existsSync,
|
|
60
|
+
lstatSync,
|
|
61
|
+
mkdirSync,
|
|
62
|
+
readdirSync,
|
|
63
|
+
realpathSync,
|
|
64
|
+
readFileSync,
|
|
65
|
+
rmSync,
|
|
66
|
+
statfsSync,
|
|
67
|
+
writeFileSync,
|
|
68
|
+
} from "node:fs";
|
|
69
|
+
import { homedir, tmpdir } from "node:os";
|
|
70
|
+
import { basename, dirname, join, sep } from "node:path";
|
|
71
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
72
|
+
|
|
73
|
+
export const VERSION = "1.1.0";
|
|
74
|
+
const DAY_MS = 86_400_000;
|
|
75
|
+
const HOUR_MS = 3_600_000;
|
|
76
|
+
const MAX_WALK_DEPTH = 8;
|
|
77
|
+
const KEEP_REPORTS = 20;
|
|
78
|
+
const DEFAULT_TOP = 5;
|
|
79
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
80
|
+
|
|
81
|
+
/** Folders under $HOME that hold the user's own files or secrets. */
|
|
82
|
+
export const PROTECTED_HOME = [
|
|
83
|
+
"Documents",
|
|
84
|
+
"Desktop",
|
|
85
|
+
"Downloads",
|
|
86
|
+
"Pictures",
|
|
87
|
+
"Movies",
|
|
88
|
+
"Music",
|
|
89
|
+
"Library/Mobile Documents",
|
|
90
|
+
"Library/CloudStorage",
|
|
91
|
+
"Library/Keychains",
|
|
92
|
+
"Library/Application Support/MobileSync",
|
|
93
|
+
".ssh",
|
|
94
|
+
".gnupg",
|
|
95
|
+
".aws",
|
|
96
|
+
".kube",
|
|
97
|
+
".docker",
|
|
98
|
+
".config/gh",
|
|
99
|
+
".netrc",
|
|
100
|
+
];
|
|
101
|
+
const MEMORY_DIR = /\/\.claude\/projects\/[^/]+\/memory(\/|$)/;
|
|
102
|
+
|
|
103
|
+
/** Cache folders under ~/Library/Caches that belong to developer tools. */
|
|
104
|
+
export const DEV_CACHE_DIRS = [
|
|
105
|
+
"com.apple.dt.Xcode",
|
|
106
|
+
"com.apple.dt.instruments",
|
|
107
|
+
"JetBrains",
|
|
108
|
+
"ms-playwright",
|
|
109
|
+
"ms-playwright-go",
|
|
110
|
+
"node-gyp",
|
|
111
|
+
"typescript",
|
|
112
|
+
"pip",
|
|
113
|
+
"go-build",
|
|
114
|
+
"com.microsoft.VSCode.ShipIt",
|
|
115
|
+
];
|
|
116
|
+
|
|
117
|
+
const WALK_SKIP = new Set([".git", "node_modules", ".build", "DerivedData", "Pods", "build"]);
|
|
118
|
+
|
|
119
|
+
// Session children that outlive their session: log watchers, a symbol upload
|
|
120
|
+
// that never finished, and the shell wrapper Claude Code starts commands in.
|
|
121
|
+
const ORPHAN_PATTERNS = [
|
|
122
|
+
/^(\S*\/)?tail\s+(?:.*\s)?(-\S*[fF]\S*|--follow)(\s|$)/,
|
|
123
|
+
/(^|\/)upload-symbols(\s|$)/,
|
|
124
|
+
/^(\S*\/)?(ba|z)?sh\s+-c\b.*\/\.claude\/shell-snapshots\//,
|
|
125
|
+
];
|
|
126
|
+
|
|
127
|
+
// ---------------------------------------------------------------- utilities
|
|
128
|
+
|
|
129
|
+
function lstatOrNull(p) {
|
|
130
|
+
try {
|
|
131
|
+
return lstatSync(p);
|
|
132
|
+
} catch {
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function realOrNull(p) {
|
|
138
|
+
try {
|
|
139
|
+
return realpathSync(p);
|
|
140
|
+
} catch {
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function listDir(dir) {
|
|
146
|
+
try {
|
|
147
|
+
return readdirSync(dir).map((n) => join(dir, n));
|
|
148
|
+
} catch {
|
|
149
|
+
return [];
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** /tmp and /var are links to /private on macOS; compare in one spelling. */
|
|
154
|
+
export function normalizeTmp(p) {
|
|
155
|
+
return String(p).replace(/^\/(tmp|var|etc)(\/|$)/, "/private/$1$2");
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function inside(child, parent) {
|
|
159
|
+
return child.startsWith(parent.endsWith(sep) ? parent : parent + sep);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Seconds from a ps etime field: [[dd-]hh:]mm:ss. */
|
|
163
|
+
export function parseEtime(s) {
|
|
164
|
+
const m = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(String(s).trim());
|
|
165
|
+
if (!m) return 0;
|
|
166
|
+
const [, d, h, mi, se] = m;
|
|
167
|
+
return Number(d || 0) * 86400 + Number(h || 0) * 3600 + Number(mi) * 60 + Number(se);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function human(bytes) {
|
|
171
|
+
if (bytes == null) return "?";
|
|
172
|
+
if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`;
|
|
173
|
+
if (bytes >= 1e6) return `${Math.round(bytes / 1e6)} MB`;
|
|
174
|
+
return `${Math.round(bytes / 1e3)} KB`;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function realRun(cmd, args, opts = {}) {
|
|
178
|
+
const r = spawnSync(cmd, args, {
|
|
179
|
+
encoding: "utf8",
|
|
180
|
+
timeout: opts.timeout ?? 120_000,
|
|
181
|
+
maxBuffer: 256 * 1024 * 1024,
|
|
182
|
+
...opts,
|
|
183
|
+
});
|
|
184
|
+
return { status: r.status ?? 127, stdout: r.stdout || "", stderr: r.stderr || "" };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function realPs() {
|
|
188
|
+
const r = realRun("ps", ["-axww", "-o", "pid=,ppid=,uid=,etime=,command="], { timeout: 10_000 });
|
|
189
|
+
if (r.status !== 0) return [];
|
|
190
|
+
const rows = [];
|
|
191
|
+
for (const line of r.stdout.split("\n")) {
|
|
192
|
+
const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/.exec(line);
|
|
193
|
+
if (!m) continue;
|
|
194
|
+
rows.push({
|
|
195
|
+
pid: Number(m[1]),
|
|
196
|
+
ppid: Number(m[2]),
|
|
197
|
+
uid: Number(m[3]),
|
|
198
|
+
etimeSec: parseEtime(m[4]),
|
|
199
|
+
command: m[5],
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
return rows;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function realOpenPaths(uid) {
|
|
206
|
+
const r = realRun("lsof", ["-nP", "-w", "-u", String(uid), "-Fn"], { timeout: 60_000 });
|
|
207
|
+
return r.stdout
|
|
208
|
+
.split("\n")
|
|
209
|
+
.filter((l) => l.startsWith("n/"))
|
|
210
|
+
.map((l) => l.slice(1));
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Sizes in bytes for many paths, one du call per batch. */
|
|
214
|
+
function duBytes(paths) {
|
|
215
|
+
const out = new Map();
|
|
216
|
+
for (let i = 0; i < paths.length; i += 200) {
|
|
217
|
+
const batch = paths.slice(i, i + 200);
|
|
218
|
+
const r = spawnSync("du", ["-sk", ...batch], {
|
|
219
|
+
encoding: "utf8",
|
|
220
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
221
|
+
});
|
|
222
|
+
for (const line of (r.stdout || "").split("\n")) {
|
|
223
|
+
const tab = line.indexOf("\t");
|
|
224
|
+
if (tab < 0) continue;
|
|
225
|
+
out.set(line.slice(tab + 1), Number(line.slice(0, tab)) * 1024);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
return out;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export function diskStatus(path) {
|
|
232
|
+
try {
|
|
233
|
+
const s = statfsSync(path);
|
|
234
|
+
return { freeBytes: s.bavail * s.bsize, totalBytes: s.blocks * s.bsize };
|
|
235
|
+
} catch {
|
|
236
|
+
return { freeBytes: null, totalBytes: null };
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// ---------------------------------------------------------------- context
|
|
241
|
+
|
|
242
|
+
function defaultScriptsDir(home) {
|
|
243
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
244
|
+
if (existsSync(join(here, "gc-tmp.sh"))) return here;
|
|
245
|
+
return join(home, ".claude", "scripts");
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function defaultDevRoots(home) {
|
|
249
|
+
const roots = [];
|
|
250
|
+
const containers = ["", "Developer", "Projects", "src", "code", "repos", "work", "git"];
|
|
251
|
+
for (const c of containers) {
|
|
252
|
+
const dir = c ? join(home, c) : home;
|
|
253
|
+
for (const p of listDir(dir)) {
|
|
254
|
+
const st = lstatOrNull(p);
|
|
255
|
+
if (!st || !st.isDirectory() || st.isSymbolicLink()) continue;
|
|
256
|
+
if (existsSync(join(p, ".git"))) roots.push(p);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return roots;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Everything the planner reads from the machine, injectable so tests run on a
|
|
264
|
+
* temp home with stubbed commands.
|
|
265
|
+
*/
|
|
266
|
+
export function makeContext(o = {}) {
|
|
267
|
+
const home = o.home || homedir();
|
|
268
|
+
const uid = o.uid ?? (typeof process.getuid === "function" ? process.getuid() : -1);
|
|
269
|
+
const tmpRoots = o.tmpRoots || [
|
|
270
|
+
...new Set(["/private/tmp", normalizeTmp(realOrNull(tmpdir()) || tmpdir())]),
|
|
271
|
+
];
|
|
272
|
+
let psCache = null;
|
|
273
|
+
let openCache = null;
|
|
274
|
+
const ctx = {
|
|
275
|
+
home,
|
|
276
|
+
realHome: realOrNull(home) || home,
|
|
277
|
+
uid,
|
|
278
|
+
now: o.now ?? Date.now(),
|
|
279
|
+
tmpRoots,
|
|
280
|
+
devRoots: o.devRoots || defaultDevRoots(home),
|
|
281
|
+
scriptsDir: o.scriptsDir || defaultScriptsDir(home),
|
|
282
|
+
sessionId: o.sessionId ?? process.env.CLAUDE_CODE_SESSION_ID ?? "",
|
|
283
|
+
days: {
|
|
284
|
+
logs: o.logDays ?? 30,
|
|
285
|
+
archives: o.archiveDays ?? 90,
|
|
286
|
+
transcripts: o.transcriptDays ?? 90,
|
|
287
|
+
},
|
|
288
|
+
scratchHours: o.scratchHours ?? 48,
|
|
289
|
+
repoBuildHours: o.repoBuildHours ?? 12,
|
|
290
|
+
tmpGraceMinutes: o.tmpGraceMinutes ?? 120,
|
|
291
|
+
orphanMinutes: o.orphanMinutes ?? 30,
|
|
292
|
+
run: o.run || realRun,
|
|
293
|
+
du: o.du || duBytes,
|
|
294
|
+
ps: () => (psCache ??= (o.ps || realPs)()),
|
|
295
|
+
openPaths: () =>
|
|
296
|
+
(openCache ??= (o.openPaths || (() => realOpenPaths(uid)))().map(normalizeTmp)),
|
|
297
|
+
resetProbes() {
|
|
298
|
+
psCache = null;
|
|
299
|
+
openCache = null;
|
|
300
|
+
},
|
|
301
|
+
};
|
|
302
|
+
return ctx;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function has(ctx, cmd) {
|
|
306
|
+
return ctx.run("/usr/bin/which", [cmd], { timeout: 5000 }).status === 0;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** True when an open file or a running command line points into `path`. */
|
|
310
|
+
export function inUse(ctx, path) {
|
|
311
|
+
const p = normalizeTmp(path);
|
|
312
|
+
for (const open of ctx.openPaths()) if (open === p || inside(open, p)) return true;
|
|
313
|
+
for (const row of ctx.ps()) {
|
|
314
|
+
if (row.pid === process.pid) continue;
|
|
315
|
+
const cmd = normalizeTmp(row.command.replace(/\s\/(tmp|var)\//g, " /private/$1/"));
|
|
316
|
+
if (cmd.includes(p + "/") || cmd.endsWith(p) || cmd.includes(p + " ")) return true;
|
|
317
|
+
}
|
|
318
|
+
return false;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// ---------------------------------------------------------------- the guard
|
|
322
|
+
|
|
323
|
+
function protectedHit(real, ctx) {
|
|
324
|
+
for (const rel of PROTECTED_HOME) {
|
|
325
|
+
const p = join(ctx.realHome, rel);
|
|
326
|
+
if (real === p || inside(real, p)) return `~/${rel}`;
|
|
327
|
+
}
|
|
328
|
+
if (MEMORY_DIR.test(real)) return "a memory folder";
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Whether `path` may be deleted for a category whose roots are `roots`.
|
|
334
|
+
* @returns {{ok: true, real: string} | {ok: false, reason: string}}
|
|
335
|
+
*/
|
|
336
|
+
export function guardPath(path, ctx, roots) {
|
|
337
|
+
const st = lstatOrNull(path);
|
|
338
|
+
if (!st) return { ok: false, reason: "missing" };
|
|
339
|
+
if (st.isSymbolicLink()) return { ok: false, reason: "symlink, not followed" };
|
|
340
|
+
const real = realOrNull(path);
|
|
341
|
+
if (!real) return { ok: false, reason: "unresolvable path" };
|
|
342
|
+
const hit = protectedHit(real, ctx);
|
|
343
|
+
if (hit) return { ok: false, reason: `protected: ${hit}` };
|
|
344
|
+
const realRoots = roots.map(realOrNull).filter(Boolean);
|
|
345
|
+
if (!realRoots.some((r) => inside(real, r))) {
|
|
346
|
+
return { ok: false, reason: "outside the category roots" };
|
|
347
|
+
}
|
|
348
|
+
if (ctx.uid >= 0 && st.uid !== ctx.uid) return { ok: false, reason: "not owned by you" };
|
|
349
|
+
if (st.isDirectory() && existsSync(join(real, ".git"))) {
|
|
350
|
+
return { ok: false, reason: "git working tree" };
|
|
351
|
+
}
|
|
352
|
+
return { ok: true, real };
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// ---------------------------------------------------------------- discovery
|
|
356
|
+
|
|
357
|
+
function rootUsable(root, ctx, out) {
|
|
358
|
+
const st = lstatOrNull(root);
|
|
359
|
+
if (!st) return false;
|
|
360
|
+
if (st.isSymbolicLink()) {
|
|
361
|
+
out.skipped.push({ path: root, reason: "category root is a symlink, not followed" });
|
|
362
|
+
return false;
|
|
363
|
+
}
|
|
364
|
+
const real = realOrNull(root);
|
|
365
|
+
const hit = real && protectedHit(real, ctx);
|
|
366
|
+
if (hit) {
|
|
367
|
+
out.skipped.push({ path: root, reason: `protected: ${hit}` });
|
|
368
|
+
return false;
|
|
369
|
+
}
|
|
370
|
+
return st.isDirectory();
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function addPath(out, ctx, path, roots, extra = {}) {
|
|
374
|
+
const g = guardPath(path, ctx, roots);
|
|
375
|
+
if (!g.ok) {
|
|
376
|
+
out.skipped.push({ path, reason: g.reason });
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
out.candidates.push({ kind: "path", path: g.real, roots, ...extra });
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function childrenOf(ctx, out, roots, filter = () => true) {
|
|
383
|
+
for (const root of roots) {
|
|
384
|
+
if (!rootUsable(root, ctx, out)) continue;
|
|
385
|
+
for (const p of listDir(root)) if (filter(p)) addPath(out, ctx, p, [root]);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function walk(dir, depth, visit) {
|
|
390
|
+
if (depth > MAX_WALK_DEPTH) return;
|
|
391
|
+
let entries;
|
|
392
|
+
try {
|
|
393
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
394
|
+
} catch {
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
for (const e of entries) {
|
|
398
|
+
const p = join(dir, e.name);
|
|
399
|
+
if (e.isSymbolicLink()) continue;
|
|
400
|
+
if (e.isDirectory()) {
|
|
401
|
+
if (WALK_SKIP.has(e.name)) continue;
|
|
402
|
+
walk(p, depth + 1, visit);
|
|
403
|
+
} else if (e.isFile()) visit(p);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function olderThan(path, ms, ctx) {
|
|
408
|
+
const st = lstatOrNull(path);
|
|
409
|
+
return Boolean(st) && ctx.now - st.mtimeMs > ms;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function newestMtime(path, depth) {
|
|
413
|
+
const st = lstatOrNull(path);
|
|
414
|
+
if (!st) return 0;
|
|
415
|
+
let t = st.mtimeMs;
|
|
416
|
+
if (depth > 0 && st.isDirectory()) {
|
|
417
|
+
for (const c of listDir(path)) t = Math.max(t, newestMtime(c, depth - 1));
|
|
418
|
+
}
|
|
419
|
+
return t;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function processRunning(ctx, test) {
|
|
423
|
+
return ctx.ps().some((r) => (ctx.uid < 0 || r.uid === ctx.uid) && test(r));
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
const exeIs =
|
|
427
|
+
(...names) =>
|
|
428
|
+
(r) =>
|
|
429
|
+
names.includes(basename(r.command.split(/\s+/)[0] || ""));
|
|
430
|
+
|
|
431
|
+
const H = (ctx, ...rel) => join(ctx.home, ...rel);
|
|
432
|
+
|
|
433
|
+
function commandCandidate(out, ctx, { tool, args, measure, label }) {
|
|
434
|
+
const bytes = measure.filter((p) => existsSync(p));
|
|
435
|
+
out.candidates.push({ kind: "command", cmd: tool, args, path: label, measure: bytes });
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function cacheWithTool(ctx, out, tool, args, dir) {
|
|
439
|
+
if (!existsSync(dir)) return;
|
|
440
|
+
if (!rootUsable(dir, ctx, out)) return;
|
|
441
|
+
if (has(ctx, tool)) {
|
|
442
|
+
commandCandidate(out, ctx, { tool, args, measure: [dir], label: `${tool} ${args.join(" ")}` });
|
|
443
|
+
} else {
|
|
444
|
+
childrenOf(ctx, out, [dir]);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function devicePairedVersions(ctx) {
|
|
449
|
+
const r = ctx.run("xcrun", ["xctrace", "list", "devices"], { timeout: 60_000 });
|
|
450
|
+
if (r.status !== 0) return null;
|
|
451
|
+
const versions = new Set();
|
|
452
|
+
let section = "";
|
|
453
|
+
for (const line of r.stdout.split("\n")) {
|
|
454
|
+
const h = /^==\s*(.+?)\s*==$/.exec(line.trim());
|
|
455
|
+
if (h) {
|
|
456
|
+
section = h[1];
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
if (/simulator/i.test(section)) continue;
|
|
460
|
+
for (const m of line.matchAll(/\((\d+(?:\.\d+)+)\)/g)) versions.add(m[1]);
|
|
461
|
+
}
|
|
462
|
+
return versions;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function gcTmpCandidates(ctx, out) {
|
|
466
|
+
const script = join(ctx.scriptsDir, "gc-tmp.sh");
|
|
467
|
+
if (!existsSync(script)) {
|
|
468
|
+
out.note = "gc-tmp.sh is not installed; pipeline scratch was not measured";
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
const reportFile = join(tmpdir(), `disk-cleaner-gc-${process.pid}-${Date.now()}.jsonl`);
|
|
472
|
+
ctx.run("bash", [script, "--report", reportFile], { timeout: 120_000 });
|
|
473
|
+
const text = readFileSafe(reportFile);
|
|
474
|
+
rmSync(reportFile, { force: true });
|
|
475
|
+
for (const line of text.split("\n")) {
|
|
476
|
+
if (!line.trim()) continue;
|
|
477
|
+
try {
|
|
478
|
+
const row = JSON.parse(line);
|
|
479
|
+
if (row.action !== "would-remove") continue;
|
|
480
|
+
out.candidates.push({
|
|
481
|
+
kind: "delegate",
|
|
482
|
+
tool: "gc-tmp",
|
|
483
|
+
path: row.path,
|
|
484
|
+
bytes: Number(row.sizeKb || 0) * 1024,
|
|
485
|
+
});
|
|
486
|
+
} catch {
|
|
487
|
+
/* a malformed row is not a candidate */
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function pruneLogsCandidates(ctx, out) {
|
|
493
|
+
const script = join(ctx.scriptsDir, "prune-logs.sh");
|
|
494
|
+
if (!existsSync(script)) {
|
|
495
|
+
out.note = "prune-logs.sh is not installed; pipeline task logs were not measured";
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
const logRoot = H(ctx, ".claude", "logs", "multi-agent");
|
|
499
|
+
if (!existsSync(logRoot)) return;
|
|
500
|
+
const r = ctx.run("bash", [script, `--older-than=${ctx.days.logs}`], {
|
|
501
|
+
timeout: 120_000,
|
|
502
|
+
env: { ...process.env, PRUNE_LOG_ROOT: logRoot },
|
|
503
|
+
});
|
|
504
|
+
let listing = false;
|
|
505
|
+
for (const line of r.stdout.split("\n")) {
|
|
506
|
+
if (line.startsWith("DRY-RUN")) {
|
|
507
|
+
listing = true;
|
|
508
|
+
continue;
|
|
509
|
+
}
|
|
510
|
+
if (!listing) continue;
|
|
511
|
+
if (!line.startsWith(" ")) break;
|
|
512
|
+
const rel = line.trim();
|
|
513
|
+
out.candidates.push({ kind: "delegate", tool: "prune-logs", path: join(logRoot, rel), rel });
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function readFileSafe(p) {
|
|
518
|
+
try {
|
|
519
|
+
return readFileSync(p, "utf8");
|
|
520
|
+
} catch {
|
|
521
|
+
return "";
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
function worktreeCandidates(ctx, out) {
|
|
526
|
+
const bases = ["main", "master", "develop", "origin/main", "origin/master", "origin/develop"];
|
|
527
|
+
for (const repo of ctx.devRoots) {
|
|
528
|
+
const wtRoot = join(repo, ".claude", "worktrees");
|
|
529
|
+
if (!existsSync(wtRoot) || !rootUsable(wtRoot, ctx, out)) continue;
|
|
530
|
+
const list = ctx.run("git", ["-C", repo, "worktree", "list", "--porcelain"]);
|
|
531
|
+
const locked = new Set();
|
|
532
|
+
let current = null;
|
|
533
|
+
for (const line of list.stdout.split("\n")) {
|
|
534
|
+
if (line.startsWith("worktree ")) current = realOrNull(line.slice(9)) || line.slice(9);
|
|
535
|
+
else if (line.startsWith("locked") && current) locked.add(current);
|
|
536
|
+
}
|
|
537
|
+
const knownBases = bases.filter(
|
|
538
|
+
(b) => ctx.run("git", ["-C", repo, "rev-parse", "--verify", "--quiet", b]).status === 0,
|
|
539
|
+
);
|
|
540
|
+
for (const wt of listDir(wtRoot)) {
|
|
541
|
+
const st = lstatOrNull(wt);
|
|
542
|
+
if (!st || !st.isDirectory()) continue;
|
|
543
|
+
if (st.isSymbolicLink()) {
|
|
544
|
+
out.skipped.push({ path: wt, reason: "symlink, not followed" });
|
|
545
|
+
continue;
|
|
546
|
+
}
|
|
547
|
+
const real = realOrNull(wt);
|
|
548
|
+
const keep = (reason) => out.skipped.push({ path: wt, reason });
|
|
549
|
+
if (!existsSync(join(wt, ".git"))) {
|
|
550
|
+
keep("not a git worktree");
|
|
551
|
+
continue;
|
|
552
|
+
}
|
|
553
|
+
if (locked.has(real)) {
|
|
554
|
+
keep("locked worktree");
|
|
555
|
+
continue;
|
|
556
|
+
}
|
|
557
|
+
if (inUse(ctx, real)) {
|
|
558
|
+
keep("in use by a running process");
|
|
559
|
+
continue;
|
|
560
|
+
}
|
|
561
|
+
const status = ctx.run("git", ["-C", wt, "status", "--porcelain"]);
|
|
562
|
+
if (status.status !== 0) {
|
|
563
|
+
keep("git status failed");
|
|
564
|
+
continue;
|
|
565
|
+
}
|
|
566
|
+
if (status.stdout.trim()) {
|
|
567
|
+
keep("uncommitted changes");
|
|
568
|
+
continue;
|
|
569
|
+
}
|
|
570
|
+
const merged = knownBases.some(
|
|
571
|
+
(b) => ctx.run("git", ["-C", wt, "merge-base", "--is-ancestor", "HEAD", b]).status === 0,
|
|
572
|
+
);
|
|
573
|
+
if (!merged) {
|
|
574
|
+
keep("not merged into main, master or develop");
|
|
575
|
+
continue;
|
|
576
|
+
}
|
|
577
|
+
out.candidates.push({ kind: "worktree", path: real, repo });
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
function dsStoreCandidates(ctx, out) {
|
|
583
|
+
for (const root of ctx.devRoots) {
|
|
584
|
+
if (!rootUsable(root, ctx, out)) continue;
|
|
585
|
+
walk(root, 0, (p) => {
|
|
586
|
+
if (basename(p) === ".DS_Store") addPath(out, ctx, p, [root]);
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
// A folder is build output only when it carries what the build tool writes:
|
|
592
|
+
// a hand-made folder that happens to be called `.build` keeps its content.
|
|
593
|
+
const BUILD_SHAPE = {
|
|
594
|
+
".build": [
|
|
595
|
+
"build.db",
|
|
596
|
+
"manifest.db",
|
|
597
|
+
"checkouts",
|
|
598
|
+
"artifacts",
|
|
599
|
+
"repositories",
|
|
600
|
+
"debug",
|
|
601
|
+
"release",
|
|
602
|
+
"index-build",
|
|
603
|
+
"plugins",
|
|
604
|
+
],
|
|
605
|
+
DerivedData: ["Build", "Index.noindex", "ModuleCache.noindex", "info.plist", "SourcePackages"],
|
|
606
|
+
};
|
|
607
|
+
BUILD_SHAPE[".DerivedData"] = BUILD_SHAPE.DerivedData;
|
|
608
|
+
|
|
609
|
+
function repoBuildCandidates(ctx, out) {
|
|
610
|
+
const maxAge = ctx.repoBuildHours * HOUR_MS;
|
|
611
|
+
const visit = (root, dir, depth) => {
|
|
612
|
+
if (depth > MAX_WALK_DEPTH) return;
|
|
613
|
+
let entries;
|
|
614
|
+
try {
|
|
615
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
616
|
+
} catch {
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
for (const e of entries) {
|
|
620
|
+
if (!e.isDirectory() || e.isSymbolicLink()) continue;
|
|
621
|
+
const p = join(dir, e.name);
|
|
622
|
+
const shape = BUILD_SHAPE[e.name];
|
|
623
|
+
if (shape) {
|
|
624
|
+
if (!shape.some((n) => existsSync(join(p, n)))) {
|
|
625
|
+
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
|
+
} else if (inUse(ctx, realOrNull(p) || p)) {
|
|
629
|
+
out.skipped.push({ path: p, reason: "in use by a running process" });
|
|
630
|
+
} else {
|
|
631
|
+
addPath(out, ctx, p, [root]);
|
|
632
|
+
}
|
|
633
|
+
continue;
|
|
634
|
+
}
|
|
635
|
+
if (e.name === ".git" || e.name === "node_modules" || e.name === "Pods") continue;
|
|
636
|
+
visit(root, p, depth + 1);
|
|
637
|
+
}
|
|
638
|
+
};
|
|
639
|
+
for (const root of ctx.devRoots) {
|
|
640
|
+
if (rootUsable(root, ctx, out)) visit(root, root, 0);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
function oldFiles(ctx, out, roots, maxAgeMs, match = () => true) {
|
|
645
|
+
for (const root of roots) {
|
|
646
|
+
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
|
+
});
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
function tmpBuildCandidates(ctx, out) {
|
|
654
|
+
for (const root of ctx.tmpRoots) {
|
|
655
|
+
if (!rootUsable(root, ctx, out)) continue;
|
|
656
|
+
for (const p of listDir(root)) {
|
|
657
|
+
if (!/^dd-/.test(basename(p))) continue;
|
|
658
|
+
const st = lstatOrNull(p);
|
|
659
|
+
if (!st || !st.isDirectory()) continue;
|
|
660
|
+
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" });
|
|
663
|
+
continue;
|
|
664
|
+
}
|
|
665
|
+
if (inUse(ctx, realOrNull(p) || p)) {
|
|
666
|
+
out.skipped.push({ path: p, reason: "in use by a running process" });
|
|
667
|
+
continue;
|
|
668
|
+
}
|
|
669
|
+
addPath(out, ctx, p, [root]);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
function claudeScratchCandidates(ctx, out) {
|
|
675
|
+
for (const root of ctx.tmpRoots) {
|
|
676
|
+
const base = join(root, `claude-${ctx.uid}`);
|
|
677
|
+
if (!existsSync(base) || !rootUsable(base, ctx, out)) continue;
|
|
678
|
+
for (const slug of listDir(base)) {
|
|
679
|
+
for (const session of listDir(slug)) {
|
|
680
|
+
const name = basename(session);
|
|
681
|
+
if (!UUID.test(name)) continue;
|
|
682
|
+
if (ctx.sessionId && name === ctx.sessionId) {
|
|
683
|
+
out.skipped.push({ path: session, reason: "the current session" });
|
|
684
|
+
continue;
|
|
685
|
+
}
|
|
686
|
+
if (ctx.now - newestMtime(session, 2) < ctx.scratchHours * HOUR_MS) continue;
|
|
687
|
+
if (inUse(ctx, realOrNull(session) || session)) {
|
|
688
|
+
out.skipped.push({ path: session, reason: "in use by a running process" });
|
|
689
|
+
continue;
|
|
690
|
+
}
|
|
691
|
+
addPath(out, ctx, session, [base]);
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
function transcriptCandidates(ctx, out) {
|
|
698
|
+
const maxAge = ctx.days.transcripts * DAY_MS;
|
|
699
|
+
const roots = [H(ctx, ".claude", "projects"), H(ctx, ".codex", "sessions")];
|
|
700
|
+
for (const root of roots) {
|
|
701
|
+
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]);
|
|
714
|
+
});
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/** Orphaned session children, for the report only: pid and command, nothing to act on. */
|
|
719
|
+
export function listOrphans(ctx) {
|
|
720
|
+
const rows = ctx.ps();
|
|
721
|
+
return findOrphans(rows, {
|
|
722
|
+
uid: ctx.uid,
|
|
723
|
+
minAgeSec: ctx.orphanMinutes * 60,
|
|
724
|
+
selfChain: selfChain(rows),
|
|
725
|
+
}).map((r) => ({ pid: r.pid, command: r.command }));
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
function selfChain(rows) {
|
|
729
|
+
const parent = new Map(rows.map((r) => [r.pid, r.ppid]));
|
|
730
|
+
const chain = new Set();
|
|
731
|
+
let pid = process.pid;
|
|
732
|
+
while (pid > 1 && !chain.has(pid)) {
|
|
733
|
+
chain.add(pid);
|
|
734
|
+
pid = parent.get(pid) ?? 0;
|
|
735
|
+
}
|
|
736
|
+
return chain;
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/** Session children whose parent is gone: reparented to launchd, old enough, ours. */
|
|
740
|
+
export function findOrphans(rows, { uid, minAgeSec, selfChain: own = new Set() }) {
|
|
741
|
+
return rows.filter(
|
|
742
|
+
(r) =>
|
|
743
|
+
r.ppid === 1 &&
|
|
744
|
+
r.uid === uid &&
|
|
745
|
+
r.etimeSec >= minAgeSec &&
|
|
746
|
+
!own.has(r.pid) &&
|
|
747
|
+
ORPHAN_PATTERNS.some((re) => re.test(r.command)),
|
|
748
|
+
);
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
// ---------------------------------------------------------------- categories
|
|
752
|
+
|
|
753
|
+
const XCODE = exeIs("Xcode", "xcodebuild");
|
|
754
|
+
const SIMULATOR = exeIs("Simulator");
|
|
755
|
+
|
|
756
|
+
/**
|
|
757
|
+
* The allowlist. `unattended` marks the categories a run nobody watches may
|
|
758
|
+
* apply; `optIn` names the flag a category needs before it is planned.
|
|
759
|
+
*/
|
|
760
|
+
export const CATEGORIES = [
|
|
761
|
+
{
|
|
762
|
+
id: "derived-data",
|
|
763
|
+
label: "Xcode DerivedData",
|
|
764
|
+
unattended: true,
|
|
765
|
+
blocker: [XCODE, "Xcode or xcodebuild is running"],
|
|
766
|
+
discover: (ctx, out) => childrenOf(ctx, out, [H(ctx, "Library/Developer/Xcode/DerivedData")]),
|
|
767
|
+
},
|
|
768
|
+
{
|
|
769
|
+
id: "repo-build",
|
|
770
|
+
label: "SwiftPM .build and DerivedData folders inside dev roots, untouched for the build age",
|
|
771
|
+
unattended: true,
|
|
772
|
+
blocker: [
|
|
773
|
+
(r) => XCODE(r) || exeIs("swift-build", "swift-test", "sourcekit-lsp")(r),
|
|
774
|
+
"Xcode, xcodebuild or a SwiftPM build is running",
|
|
775
|
+
],
|
|
776
|
+
discover: repoBuildCandidates,
|
|
777
|
+
},
|
|
778
|
+
{
|
|
779
|
+
id: "xctest-devices",
|
|
780
|
+
label: "per-run XCTest simulator clones untouched for the build age (du overstates them)",
|
|
781
|
+
unattended: true,
|
|
782
|
+
blocker: [XCODE, "Xcode or xcodebuild is running"],
|
|
783
|
+
discover: (ctx, out) =>
|
|
784
|
+
childrenOf(ctx, out, [H(ctx, "Library/Developer/XCTestDevices")], (p) =>
|
|
785
|
+
olderThan(p, ctx.repoBuildHours * HOUR_MS, ctx),
|
|
786
|
+
),
|
|
787
|
+
},
|
|
788
|
+
{
|
|
789
|
+
id: "xcode-caches",
|
|
790
|
+
label: "Xcode SwiftUI preview, Interface Builder and documentation caches",
|
|
791
|
+
unattended: true,
|
|
792
|
+
blocker: [XCODE, "Xcode or xcodebuild is running"],
|
|
793
|
+
discover: (ctx, out) =>
|
|
794
|
+
childrenOf(ctx, out, [
|
|
795
|
+
H(ctx, "Library/Developer/Xcode/UserData/Previews"),
|
|
796
|
+
H(ctx, "Library/Developer/Xcode/UserData/IB Support"),
|
|
797
|
+
H(ctx, "Library/Developer/Xcode/DocumentationCache"),
|
|
798
|
+
]),
|
|
799
|
+
},
|
|
800
|
+
{
|
|
801
|
+
id: "archives",
|
|
802
|
+
label: "Xcode Archives older than the archive age",
|
|
803
|
+
unattended: false,
|
|
804
|
+
discover(ctx, out) {
|
|
805
|
+
const root = H(ctx, "Library/Developer/Xcode/Archives");
|
|
806
|
+
if (!rootUsable(root, ctx, out)) return;
|
|
807
|
+
for (const day of listDir(root)) {
|
|
808
|
+
for (const arc of listDir(day)) {
|
|
809
|
+
if (arc.endsWith(".xcarchive") && olderThan(arc, ctx.days.archives * DAY_MS, ctx)) {
|
|
810
|
+
addPath(out, ctx, arc, [root]);
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
},
|
|
815
|
+
},
|
|
816
|
+
{
|
|
817
|
+
id: "device-support",
|
|
818
|
+
label: "iOS, watchOS and tvOS DeviceSupport for OS versions with no paired device",
|
|
819
|
+
unattended: false,
|
|
820
|
+
blocker: [XCODE, "Xcode or xcodebuild is running"],
|
|
821
|
+
discover(ctx, out) {
|
|
822
|
+
const roots = ["iOS", "watchOS", "tvOS"]
|
|
823
|
+
.map((p) => H(ctx, `Library/Developer/Xcode/${p} DeviceSupport`))
|
|
824
|
+
.filter((r) => existsSync(r));
|
|
825
|
+
if (!roots.length) return;
|
|
826
|
+
const paired = devicePairedVersions(ctx);
|
|
827
|
+
if (!paired) {
|
|
828
|
+
out.note = "could not list paired devices, so every DeviceSupport folder was kept";
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
const keep = (p) =>
|
|
832
|
+
[...paired].some((v) =>
|
|
833
|
+
new RegExp(`(^|\\s)${v.replace(/\./g, "\\.")}(\\s|$)`).test(basename(p)),
|
|
834
|
+
);
|
|
835
|
+
childrenOf(ctx, out, roots, (p) => {
|
|
836
|
+
if (keep(p)) {
|
|
837
|
+
out.skipped.push({ path: p, reason: "a paired device runs this version" });
|
|
838
|
+
return false;
|
|
839
|
+
}
|
|
840
|
+
return true;
|
|
841
|
+
});
|
|
842
|
+
},
|
|
843
|
+
},
|
|
844
|
+
{
|
|
845
|
+
id: "sim-unavailable",
|
|
846
|
+
label: "CoreSimulator devices whose runtime is gone (simctl delete unavailable)",
|
|
847
|
+
unattended: true,
|
|
848
|
+
discover(ctx, out) {
|
|
849
|
+
const r = ctx.run("xcrun", ["simctl", "list", "devices", "unavailable", "-j"], {
|
|
850
|
+
timeout: 60_000,
|
|
851
|
+
});
|
|
852
|
+
if (r.status !== 0) return;
|
|
853
|
+
let data;
|
|
854
|
+
try {
|
|
855
|
+
data = JSON.parse(r.stdout);
|
|
856
|
+
} catch {
|
|
857
|
+
return;
|
|
858
|
+
}
|
|
859
|
+
const dirs = [];
|
|
860
|
+
for (const list of Object.values(data.devices || {})) {
|
|
861
|
+
for (const d of list) if (d.dataPath) dirs.push(dirname(d.dataPath));
|
|
862
|
+
}
|
|
863
|
+
if (!dirs.length) return;
|
|
864
|
+
out.candidates.push({
|
|
865
|
+
kind: "command",
|
|
866
|
+
cmd: "xcrun",
|
|
867
|
+
args: ["simctl", "delete", "unavailable"],
|
|
868
|
+
path: `xcrun simctl delete unavailable (${dirs.length} devices)`,
|
|
869
|
+
measure: dirs.filter((d) => existsSync(d)),
|
|
870
|
+
});
|
|
871
|
+
},
|
|
872
|
+
},
|
|
873
|
+
{
|
|
874
|
+
id: "sim-caches",
|
|
875
|
+
label: "CoreSimulator caches",
|
|
876
|
+
unattended: true,
|
|
877
|
+
blocker: [SIMULATOR, "Simulator is running"],
|
|
878
|
+
discover: (ctx, out) =>
|
|
879
|
+
childrenOf(ctx, out, [H(ctx, "Library/Developer/CoreSimulator/Caches")]),
|
|
880
|
+
},
|
|
881
|
+
{
|
|
882
|
+
id: "spm-cache",
|
|
883
|
+
label: "SwiftPM package cache",
|
|
884
|
+
unattended: true,
|
|
885
|
+
blocker: [XCODE, "Xcode or xcodebuild is running"],
|
|
886
|
+
discover: (ctx, out) => childrenOf(ctx, out, [H(ctx, "Library/Caches/org.swift.swiftpm")]),
|
|
887
|
+
},
|
|
888
|
+
{
|
|
889
|
+
id: "pods-cache",
|
|
890
|
+
label: "CocoaPods cache",
|
|
891
|
+
unattended: true,
|
|
892
|
+
discover: (ctx, out) =>
|
|
893
|
+
cacheWithTool(
|
|
894
|
+
ctx,
|
|
895
|
+
out,
|
|
896
|
+
"pod",
|
|
897
|
+
["cache", "clean", "--all"],
|
|
898
|
+
H(ctx, "Library/Caches/CocoaPods"),
|
|
899
|
+
),
|
|
900
|
+
},
|
|
901
|
+
{
|
|
902
|
+
id: "gradle-cache",
|
|
903
|
+
label: "Gradle caches",
|
|
904
|
+
unattended: true,
|
|
905
|
+
blocker: [(r) => /GradleDaemon/.test(r.command), "a Gradle daemon is running"],
|
|
906
|
+
discover: (ctx, out) => childrenOf(ctx, out, [H(ctx, ".gradle/caches")]),
|
|
907
|
+
},
|
|
908
|
+
{
|
|
909
|
+
id: "js-caches",
|
|
910
|
+
label: "npm, yarn and pnpm caches",
|
|
911
|
+
unattended: true,
|
|
912
|
+
discover(ctx, out) {
|
|
913
|
+
cacheWithTool(ctx, out, "npm", ["cache", "clean", "--force"], H(ctx, ".npm/_cacache"));
|
|
914
|
+
cacheWithTool(ctx, out, "yarn", ["cache", "clean"], H(ctx, "Library/Caches/Yarn"));
|
|
915
|
+
cacheWithTool(ctx, out, "pnpm", ["store", "prune"], H(ctx, "Library/pnpm/store"));
|
|
916
|
+
},
|
|
917
|
+
},
|
|
918
|
+
{
|
|
919
|
+
id: "homebrew",
|
|
920
|
+
label: "Homebrew downloads and old versions (brew cleanup)",
|
|
921
|
+
unattended: true,
|
|
922
|
+
discover(ctx, out) {
|
|
923
|
+
const dir = H(ctx, "Library/Caches/Homebrew");
|
|
924
|
+
if (!existsSync(dir) || !has(ctx, "brew")) return;
|
|
925
|
+
commandCandidate(out, ctx, {
|
|
926
|
+
tool: "brew",
|
|
927
|
+
args: ["cleanup", "--prune=all"],
|
|
928
|
+
measure: [dir],
|
|
929
|
+
label: "brew cleanup --prune=all",
|
|
930
|
+
});
|
|
931
|
+
},
|
|
932
|
+
},
|
|
933
|
+
{
|
|
934
|
+
id: "tmp-builds",
|
|
935
|
+
label: "build leftovers in /tmp and $TMPDIR (dd-*)",
|
|
936
|
+
unattended: true,
|
|
937
|
+
discover: tmpBuildCandidates,
|
|
938
|
+
},
|
|
939
|
+
{
|
|
940
|
+
id: "pipeline-scratch",
|
|
941
|
+
label: "pipeline scratch in /tmp (through gc-tmp.sh)",
|
|
942
|
+
unattended: true,
|
|
943
|
+
discover: gcTmpCandidates,
|
|
944
|
+
},
|
|
945
|
+
{
|
|
946
|
+
id: "claude-scratch",
|
|
947
|
+
label: "scratchpads and task outputs of ended Claude Code sessions",
|
|
948
|
+
unattended: true,
|
|
949
|
+
discover: claudeScratchCandidates,
|
|
950
|
+
},
|
|
951
|
+
{
|
|
952
|
+
id: "agent-worktrees",
|
|
953
|
+
label: "merged, clean agent worktrees under .claude/worktrees",
|
|
954
|
+
unattended: false,
|
|
955
|
+
discover: worktreeCandidates,
|
|
956
|
+
},
|
|
957
|
+
{
|
|
958
|
+
id: "dev-caches",
|
|
959
|
+
label: "~/Library/Caches folders of developer tools",
|
|
960
|
+
unattended: true,
|
|
961
|
+
blocker: [XCODE, "Xcode or xcodebuild is running"],
|
|
962
|
+
discover: (ctx, out) =>
|
|
963
|
+
childrenOf(
|
|
964
|
+
ctx,
|
|
965
|
+
out,
|
|
966
|
+
DEV_CACHE_DIRS.map((d) => H(ctx, "Library/Caches", d)),
|
|
967
|
+
),
|
|
968
|
+
},
|
|
969
|
+
{
|
|
970
|
+
id: "old-logs",
|
|
971
|
+
label: "simulator logs and crash reports older than the log age",
|
|
972
|
+
unattended: true,
|
|
973
|
+
discover: (ctx, out) =>
|
|
974
|
+
oldFiles(
|
|
975
|
+
ctx,
|
|
976
|
+
out,
|
|
977
|
+
[H(ctx, "Library/Logs/CoreSimulator"), H(ctx, "Library/Logs/DiagnosticReports")],
|
|
978
|
+
ctx.days.logs * DAY_MS,
|
|
979
|
+
),
|
|
980
|
+
},
|
|
981
|
+
{
|
|
982
|
+
id: "pipeline-logs",
|
|
983
|
+
label: "finished pipeline task logs older than the log age (through prune-logs.sh)",
|
|
984
|
+
unattended: true,
|
|
985
|
+
discover: pruneLogsCandidates,
|
|
986
|
+
},
|
|
987
|
+
{
|
|
988
|
+
id: "ds-store",
|
|
989
|
+
label: ".DS_Store files inside dev roots",
|
|
990
|
+
unattended: true,
|
|
991
|
+
discover: dsStoreCandidates,
|
|
992
|
+
},
|
|
993
|
+
{
|
|
994
|
+
id: "trash",
|
|
995
|
+
label: "the Trash",
|
|
996
|
+
unattended: false,
|
|
997
|
+
optIn: "trash",
|
|
998
|
+
discover: (ctx, out) => childrenOf(ctx, out, [H(ctx, ".Trash")]),
|
|
999
|
+
},
|
|
1000
|
+
{
|
|
1001
|
+
id: "transcripts",
|
|
1002
|
+
label: "Claude Code and Codex session transcripts older than the transcript age",
|
|
1003
|
+
unattended: false,
|
|
1004
|
+
optIn: "transcripts",
|
|
1005
|
+
discover: transcriptCandidates,
|
|
1006
|
+
},
|
|
1007
|
+
];
|
|
1008
|
+
|
|
1009
|
+
export const UNATTENDED_SAFE = new Set(CATEGORIES.filter((c) => c.unattended).map((c) => c.id));
|
|
1010
|
+
|
|
1011
|
+
/** The categories a run plans, after opt-ins, --only, --skip and the unattended set. */
|
|
1012
|
+
export function selectCategories(sel = {}) {
|
|
1013
|
+
return CATEGORIES.filter((c) => {
|
|
1014
|
+
if (sel.unattended && !c.unattended) return false;
|
|
1015
|
+
if (c.optIn && !sel[c.optIn]) return false;
|
|
1016
|
+
if (sel.only?.length && !sel.only.includes(c.id)) return false;
|
|
1017
|
+
if (sel.skip?.includes(c.id)) return false;
|
|
1018
|
+
return true;
|
|
1019
|
+
});
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
// ---------------------------------------------------------------- plan / apply
|
|
1023
|
+
|
|
1024
|
+
/** Measure every selected category. Deletes nothing. */
|
|
1025
|
+
export function plan(ctx, sel = {}) {
|
|
1026
|
+
const categories = [];
|
|
1027
|
+
for (const cat of selectCategories(sel)) {
|
|
1028
|
+
const out = { id: cat.id, label: cat.label, candidates: [], skipped: [], note: null, bytes: 0 };
|
|
1029
|
+
if (cat.blocker && processRunning(ctx, cat.blocker[0])) {
|
|
1030
|
+
out.blocked = cat.blocker[1];
|
|
1031
|
+
out.note = `${cat.blocker[1]}; measured, not applied`;
|
|
1032
|
+
}
|
|
1033
|
+
cat.discover(ctx, out);
|
|
1034
|
+
const toMeasure = [];
|
|
1035
|
+
for (const c of out.candidates) {
|
|
1036
|
+
if (c.kind === "path" || c.kind === "worktree") toMeasure.push(c.path);
|
|
1037
|
+
else if (c.kind === "command") toMeasure.push(...c.measure);
|
|
1038
|
+
else if (c.kind === "delegate" && c.bytes == null) toMeasure.push(c.path);
|
|
1039
|
+
}
|
|
1040
|
+
const sizes = toMeasure.length ? ctx.du(toMeasure) : new Map();
|
|
1041
|
+
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;
|
|
1044
|
+
c.category = cat.id;
|
|
1045
|
+
out.bytes += c.bytes;
|
|
1046
|
+
}
|
|
1047
|
+
categories.push(out);
|
|
1048
|
+
}
|
|
1049
|
+
return {
|
|
1050
|
+
categories,
|
|
1051
|
+
totalBytes: categories.reduce((s, c) => s + c.bytes, 0),
|
|
1052
|
+
};
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
function deletePath(ctx, c) {
|
|
1056
|
+
const g = guardPath(c.path, ctx, c.roots);
|
|
1057
|
+
if (!g.ok) return { ok: false, reason: g.reason };
|
|
1058
|
+
try {
|
|
1059
|
+
rmSync(g.real, { recursive: true, force: true });
|
|
1060
|
+
return existsSync(g.real) ? { ok: false, reason: "still present" } : { ok: true };
|
|
1061
|
+
} catch (e) {
|
|
1062
|
+
return { ok: false, reason: e.code || "delete failed" };
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
function removeWorktree(ctx, c) {
|
|
1067
|
+
if (inUse(ctx, c.path)) return { ok: false, reason: "in use by a running process" };
|
|
1068
|
+
const status = ctx.run("git", ["-C", c.path, "status", "--porcelain"]);
|
|
1069
|
+
if (status.status !== 0 || status.stdout.trim()) return { ok: false, reason: "no longer clean" };
|
|
1070
|
+
const r = ctx.run("git", ["-C", c.repo, "worktree", "remove", c.path]);
|
|
1071
|
+
return r.status === 0 ? { ok: true } : { ok: false, reason: r.stderr.trim() || "git refused" };
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
function runDelegate(ctx, tool, items) {
|
|
1075
|
+
const listFile = join(tmpdir(), `disk-cleaner-${tool}-${process.pid}-${Date.now()}.txt`);
|
|
1076
|
+
try {
|
|
1077
|
+
if (tool === "gc-tmp") {
|
|
1078
|
+
writeFileSync(listFile, items.map((c) => c.path).join("\n") + "\n");
|
|
1079
|
+
const r = ctx.run("bash", [join(ctx.scriptsDir, "gc-tmp.sh"), "--yes", "--only", listFile]);
|
|
1080
|
+
return r.status === 0;
|
|
1081
|
+
}
|
|
1082
|
+
writeFileSync(listFile, items.map((c) => c.rel).join("\n") + "\n");
|
|
1083
|
+
const r = ctx.run(
|
|
1084
|
+
"bash",
|
|
1085
|
+
[
|
|
1086
|
+
join(ctx.scriptsDir, "prune-logs.sh"),
|
|
1087
|
+
`--older-than=${ctx.days.logs}`,
|
|
1088
|
+
`--only-from=${listFile}`,
|
|
1089
|
+
"--yes",
|
|
1090
|
+
],
|
|
1091
|
+
{ env: { ...process.env, PRUNE_LOG_ROOT: H(ctx, ".claude", "logs", "multi-agent") } },
|
|
1092
|
+
);
|
|
1093
|
+
return r.status === 0;
|
|
1094
|
+
} finally {
|
|
1095
|
+
rmSync(listFile, { force: true });
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
/**
|
|
1100
|
+
* Delete what `planned` lists. Every path passes the guard again first, a
|
|
1101
|
+
* worktree is re-checked for changes.
|
|
1102
|
+
*/
|
|
1103
|
+
export function applyPlan(ctx, planned) {
|
|
1104
|
+
ctx.resetProbes?.();
|
|
1105
|
+
const result = { removed: 0, failed: 0, failures: [], held: [] };
|
|
1106
|
+
for (const cat of planned.categories) {
|
|
1107
|
+
const def = CATEGORIES.find((c) => c.id === cat.id);
|
|
1108
|
+
if (cat.blocked || (def?.blocker && processRunning(ctx, def.blocker[0]))) {
|
|
1109
|
+
result.held.push({ category: cat.id, reason: def?.blocker?.[1] || cat.blocked });
|
|
1110
|
+
continue;
|
|
1111
|
+
}
|
|
1112
|
+
const delegates = new Map();
|
|
1113
|
+
for (const c of cat.candidates) {
|
|
1114
|
+
let r;
|
|
1115
|
+
if (c.kind === "path") r = deletePath(ctx, c);
|
|
1116
|
+
else if (c.kind === "worktree") r = removeWorktree(ctx, c);
|
|
1117
|
+
else if (c.kind === "command") {
|
|
1118
|
+
const x = ctx.run(c.cmd, c.args, { timeout: 600_000 });
|
|
1119
|
+
r = x.status === 0 ? { ok: true } : { ok: false, reason: `${c.cmd} exited ${x.status}` };
|
|
1120
|
+
} else if (c.kind === "delegate") {
|
|
1121
|
+
if (!delegates.has(c.tool)) delegates.set(c.tool, []);
|
|
1122
|
+
delegates.get(c.tool).push(c);
|
|
1123
|
+
continue;
|
|
1124
|
+
}
|
|
1125
|
+
if (r.ok) result.removed++;
|
|
1126
|
+
else {
|
|
1127
|
+
result.failed++;
|
|
1128
|
+
result.failures.push({ category: cat.id, path: c.path, reason: r.reason });
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
for (const [tool, items] of delegates) {
|
|
1132
|
+
if (runDelegate(ctx, tool, items)) result.removed += items.length;
|
|
1133
|
+
else {
|
|
1134
|
+
result.failed += items.length;
|
|
1135
|
+
result.failures.push({ category: cat.id, path: tool, reason: `${tool} failed` });
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
return result;
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
// ---------------------------------------------------------------- CLI
|
|
1143
|
+
|
|
1144
|
+
function parseCli(argv) {
|
|
1145
|
+
const o = { only: [], skip: [], tmpRoots: [], devRoots: [] };
|
|
1146
|
+
const num = (k, v) => {
|
|
1147
|
+
if (!/^\d+$/.test(v)) throw new Error(`${k} needs a whole number, got "${v}"`);
|
|
1148
|
+
return Number(v);
|
|
1149
|
+
};
|
|
1150
|
+
for (const a of argv) {
|
|
1151
|
+
const [k, v = ""] = a.includes("=")
|
|
1152
|
+
? [a.slice(0, a.indexOf("=")), a.slice(a.indexOf("=") + 1)]
|
|
1153
|
+
: [a, ""];
|
|
1154
|
+
switch (k) {
|
|
1155
|
+
case "--apply":
|
|
1156
|
+
o.apply = true;
|
|
1157
|
+
break;
|
|
1158
|
+
case "--dry-run":
|
|
1159
|
+
o.dryRun = true;
|
|
1160
|
+
break;
|
|
1161
|
+
case "--trash":
|
|
1162
|
+
case "--transcripts":
|
|
1163
|
+
case "--unattended":
|
|
1164
|
+
case "--json":
|
|
1165
|
+
case "--list":
|
|
1166
|
+
o[k.slice(2)] = true;
|
|
1167
|
+
break;
|
|
1168
|
+
case "--only":
|
|
1169
|
+
case "--skip":
|
|
1170
|
+
o[k.slice(2)].push(...v.split(",").filter(Boolean));
|
|
1171
|
+
break;
|
|
1172
|
+
case "--root":
|
|
1173
|
+
o.devRoots.push(v);
|
|
1174
|
+
break;
|
|
1175
|
+
case "--tmp-root":
|
|
1176
|
+
o.tmpRoots.push(v);
|
|
1177
|
+
break;
|
|
1178
|
+
case "--home":
|
|
1179
|
+
o.home = v;
|
|
1180
|
+
break;
|
|
1181
|
+
case "--report":
|
|
1182
|
+
o.report = v;
|
|
1183
|
+
break;
|
|
1184
|
+
case "--log-days":
|
|
1185
|
+
o.logDays = num(k, v);
|
|
1186
|
+
break;
|
|
1187
|
+
case "--archive-days":
|
|
1188
|
+
o.archiveDays = num(k, v);
|
|
1189
|
+
break;
|
|
1190
|
+
case "--scratch-hours":
|
|
1191
|
+
o.scratchHours = num(k, v);
|
|
1192
|
+
break;
|
|
1193
|
+
case "--build-hours":
|
|
1194
|
+
o.buildHours = num(k, v);
|
|
1195
|
+
break;
|
|
1196
|
+
case "--transcript-days":
|
|
1197
|
+
o.transcriptDays = num(k, v);
|
|
1198
|
+
break;
|
|
1199
|
+
case "--orphan-minutes":
|
|
1200
|
+
o.orphanMinutes = num(k, v);
|
|
1201
|
+
break;
|
|
1202
|
+
case "--top":
|
|
1203
|
+
o.top = num(k, v);
|
|
1204
|
+
break;
|
|
1205
|
+
case "-h":
|
|
1206
|
+
case "--help":
|
|
1207
|
+
o.help = true;
|
|
1208
|
+
break;
|
|
1209
|
+
default:
|
|
1210
|
+
throw new Error(`unknown option ${a}`);
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
const known = new Set(CATEGORIES.map((c) => c.id));
|
|
1214
|
+
for (const id of [...o.only, ...o.skip]) {
|
|
1215
|
+
if (!known.has(id)) throw new Error(`unknown category "${id}"; --list shows them`);
|
|
1216
|
+
}
|
|
1217
|
+
return o;
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
function usage() {
|
|
1221
|
+
const lines = readFileSafe(fileURLToPath(import.meta.url)).split("\n");
|
|
1222
|
+
const start = lines.findIndex((l) => l.includes("Usage:"));
|
|
1223
|
+
const end = lines.findIndex((l, i) => i > start && l.includes("@module"));
|
|
1224
|
+
return lines
|
|
1225
|
+
.slice(start, end)
|
|
1226
|
+
.map((l) => l.replace(/^ \*\s?/, ""))
|
|
1227
|
+
.join("\n");
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
function writeReport(file, data) {
|
|
1231
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
1232
|
+
writeFileSync(file, JSON.stringify(data, null, 2) + "\n");
|
|
1233
|
+
const dir = dirname(file);
|
|
1234
|
+
const old = listDir(dir)
|
|
1235
|
+
.filter((p) => /^report-.*\.json$/.test(basename(p)))
|
|
1236
|
+
.sort()
|
|
1237
|
+
.slice(0, -KEEP_REPORTS);
|
|
1238
|
+
for (const p of old) rmSync(p, { force: true });
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
/** The largest items of a category, how many are left out, and why items were kept. */
|
|
1242
|
+
export function categorySummary(c, top = DEFAULT_TOP) {
|
|
1243
|
+
const sorted = [...c.candidates].sort((a, b) => (b.bytes || 0) - (a.bytes || 0));
|
|
1244
|
+
const kept = {};
|
|
1245
|
+
for (const k of c.skipped) kept[k.reason] = (kept[k.reason] || 0) + 1;
|
|
1246
|
+
return {
|
|
1247
|
+
top: sorted.slice(0, top).map((x) => ({ path: x.path, bytes: x.bytes, kind: x.kind })),
|
|
1248
|
+
more: Math.max(0, sorted.length - top),
|
|
1249
|
+
kept,
|
|
1250
|
+
};
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
/** What an apply of this plan would free: blocked categories are not applied. */
|
|
1254
|
+
export function reclaimable(p) {
|
|
1255
|
+
return p.categories.filter((c) => !c.blocked).reduce((s, c) => s + c.bytes, 0);
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
function printPlan(p, mode, disk, top = 0) {
|
|
1259
|
+
const lines = [];
|
|
1260
|
+
const pct = disk.totalBytes ? ((disk.freeBytes / disk.totalBytes) * 100).toFixed(1) : "?";
|
|
1261
|
+
lines.push(
|
|
1262
|
+
`disk-cleaner: ${mode === "dry-run" ? "dry run, nothing deleted" : "apply"}. Free: ${human(disk.freeBytes)} of ${human(disk.totalBytes)} (${pct}%).`,
|
|
1263
|
+
);
|
|
1264
|
+
lines.push("");
|
|
1265
|
+
lines.push(`${"category".padEnd(18)} ${"items".padStart(6)} ${"size".padStart(9)} note`);
|
|
1266
|
+
for (const c of p.categories) {
|
|
1267
|
+
const note = [c.note, c.skipped.length ? `${c.skipped.length} kept` : null]
|
|
1268
|
+
.filter(Boolean)
|
|
1269
|
+
.join("; ");
|
|
1270
|
+
lines.push(
|
|
1271
|
+
`${c.id.padEnd(18)} ${String(c.candidates.length).padStart(6)} ${human(c.bytes).padStart(9)} ${note}`,
|
|
1272
|
+
);
|
|
1273
|
+
if (top > 0) {
|
|
1274
|
+
const s = categorySummary(c, top);
|
|
1275
|
+
for (const x of s.top)
|
|
1276
|
+
lines.push(`${"".padEnd(18)} ${human(x.bytes).padStart(16)} ${x.path}`);
|
|
1277
|
+
if (s.more) lines.push(`${"".padEnd(18)} ${"".padStart(16)} + ${s.more} more`);
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
lines.push(`${"total".padEnd(18)} ${"".padStart(6)} ${human(p.totalBytes).padStart(9)}`);
|
|
1281
|
+
return lines.join("\n");
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
function summarizeSkips(p) {
|
|
1285
|
+
const out = [];
|
|
1286
|
+
for (const c of p.categories) {
|
|
1287
|
+
const reasons = new Map();
|
|
1288
|
+
for (const s of c.skipped) reasons.set(s.reason, (reasons.get(s.reason) || 0) + 1);
|
|
1289
|
+
if (reasons.size) {
|
|
1290
|
+
out.push(`kept in ${c.id}: ${[...reasons].map(([r, n]) => `${n} ${r}`).join(", ")}`);
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
return out;
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
export function main(argv, env = process.env) {
|
|
1297
|
+
let o;
|
|
1298
|
+
try {
|
|
1299
|
+
o = parseCli(argv);
|
|
1300
|
+
} catch (e) {
|
|
1301
|
+
process.stderr.write(`disk-cleaner: ${e.message}\n`);
|
|
1302
|
+
return 2;
|
|
1303
|
+
}
|
|
1304
|
+
if (o.help) {
|
|
1305
|
+
process.stdout.write(usage() + "\n");
|
|
1306
|
+
return 0;
|
|
1307
|
+
}
|
|
1308
|
+
if (o.list) {
|
|
1309
|
+
for (const c of CATEGORIES) {
|
|
1310
|
+
const tags = [c.unattended ? "unattended-safe" : null, c.optIn ? `needs --${c.optIn}` : null]
|
|
1311
|
+
.filter(Boolean)
|
|
1312
|
+
.join(", ");
|
|
1313
|
+
process.stdout.write(`${c.id.padEnd(18)} ${c.label}${tags ? ` [${tags}]` : ""}\n`);
|
|
1314
|
+
}
|
|
1315
|
+
return 0;
|
|
1316
|
+
}
|
|
1317
|
+
const noProbes = env.DISK_CLEANER_NO_PROBES === "1";
|
|
1318
|
+
if (noProbes && o.apply) {
|
|
1319
|
+
process.stderr.write("disk-cleaner: --apply needs the open-file and process probes\n");
|
|
1320
|
+
return 2;
|
|
1321
|
+
}
|
|
1322
|
+
const unattended = Boolean(o.unattended) || env.MULTI_AGENT_UNATTENDED === "1";
|
|
1323
|
+
if (o.dryRun) o.apply = false;
|
|
1324
|
+
const ctx = makeContext({
|
|
1325
|
+
home: o.home,
|
|
1326
|
+
tmpRoots: o.tmpRoots.length ? o.tmpRoots : undefined,
|
|
1327
|
+
devRoots: o.devRoots.length ? o.devRoots : env.DISK_CLEANER_ROOTS?.split(":").filter(Boolean),
|
|
1328
|
+
logDays: o.logDays,
|
|
1329
|
+
archiveDays: o.archiveDays,
|
|
1330
|
+
transcriptDays: o.transcriptDays,
|
|
1331
|
+
scratchHours: o.scratchHours,
|
|
1332
|
+
repoBuildHours: o.buildHours,
|
|
1333
|
+
orphanMinutes: o.orphanMinutes,
|
|
1334
|
+
...(noProbes
|
|
1335
|
+
? { ps: () => [], openPaths: () => [], run: () => ({ status: 127, stdout: "", stderr: "" }) }
|
|
1336
|
+
: {}),
|
|
1337
|
+
});
|
|
1338
|
+
const sel = {
|
|
1339
|
+
only: o.only,
|
|
1340
|
+
skip: o.skip,
|
|
1341
|
+
unattended,
|
|
1342
|
+
trash: unattended ? false : o.trash,
|
|
1343
|
+
transcripts: unattended ? false : o.transcripts,
|
|
1344
|
+
};
|
|
1345
|
+
const before = diskStatus(ctx.home);
|
|
1346
|
+
const planned = plan(ctx, sel);
|
|
1347
|
+
const mode = o.apply ? "apply" : "dry-run";
|
|
1348
|
+
const report = {
|
|
1349
|
+
version: VERSION,
|
|
1350
|
+
mode,
|
|
1351
|
+
unattended,
|
|
1352
|
+
startedAt: new Date(ctx.now).toISOString(),
|
|
1353
|
+
disk: {
|
|
1354
|
+
before,
|
|
1355
|
+
expectedFreeBytes: before.freeBytes == null ? null : before.freeBytes + reclaimable(planned),
|
|
1356
|
+
},
|
|
1357
|
+
totalBytes: planned.totalBytes,
|
|
1358
|
+
reclaimableBytes: reclaimable(planned),
|
|
1359
|
+
categories: planned.categories.map((c) => ({
|
|
1360
|
+
id: c.id,
|
|
1361
|
+
label: c.label,
|
|
1362
|
+
bytes: c.bytes,
|
|
1363
|
+
note: c.note,
|
|
1364
|
+
candidates: c.candidates.map((x) => ({ path: x.path, bytes: x.bytes, kind: x.kind })),
|
|
1365
|
+
skipped: c.skipped,
|
|
1366
|
+
blocked: c.blocked || null,
|
|
1367
|
+
...categorySummary(c, o.top ?? DEFAULT_TOP),
|
|
1368
|
+
})),
|
|
1369
|
+
orphans: listOrphans(ctx),
|
|
1370
|
+
};
|
|
1371
|
+
let applied = null;
|
|
1372
|
+
if (o.apply) {
|
|
1373
|
+
applied = applyPlan(ctx, planned);
|
|
1374
|
+
const after = diskStatus(ctx.home);
|
|
1375
|
+
report.disk.after = after;
|
|
1376
|
+
report.applied = {
|
|
1377
|
+
...applied,
|
|
1378
|
+
freedBytes:
|
|
1379
|
+
after.freeBytes != null && before.freeBytes != null
|
|
1380
|
+
? Math.max(0, after.freeBytes - before.freeBytes)
|
|
1381
|
+
: null,
|
|
1382
|
+
};
|
|
1383
|
+
}
|
|
1384
|
+
const reportFile =
|
|
1385
|
+
o.report ||
|
|
1386
|
+
join(
|
|
1387
|
+
ctx.home,
|
|
1388
|
+
".claude",
|
|
1389
|
+
"logs",
|
|
1390
|
+
"disk-cleaner",
|
|
1391
|
+
`report-${report.startedAt.replace(/[:.]/g, "-")}.json`,
|
|
1392
|
+
);
|
|
1393
|
+
try {
|
|
1394
|
+
writeReport(reportFile, report);
|
|
1395
|
+
} catch (e) {
|
|
1396
|
+
process.stderr.write(`disk-cleaner: could not write the report: ${e.message}\n`);
|
|
1397
|
+
}
|
|
1398
|
+
if (o.json) {
|
|
1399
|
+
process.stdout.write(JSON.stringify(report, null, 2) + "\n");
|
|
1400
|
+
} else {
|
|
1401
|
+
const lines = [printPlan(planned, mode, before, o.top || 0), ...summarizeSkips(planned)];
|
|
1402
|
+
if (report.orphans.length) {
|
|
1403
|
+
lines.push(
|
|
1404
|
+
`orphaned session processes: ${report.orphans.length} (information only; never stopped)`,
|
|
1405
|
+
);
|
|
1406
|
+
}
|
|
1407
|
+
if (applied) {
|
|
1408
|
+
lines.push(
|
|
1409
|
+
`removed ${applied.removed}, failed ${applied.failed}; freed ${human(report.applied.freedBytes)} (df before ${human(before.freeBytes)}, after ${human(report.disk.after.freeBytes)})`,
|
|
1410
|
+
);
|
|
1411
|
+
for (const f of applied.failures.slice(0, 10)) {
|
|
1412
|
+
lines.push(` failed ${f.category}: ${f.path} (${f.reason})`);
|
|
1413
|
+
}
|
|
1414
|
+
for (const h of applied.held) lines.push(` held ${h.category}: ${h.reason}`);
|
|
1415
|
+
} else {
|
|
1416
|
+
lines.push("re-run with --apply to delete the listed items");
|
|
1417
|
+
}
|
|
1418
|
+
lines.push(`report: ${reportFile}`);
|
|
1419
|
+
process.stdout.write(lines.join("\n") + "\n");
|
|
1420
|
+
}
|
|
1421
|
+
return applied && applied.failed > 0 ? 1 : 0;
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
function invokedDirectly() {
|
|
1425
|
+
try {
|
|
1426
|
+
return import.meta.url === pathToFileURL(realpathSync(process.argv[1] ?? "")).href;
|
|
1427
|
+
} catch {
|
|
1428
|
+
return false;
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
if (invokedDirectly()) process.exitCode = main(process.argv.slice(2));
|