@oficiallyakshay/trash-panda 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +108 -2
- package/docs/reference.md +220 -0
- package/examples/in-charge.json +7 -0
- package/examples/live.json +17 -0
- package/package.json +38 -4
- package/scripts/claude-leftovers-cleanup.mjs +242 -0
- package/src/claude-leftovers.mjs +949 -0
- package/src/metrics.mjs +233 -0
- package/src/rebuildables.mjs +491 -0
- package/src/records.mjs +326 -0
- package/src/settings.mjs +205 -0
- package/src/setup.mjs +428 -0
- package/src/temp-entries.mjs +153 -0
- package/src/triggers.mjs +500 -0
- package/src/tui/format.mjs +177 -0
- package/src/tui/watch.mjs +118 -0
- package/src/update.mjs +281 -0
- package/src/worktree-git.mjs +145 -0
- package/src/worktree-liveness.mjs +87 -0
|
@@ -0,0 +1,949 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/claude-leftovers.mjs — removes what Claude sessions leave behind on
|
|
3
|
+
* disk, and nothing else.
|
|
4
|
+
*
|
|
5
|
+
* WHY THIS EXISTS. Coding-agent sessions leave gigabytes on a developer's
|
|
6
|
+
* disk: copies of Chrome that a crashed or killed Chrome left in the macOS
|
|
7
|
+
* temporary folder (about 1.4 GB each), finished repo copies whose every
|
|
8
|
+
* commit is safe elsewhere, and the scratch folders of sessions that are over.
|
|
9
|
+
*
|
|
10
|
+
* PROOF, NEVER AGE. No rule waits on how old something is, with one exception:
|
|
11
|
+
* the temp entries rule, where age is one more guard on a list of names the
|
|
12
|
+
* person writes (src/temp-entries.mjs). An item goes only
|
|
13
|
+
* when a check proves it is finished; a probe that fails or answers unclearly
|
|
14
|
+
* keeps it, and a record source that is missing or unreadable keeps every item
|
|
15
|
+
* it could name. A leftover kept is a few GB; a live copy deleted is a
|
|
16
|
+
* session's work. Just before each delete, `stillGoes(item)` runs every check
|
|
17
|
+
* for that item again, GitHub included; anything but a clean yes keeps it.
|
|
18
|
+
*
|
|
19
|
+
* - Chrome copies: `code_sign_clone.*` directories directly inside the
|
|
20
|
+
* user's `X/com.google.Chrome.code_sign_clone` or
|
|
21
|
+
* `X/org.chromium.Chromium.code_sign_clone`. One goes only when no process
|
|
22
|
+
* has a file open inside it and no running Chrome started before the copy
|
|
23
|
+
* was made (a long-running Chrome runs from a copy made after its start).
|
|
24
|
+
* - Worktrees: in the repositories the Claude desktop app's registry names
|
|
25
|
+
* (schemaVersion 2), and in those under each settings `repoRoots` folder;
|
|
26
|
+
* no readable registry turns both off. A copy under
|
|
27
|
+
* `<repo>/.claude/worktrees/` stays when the registry, a live process or an
|
|
28
|
+
* unarchived app session names it; git locks it; a process works in it or
|
|
29
|
+
* has a file in it open; it is detached or on the default branch; it has a
|
|
30
|
+
* changed, untracked or unknown ignored file, a nested repository or a link
|
|
31
|
+
* out; or it has an open pull request (gh, read only; no answer keeps it).
|
|
32
|
+
* Otherwise it goes when one merged pull request carries every commit, or
|
|
33
|
+
* when an owner record says its session is archived and the live remote
|
|
34
|
+
* has every commit; a copy with no owner and no merged pull request, every
|
|
35
|
+
* commit on the live remote, goes only when free space is below
|
|
36
|
+
* `lowMarkPct`. `git worktree remove` only: never a branch delete, an
|
|
37
|
+
* unlock or a force.
|
|
38
|
+
* - Scratch: `/private/tmp/claude-<uid>/` folders named (every
|
|
39
|
+
* non-alphanumeric character becomes `-`) after a worktree that no longer
|
|
40
|
+
* exists. An ended session can resume, so one goes only once its app
|
|
41
|
+
* session is archived or its Claude history is gone, and nothing uses it:
|
|
42
|
+
* no process inside, no open file, no git copy inside with a local change,
|
|
43
|
+
* an ignored file outside the caches, or a commit on any ref that its live
|
|
44
|
+
* remote lacks.
|
|
45
|
+
*
|
|
46
|
+
* - Rebuildable folders: a `node_modules` or Swift `.build` in a linked
|
|
47
|
+
* worktree, only when git ignores it, the worktree has no unfinished work,
|
|
48
|
+
* nothing is using it and its package file and lockfile are committed and
|
|
49
|
+
* unchanged (an unowned worktree only when space is low).
|
|
50
|
+
* - Test folders: `<pid>-<name>` folders in the user's listed test
|
|
51
|
+
* directories whose process is gone and with no file open inside.
|
|
52
|
+
* - Module caches: hash-named cache folders in the user's listed cache
|
|
53
|
+
* directories that no repository links to or needs by lockfile hash, set
|
|
54
|
+
* aside by rename and re-checked before the delete.
|
|
55
|
+
* - uv cache: `uv cache prune` (never forced), skipped while anything holds
|
|
56
|
+
* the cache lock.
|
|
57
|
+
* - Old Playwright builds: browser builds no installed playwright names.
|
|
58
|
+
* - Stale worktree records: `git worktree prune` of records whose folder is gone.
|
|
59
|
+
* - Temp entries: old entries of the user temp folder whose names start with a
|
|
60
|
+
* listed prefix, in small batches; nothing is listed by default.
|
|
61
|
+
*
|
|
62
|
+
* Preview (src/settings.mjs, on by default) turns every delete into a report.
|
|
63
|
+
*/
|
|
64
|
+
|
|
65
|
+
import { execFile, execFileSync } from "node:child_process";
|
|
66
|
+
import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync, statSync, statfsSync } from "node:fs";
|
|
67
|
+
import { rm } from "node:fs/promises";
|
|
68
|
+
import { homedir } from "node:os";
|
|
69
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
70
|
+
import { fileURLToPath } from "node:url";
|
|
71
|
+
import { promisify } from "node:util";
|
|
72
|
+
import { PLAYWRIGHT_ROOT, findUv, pruneUvCache, pruneWorktreeRecords, sweepModuleCaches, sweepPlaywright, sweepRebuildables, sweepTestFolders } from "./rebuildables.mjs";
|
|
73
|
+
import { DEFAULTS, readSettings } from "./settings.mjs";
|
|
74
|
+
import { sweepTempEntries, tempReport } from "./temp-entries.mjs";
|
|
75
|
+
import { commitsBeyondMergedHead, mergedPrInfo, openPrCount, parseWorktreePorcelain } from "./worktree-git.mjs";
|
|
76
|
+
import { LSOF_BIN, dirHasLiveCwd, liveCwds, parseLsofCwds } from "./worktree-liveness.mjs";
|
|
77
|
+
|
|
78
|
+
const execFileP = promisify(execFile);
|
|
79
|
+
|
|
80
|
+
// The only shape a Chrome-copy root may resolve to: the per-user temp parent
|
|
81
|
+
// macOS hands out under /private/var/folders, then X/<bundle id>.code_sign_clone.
|
|
82
|
+
export const CHROME_ROOT_RE = /^\/private\/var\/folders\/[^/]{2}\/[^/]+\/X\/(com\.google\.Chrome|org\.chromium\.Chromium)\.code_sign_clone$/;
|
|
83
|
+
const CHROME_ROOT_NAMES = ["com.google.Chrome.code_sign_clone", "org.chromium.Chromium.code_sign_clone"];
|
|
84
|
+
const CHROME_COPY_PREFIX = "code_sign_clone.";
|
|
85
|
+
const CHROME_PROCESS_RE = /Google Chrome|Chromium/;
|
|
86
|
+
// ps gives a start time to the second only: a Chrome this close to the copy's
|
|
87
|
+
// birth counts as started before it.
|
|
88
|
+
const PS_CLOCK_SLACK_MS = 5_000;
|
|
89
|
+
export const PS_BIN = "/bin/ps";
|
|
90
|
+
|
|
91
|
+
export const CLAUDE_WORKTREE_REGISTRY = join(homedir(), "Library/Application Support/Claude/git-worktrees.json");
|
|
92
|
+
// The desktop app's session records (`cwd`, `worktreePath`, `isArchived`) and
|
|
93
|
+
// Claude's history folders, one per working directory.
|
|
94
|
+
export const APP_SESSIONS_DIR = join(homedir(), "Library/Application Support/Claude/claude-code-sessions");
|
|
95
|
+
export const CLAUDE_HISTORY_DIR = join(homedir(), ".claude/projects");
|
|
96
|
+
// Absolute, because a detached session-start process may have no PATH to it.
|
|
97
|
+
const GH_CANDIDATES = [join(homedir(), ".local/bin/gh"), "/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh"];
|
|
98
|
+
// Ignored paths a merged repo copy may still hold: dependencies, coverage and
|
|
99
|
+
// the code graph, which a fresh checkout rebuilds. Generic names (build, dist,
|
|
100
|
+
// .cache) are not here: a hand-placed file there, a secret included, keeps the
|
|
101
|
+
// copy. Any other ignored file keeps it too.
|
|
102
|
+
const CACHE_SEGMENTS = new Set(["node_modules", "coverage", ".nyc_output", "graphify-out", "__pycache__", ".pytest_cache"]);
|
|
103
|
+
const PROTECTED_BRANCHES = ["main", "master"];
|
|
104
|
+
// The free-space figure lives on the data volume; `/` is the sealed system one.
|
|
105
|
+
export const DATA_VOLUME = "/System/Volumes/Data";
|
|
106
|
+
/** True when the free share of the disk is under the low mark (a percent). Unreadable space is not low. */
|
|
107
|
+
export const isLowSpace = (disk, lowMarkPct = DEFAULTS.lowMarkPct) => disk?.freePct != null && disk.freePct < lowMarkPct;
|
|
108
|
+
export const formatGb = (b) => `${(b / 1024 ** 3).toFixed(1)} GB`;
|
|
109
|
+
/** One item's size, in the largest unit that fits; null is a size nothing measured. */
|
|
110
|
+
export function formatSize(b) {
|
|
111
|
+
if (b === null) return "size not measured";
|
|
112
|
+
if (b >= 1024 ** 3) return formatGb(b);
|
|
113
|
+
return b >= 1024 ** 2 ? `${(b / 1024 ** 2).toFixed(1)} MB` : `${(b / 1024).toFixed(1)} KB`;
|
|
114
|
+
}
|
|
115
|
+
// The classes a run may be limited to (--only), each as the rules it holds.
|
|
116
|
+
export const CLASSES = {
|
|
117
|
+
chrome: ["chrome"],
|
|
118
|
+
worktrees: ["repos", "codeFolder", "records"],
|
|
119
|
+
scratch: ["scratch"],
|
|
120
|
+
rebuildables: ["rebuild"],
|
|
121
|
+
tests: ["tests"],
|
|
122
|
+
caches: ["caches"],
|
|
123
|
+
uv: ["uv"],
|
|
124
|
+
playwright: ["playwright"],
|
|
125
|
+
temp: ["temp"],
|
|
126
|
+
};
|
|
127
|
+
// The cleanup rules, as keys of a run's result, with the name the summary prints.
|
|
128
|
+
export const CLEANUP_RULES = [
|
|
129
|
+
{ key: "chrome", label: "Chrome copies" },
|
|
130
|
+
{ key: "repos", label: "repo copies" },
|
|
131
|
+
{ key: "codeFolder", label: "repo roots" },
|
|
132
|
+
{ key: "scratch", label: "scratch" },
|
|
133
|
+
{ key: "rebuild", label: "rebuildable folders" },
|
|
134
|
+
{ key: "tests", label: "test folders" },
|
|
135
|
+
{ key: "caches", label: "module caches" },
|
|
136
|
+
{ key: "uv", label: "uv cache" },
|
|
137
|
+
{ key: "playwright", label: "old Playwright builds" },
|
|
138
|
+
{ key: "records", label: "stale worktree records" },
|
|
139
|
+
{ key: "temp", label: "old temp entries" },
|
|
140
|
+
];
|
|
141
|
+
const DIRTY_REASON = "uncommitted or untracked files";
|
|
142
|
+
const RECHECK_REASON = "changed before the delete";
|
|
143
|
+
|
|
144
|
+
// ── small fs helpers ────────────────────────────────────────────────────────
|
|
145
|
+
|
|
146
|
+
const isInside = (child, root) => child.startsWith(`${root}/`);
|
|
147
|
+
const within = (p, root) => p === root || isInside(p, root);
|
|
148
|
+
|
|
149
|
+
// Function declarations only cross the import cycle with src/rebuildables.mjs
|
|
150
|
+
// at load time, so these stay declarations.
|
|
151
|
+
export async function duBytes(path, { execImpl = execFileP } = {}) {
|
|
152
|
+
try {
|
|
153
|
+
const { stdout } = await execImpl("/usr/bin/du", ["-sk", path], { timeout: 120_000 });
|
|
154
|
+
const kb = Number.parseInt(String(stdout).split(/\s/)[0], 10);
|
|
155
|
+
return Number.isFinite(kb) ? kb * 1024 : 0;
|
|
156
|
+
} catch {
|
|
157
|
+
return 0;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Free bytes, total bytes and free percent (one decimal) of `volume`; all null when it cannot be read. */
|
|
162
|
+
export function diskSpace(volume = DATA_VOLUME, { statfsImpl = statfsSync } = {}) {
|
|
163
|
+
try {
|
|
164
|
+
const s = statfsImpl(volume);
|
|
165
|
+
const free = Number(s.bavail) * Number(s.bsize);
|
|
166
|
+
const total = Number(s.blocks) * Number(s.bsize);
|
|
167
|
+
if (!(total > 0)) throw new Error("no size");
|
|
168
|
+
return { freeBytes: free, totalBytes: total, freePct: Math.round((free / total) * 1000) / 10 };
|
|
169
|
+
} catch {
|
|
170
|
+
return { freeBytes: null, totalBytes: null, freePct: null };
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Free bytes on `volume`, or null when it cannot be read. */
|
|
175
|
+
export function freeBytes(volume = DATA_VOLUME, opts) {
|
|
176
|
+
return diskSpace(volume, opts).freeBytes;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Free space on `volume` in percent, or null when it cannot be read. */
|
|
180
|
+
export function freePct(volume = DATA_VOLUME, { statfsImpl = statfsSync } = {}) {
|
|
181
|
+
try {
|
|
182
|
+
const s = statfsImpl(volume);
|
|
183
|
+
const pct = (Number(s.bavail) / Number(s.blocks)) * 100;
|
|
184
|
+
return Number.isFinite(pct) ? pct : null;
|
|
185
|
+
} catch {
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** True when `dir` or a folder inside it is on another device than `dev`. No link is followed. */
|
|
191
|
+
function holdsOtherVolume(dir, dev, lstat) {
|
|
192
|
+
if (lstat(dir).dev !== dev) return true;
|
|
193
|
+
return readdirSync(dir, { withFileTypes: true }).some((e) => e.isDirectory() && holdsOtherVolume(join(dir, e.name), dev, lstat));
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Delete one directory: refuses a symlink or non-directory, and re-checks that
|
|
198
|
+
* its resolved path is still directly inside `realRoot` right before the rm.
|
|
199
|
+
* A folder with a volume mounted in it stays: the rm would empty that volume.
|
|
200
|
+
*/
|
|
201
|
+
export async function removeDirectChild(path, realRoot, { lstat = lstatSync } = {}) {
|
|
202
|
+
const st = lstatSync(path);
|
|
203
|
+
if (st.isSymbolicLink() || !st.isDirectory()) throw new Error("not a plain directory");
|
|
204
|
+
const real = realpathSync(path);
|
|
205
|
+
if (dirname(real) !== realRoot) throw new Error("escapes its root");
|
|
206
|
+
if (holdsOtherVolume(real, lstat(realRoot).dev, lstat)) throw new Error("holds another volume");
|
|
207
|
+
await rm(real, { recursive: true, force: false });
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Why a folder's own tree keeps it, or null: a `.git` below its top (a nested
|
|
212
|
+
* repository) or a link resolving outside it. Never follows a link.
|
|
213
|
+
*/
|
|
214
|
+
function nestedRepoOrLinkOut(dir) {
|
|
215
|
+
try {
|
|
216
|
+
const realDir = realpathSync(dir);
|
|
217
|
+
const stack = [dir];
|
|
218
|
+
while (stack.length) {
|
|
219
|
+
const cur = stack.pop();
|
|
220
|
+
for (const ent of readdirSync(cur, { withFileTypes: true })) {
|
|
221
|
+
const p = join(cur, ent.name);
|
|
222
|
+
if (ent.name === ".git" && cur !== dir) return "a nested repository";
|
|
223
|
+
if (ent.isSymbolicLink()) {
|
|
224
|
+
let target;
|
|
225
|
+
try {
|
|
226
|
+
target = realpathSync(p);
|
|
227
|
+
} catch {
|
|
228
|
+
return "a link out";
|
|
229
|
+
}
|
|
230
|
+
if (!within(target, realDir)) return "a link out";
|
|
231
|
+
} else if (ent.isDirectory() && !(ent.name === ".git" && cur === dir)) stack.push(p);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return null;
|
|
235
|
+
} catch {
|
|
236
|
+
return "files unreadable";
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// ── probes: one fresh look at the machine ───────────────────────────────────
|
|
241
|
+
|
|
242
|
+
/** Every open file path on the system from one lsof pass, or null when lsof failed. */
|
|
243
|
+
export async function openFilePaths({ execImpl = execFileP } = {}) {
|
|
244
|
+
try {
|
|
245
|
+
const { stdout } = await execImpl(LSOF_BIN, ["-n", "-P", "-w", "-F", "n"], { maxBuffer: 512 * 1024 * 1024, timeout: 120_000 });
|
|
246
|
+
return parseLsofCwds(stdout);
|
|
247
|
+
} catch {
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** ps `etime` (`[[dd-]hh:]mm:ss`) in ms, or NaN. */
|
|
253
|
+
function etimeMs(s) {
|
|
254
|
+
const m = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(s);
|
|
255
|
+
if (!m) return Number.NaN;
|
|
256
|
+
const [, d = 0, h = 0, min, sec] = m;
|
|
257
|
+
return (((Number(d) * 24 + Number(h)) * 60 + Number(min)) * 60 + Number(sec)) * 1000;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Every process's start time and command line, or null when ps failed or gave an unreadable line. */
|
|
261
|
+
export async function processList({ execImpl = execFileP, now = Date.now() } = {}) {
|
|
262
|
+
try {
|
|
263
|
+
const { stdout } = await execImpl(PS_BIN, ["-axww", "-o", "etime=", "-o", "args="], { maxBuffer: 64 * 1024 * 1024, timeout: 30_000 });
|
|
264
|
+
const procs = [];
|
|
265
|
+
for (const line of String(stdout).split("\n")) {
|
|
266
|
+
const m = /^\s*(\S+)\s+(.*)$/.exec(line);
|
|
267
|
+
if (!m) continue;
|
|
268
|
+
const ms = etimeMs(m[1]);
|
|
269
|
+
if (Number.isNaN(ms)) return null;
|
|
270
|
+
procs.push({ startMs: now - ms, args: m[2] });
|
|
271
|
+
}
|
|
272
|
+
return procs;
|
|
273
|
+
} catch {
|
|
274
|
+
return null;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function readJsonFiles(dir, depth) {
|
|
279
|
+
const out = [];
|
|
280
|
+
for (const ent of readdirSync(dir, { withFileTypes: true })) {
|
|
281
|
+
const p = join(dir, ent.name);
|
|
282
|
+
if (ent.isDirectory() && depth > 0) out.push(...readJsonFiles(p, depth - 1));
|
|
283
|
+
else if (ent.isFile() && ent.name.endsWith(".json")) out.push(JSON.parse(readFileSync(p, "utf8")));
|
|
284
|
+
}
|
|
285
|
+
return out;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* The app's session records as `{ paths, archived }`, or null when the folder
|
|
290
|
+
* or any record cannot be read. `archived` is true only for `isArchived: true`.
|
|
291
|
+
*/
|
|
292
|
+
export function readSessionRecords(dir = APP_SESSIONS_DIR) {
|
|
293
|
+
try {
|
|
294
|
+
return readJsonFiles(dir, 4)
|
|
295
|
+
.filter((r) => r && typeof r === "object")
|
|
296
|
+
.map((r) => ({ paths: [r.cwd, r.worktreePath, r.originCwd].filter((p) => typeof p === "string" && p), archived: r.isArchived === true }))
|
|
297
|
+
.filter((r) => r.paths.length);
|
|
298
|
+
} catch {
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** The names of Claude's history folders, lowercased, or null when the folder cannot be read. */
|
|
304
|
+
function historyNames(dir = CLAUDE_HISTORY_DIR) {
|
|
305
|
+
try {
|
|
306
|
+
return new Set(readdirSync(dir).map((n) => n.toLowerCase()));
|
|
307
|
+
} catch {
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** One fresh look: working folders, open files, processes, session records, history and free space. */
|
|
313
|
+
async function lookAround({ execImpl, sessionsDir, historyDir, volume, statfsImpl, lowMarkPct }) {
|
|
314
|
+
const [cwds, openPaths, procs] = await Promise.all([liveCwds({ execImpl }), openFilePaths({ execImpl }), processList({ execImpl })]);
|
|
315
|
+
const pct = freePct(volume, { statfsImpl });
|
|
316
|
+
return { cwds, openPaths, procs, sessions: readSessionRecords(sessionsDir), history: historyNames(historyDir), lowSpace: pct !== null && pct < lowMarkPct, freePct: pct };
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* The last word before a delete: runs every check of `item` again
|
|
321
|
+
* (`item.check()`); only a plain `true` lets it go, anything else or a throw keeps it.
|
|
322
|
+
*/
|
|
323
|
+
export async function stillGoes(item) {
|
|
324
|
+
try {
|
|
325
|
+
return (await item.check()) === true;
|
|
326
|
+
} catch {
|
|
327
|
+
return false;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** What keeps a path in use: a process inside, a file open inside, a process naming it; or null. */
|
|
332
|
+
function inUse(path, { cwds, openPaths, procs }) {
|
|
333
|
+
if (dirHasLiveCwd(cwds, path) !== false) return "a process is inside, or that could not be checked";
|
|
334
|
+
if (!Array.isArray(openPaths)) return "open files could not be checked";
|
|
335
|
+
// Callers resolved the path just before; a throw here keeps the item.
|
|
336
|
+
const roots = [path, realpathSync(path)];
|
|
337
|
+
if (openPaths.some((o) => roots.some((r) => within(o, r)))) return "a process has a file open inside";
|
|
338
|
+
if (!Array.isArray(procs)) return "processes could not be checked";
|
|
339
|
+
if (procs.some((p) => roots.some((r) => p.args.includes(r)))) return "a live process names it";
|
|
340
|
+
return null;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// ── Chrome copies ───────────────────────────────────────────────────────────
|
|
344
|
+
|
|
345
|
+
/** The user temp folder macOS names, whatever TMPDIR says, or null when it cannot be read. */
|
|
346
|
+
export function userTempDir({ execFileSyncImpl = execFileSync } = {}) {
|
|
347
|
+
try {
|
|
348
|
+
const tmp = String(execFileSyncImpl("/usr/bin/getconf", ["DARWIN_USER_TEMP_DIR"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] })).trim();
|
|
349
|
+
return tmp.replace(/\/+$/, "") || null;
|
|
350
|
+
} catch {
|
|
351
|
+
return null;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** The two Chrome-copy roots under this user's temp parent, or [] when it cannot be read. */
|
|
356
|
+
export function chromeCopyRoots(opts) {
|
|
357
|
+
const tmp = userTempDir(opts);
|
|
358
|
+
return tmp ? CHROME_ROOT_NAMES.map((n) => join(dirname(tmp), "X", n)) : [];
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** Why one Chrome copy stays, or null when it may go. */
|
|
362
|
+
function chromeCopyKeeps(path, { openPaths, procs }) {
|
|
363
|
+
if (!Array.isArray(openPaths)) return "lsof failed";
|
|
364
|
+
if (!Array.isArray(procs)) return "ps failed";
|
|
365
|
+
const st = lstatSync(path);
|
|
366
|
+
if (st.isSymbolicLink() || !st.isDirectory()) return "not a plain directory";
|
|
367
|
+
if (openPaths.some((o) => within(o, path))) return "a process has a file open inside";
|
|
368
|
+
// The later of birth and change time: a file system without birth times,
|
|
369
|
+
// or a copy changed since, only makes more running Chromes count as older.
|
|
370
|
+
const made = Math.max(st.birthtimeMs || 0, st.ctimeMs);
|
|
371
|
+
if (procs.some((p) => CHROME_PROCESS_RE.test(p.args) && p.startMs <= made + PS_CLOCK_SLACK_MS)) return "a Chrome started before it is running";
|
|
372
|
+
return null;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* The Chrome-copy rule. `look` is the run's look (openPaths and procs), `probe`
|
|
377
|
+
* takes a fresh one; a failed lsof or ps skips the whole rule. Never removes a
|
|
378
|
+
* root itself.
|
|
379
|
+
*/
|
|
380
|
+
export async function sweepChromeCopies({ roots, look: first, probe, apply = false, rootRe = CHROME_ROOT_RE, uid = process.getuid(), execImpl = execFileP }) {
|
|
381
|
+
const out = { removed: [], kept: [], errors: 0, bytes: 0, skipped: null };
|
|
382
|
+
if (!Array.isArray(first.openPaths) || !Array.isArray(first.procs)) {
|
|
383
|
+
out.skipped = Array.isArray(first.openPaths) ? "ps failed" : "lsof failed";
|
|
384
|
+
return out;
|
|
385
|
+
}
|
|
386
|
+
for (const root of roots) {
|
|
387
|
+
if (!existsSync(root)) continue;
|
|
388
|
+
let realRoot;
|
|
389
|
+
try {
|
|
390
|
+
realRoot = realpathSync(root);
|
|
391
|
+
if (!rootRe.test(realRoot)) throw new Error("root outside the Chrome-copy pattern");
|
|
392
|
+
if (statSync(realRoot).uid !== uid) throw new Error("root not owned by this user");
|
|
393
|
+
} catch (e) {
|
|
394
|
+
out.kept.push({ path: root, reason: e.message });
|
|
395
|
+
continue;
|
|
396
|
+
}
|
|
397
|
+
for (const ent of readdirSync(realRoot, { withFileTypes: true })) {
|
|
398
|
+
if (!ent.name.startsWith(CHROME_COPY_PREFIX)) continue;
|
|
399
|
+
const path = join(realRoot, ent.name);
|
|
400
|
+
try {
|
|
401
|
+
const why = chromeCopyKeeps(path, first);
|
|
402
|
+
if (why) throw new Error(why);
|
|
403
|
+
const bytes = await duBytes(path, { execImpl });
|
|
404
|
+
if (apply) {
|
|
405
|
+
if (!(await stillGoes({ check: async () => chromeCopyKeeps(path, await probe()) === null }))) throw new Error(RECHECK_REASON);
|
|
406
|
+
await removeDirectChild(path, realRoot);
|
|
407
|
+
}
|
|
408
|
+
out.removed.push({ path, bytes, reason: "no process has a file open inside, and no Chrome started before it is running" });
|
|
409
|
+
out.bytes += bytes;
|
|
410
|
+
} catch (e) {
|
|
411
|
+
out.kept.push({ path, reason: e.message });
|
|
412
|
+
if (e.code) out.errors += 1;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
return out;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// ── worktrees ───────────────────────────────────────────────────────────────
|
|
420
|
+
|
|
421
|
+
/** The app's worktree registry entries, or `{ ok:false }` with why the rule is off. */
|
|
422
|
+
export function readWorktreeRegistry(path = CLAUDE_WORKTREE_REGISTRY) {
|
|
423
|
+
let parsed;
|
|
424
|
+
try {
|
|
425
|
+
parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
426
|
+
} catch {
|
|
427
|
+
return { ok: false, reason: "no readable app worktree registry" };
|
|
428
|
+
}
|
|
429
|
+
if (parsed?.schemaVersion !== 2 || !parsed.worktrees || typeof parsed.worktrees !== "object") {
|
|
430
|
+
return { ok: false, reason: "unknown app worktree registry schema" };
|
|
431
|
+
}
|
|
432
|
+
return { ok: true, entries: Object.values(parsed.worktrees).filter((e) => e && typeof e === "object") };
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** The lowercased path keys of every copy the registry names, or null when it cannot be read. */
|
|
436
|
+
function registryListed(path) {
|
|
437
|
+
const reg = readWorktreeRegistry(path);
|
|
438
|
+
return reg.ok ? new Set(reg.entries.flatMap((e) => (typeof e.path === "string" ? pathKeys(e.path) : []))) : null;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
export function findGh({ existsSyncImpl = existsSync } = {}) {
|
|
442
|
+
return GH_CANDIDATES.find((p) => existsSyncImpl(p)) ?? null;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
// Paths compared case-insensitively: APFS is, so two spellings are one folder.
|
|
446
|
+
function pathKeys(p) {
|
|
447
|
+
const keys = [String(p).replace(/\/+$/, "").toLowerCase()];
|
|
448
|
+
try {
|
|
449
|
+
keys.push(realpathSync(p).toLowerCase());
|
|
450
|
+
} catch {
|
|
451
|
+
// gone — the literal path still counts as listed
|
|
452
|
+
}
|
|
453
|
+
return keys;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
async function git(args, execImpl) {
|
|
457
|
+
const { stdout } = await execImpl("git", args, { timeout: 60_000, maxBuffer: 64 * 1024 * 1024 });
|
|
458
|
+
return String(stdout ?? "").trim();
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** One repository, resolved and checked, or null when it does not qualify. */
|
|
462
|
+
async function resolveRepo(baseRepo, { home, execImpl }) {
|
|
463
|
+
try {
|
|
464
|
+
const realRepo = realpathSync(baseRepo);
|
|
465
|
+
if (!isInside(realRepo, realpathSync(home))) return null;
|
|
466
|
+
const wtRoot = join(realRepo, ".claude", "worktrees");
|
|
467
|
+
if (!lstatSync(wtRoot).isDirectory()) return null;
|
|
468
|
+
await git(["-C", realRepo, "rev-parse", "--git-common-dir"], execImpl);
|
|
469
|
+
let defaultBranch = null;
|
|
470
|
+
try {
|
|
471
|
+
defaultBranch = (await git(["-C", realRepo, "symbolic-ref", "--short", "refs/remotes/origin/HEAD"], execImpl)).replace(/^origin\//, "");
|
|
472
|
+
} catch {
|
|
473
|
+
// no origin HEAD — main and master stay protected regardless
|
|
474
|
+
}
|
|
475
|
+
const records = parseWorktreePorcelain(await git(["-C", realRepo, "worktree", "list", "--porcelain"], execImpl));
|
|
476
|
+
return { realRepo, realWtRoot: realpathSync(wtRoot), protectedBranches: new Set([...PROTECTED_BRANCHES, defaultBranch].filter(Boolean)), records };
|
|
477
|
+
} catch {
|
|
478
|
+
return null;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* Why one copy's files keep it, or null when nothing does. One status scan with
|
|
484
|
+
* both modes named, so the user's git config cannot hide a file; `matching`
|
|
485
|
+
* lists an ignored folder as one line, never its contents.
|
|
486
|
+
*/
|
|
487
|
+
async function filesThatKeep(path, execImpl) {
|
|
488
|
+
let lines;
|
|
489
|
+
try {
|
|
490
|
+
lines = (await git(["-C", path, "status", "--porcelain", "--ignored=matching", "--untracked-files=all"], execImpl)).split("\n").filter(Boolean);
|
|
491
|
+
} catch {
|
|
492
|
+
return DIRTY_REASON;
|
|
493
|
+
}
|
|
494
|
+
if (lines.some((l) => !l.startsWith("!! "))) return DIRTY_REASON;
|
|
495
|
+
// The ignored entry itself must be a cache: a file only under a folder with such a name is not one.
|
|
496
|
+
if (lines.some((l) => !CACHE_SEGMENTS.has(basename(l.slice(3))))) return "ignored files outside caches";
|
|
497
|
+
return null;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** `{ ok:true, prNumber }` when exactly one merged PR carries every commit on `branch`; `count` when gh answered. */
|
|
501
|
+
async function mergedCarriesAll(branch, { repo, gh, execImpl }) {
|
|
502
|
+
const info = await mergedPrInfo(branch, { execGh: (_bin, args) => execImpl(gh, args, { cwd: repo, timeout: 60_000 }) });
|
|
503
|
+
if (info === null) return { ok: false, reason: "gh failed" };
|
|
504
|
+
if (info.count !== 1) return { ok: false, count: info.count, reason: `${info.count} merged pull requests` };
|
|
505
|
+
const beyond = await commitsBeyondMergedHead(branch, info.headRefOid, { execImpl, repoRoot: repo });
|
|
506
|
+
if (beyond !== 0) return { ok: false, count: 1, reason: "commits beyond the merged pull request" };
|
|
507
|
+
return { ok: true, prNumber: info.prNumber };
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** True when a remote of the copy at `path` is a folder on this disk at or under `dir`. */
|
|
511
|
+
async function remoteIsUnder(path, remote, dir, execImpl) {
|
|
512
|
+
const url = (await git(["-C", path, "remote", "get-url", remote], execImpl)).trim();
|
|
513
|
+
// A host (`scheme://` or `host:path`) is somewhere else.
|
|
514
|
+
if (!url.startsWith("file://") && /^[^/]+:/.test(url)) return false;
|
|
515
|
+
const real = realpathSync(url.startsWith("file://") ? fileURLToPath(url) : resolve(path, url));
|
|
516
|
+
return real === dir || real.startsWith(`${dir}/`);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/**
|
|
520
|
+
* Commits on `revs` that no branch of any live remote holds, asked of the
|
|
521
|
+
* remotes themselves (`git ls-remote`), never the local copy of them; null when
|
|
522
|
+
* any remote could not be read. A remote under `doomed`, a folder about to be
|
|
523
|
+
* removed, holds nothing. No remote at all means every commit is missing.
|
|
524
|
+
*/
|
|
525
|
+
export async function commitsMissingFromLiveRemote(path, execImpl, { revs = ["HEAD"], doomed = null } = {}) {
|
|
526
|
+
try {
|
|
527
|
+
const remotes = (await git(["-C", path, "remote"], execImpl)).split("\n").filter(Boolean);
|
|
528
|
+
const shas = [];
|
|
529
|
+
for (const r of remotes) {
|
|
530
|
+
if (doomed && (await remoteIsUnder(path, r, doomed, execImpl))) continue;
|
|
531
|
+
for (const line of (await git(["-C", path, "ls-remote", "--heads", r], execImpl)).split("\n")) {
|
|
532
|
+
const sha = line.split(/\s/)[0];
|
|
533
|
+
if (/^[0-9a-f]{40,64}$/.test(sha)) shas.push(sha);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
// A live tip this copy never fetched cannot hold its commits: --ignore-missing drops it.
|
|
537
|
+
const n = Number.parseInt(await git(["-C", path, "rev-list", "--ignore-missing", "--count", ...revs, "--not", ...shas], execImpl), 10);
|
|
538
|
+
return Number.isInteger(n) && n >= 0 ? n : null;
|
|
539
|
+
} catch {
|
|
540
|
+
return null;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/**
|
|
545
|
+
* `{ qualify, reason }` for one listed worktree of a resolved repository,
|
|
546
|
+
* every keep check of the rule first, then the three ways it may go. `look` is
|
|
547
|
+
* one fresh lookAround(); `listed` the registry's path keys.
|
|
548
|
+
*/
|
|
549
|
+
export async function evaluateRepoCopy(rec, { repo, listed, look, gh, execImpl }) {
|
|
550
|
+
let real;
|
|
551
|
+
try {
|
|
552
|
+
real = realpathSync(rec.path);
|
|
553
|
+
} catch {
|
|
554
|
+
return { qualify: false, reason: "path unresolvable" };
|
|
555
|
+
}
|
|
556
|
+
if (real === repo.realRepo || dirname(real) !== repo.realWtRoot) return { qualify: false, reason: "not a session copy" };
|
|
557
|
+
const keys = pathKeys(rec.path);
|
|
558
|
+
if (keys.some((k) => listed.has(k))) return { qualify: false, reason: "the app's registry names it" };
|
|
559
|
+
if (!Array.isArray(look.sessions)) return { qualify: false, reason: "app session records unreadable" };
|
|
560
|
+
const owners = look.sessions.filter((s) => s.paths.some((p) => pathKeys(p).some((k) => keys.includes(k))));
|
|
561
|
+
if (owners.some((s) => !s.archived)) return { qualify: false, reason: "an unarchived app session names it" };
|
|
562
|
+
if (rec.locked) return { qualify: false, reason: "locked" };
|
|
563
|
+
if (rec.prunable) return { qualify: false, reason: "registration only" };
|
|
564
|
+
const used = inUse(rec.path, look);
|
|
565
|
+
if (used) return { qualify: false, reason: used };
|
|
566
|
+
if (rec.detached || !rec.branch) return { qualify: false, reason: "detached HEAD" };
|
|
567
|
+
if (repo.protectedBranches.has(rec.branch)) return { qualify: false, reason: "default branch" };
|
|
568
|
+
const kept = (await filesThatKeep(rec.path, execImpl)) ?? nestedRepoOrLinkOut(rec.path);
|
|
569
|
+
if (kept) return { qualify: false, reason: kept };
|
|
570
|
+
if (!gh) return { qualify: false, reason: "gh unavailable" };
|
|
571
|
+
const open = await openPrCount(rec.branch, { execGh: (_bin, args) => execImpl(gh, args, { cwd: repo.realRepo, timeout: 60_000 }) });
|
|
572
|
+
if (open === null) return { qualify: false, reason: "gh failed" };
|
|
573
|
+
if (open > 0) return { qualify: false, reason: "an open pull request" };
|
|
574
|
+
const merged = await mergedCarriesAll(rec.branch, { repo: repo.realRepo, gh, execImpl });
|
|
575
|
+
if (merged.ok) return { qualify: true, reason: `merged in pull request ${merged.prNumber}` };
|
|
576
|
+
if (merged.reason === "gh failed") return { qualify: false, reason: "gh failed" };
|
|
577
|
+
if (owners.length) {
|
|
578
|
+
return (await commitsMissingFromLiveRemote(rec.path, execImpl)) === 0
|
|
579
|
+
? { qualify: true, reason: "its session is archived and the live remote has every commit" }
|
|
580
|
+
: { qualify: false, reason: "its session is archived, but the live remote lacks commits or could not be read" };
|
|
581
|
+
}
|
|
582
|
+
if (merged.count !== 0) return { qualify: false, reason: merged.reason };
|
|
583
|
+
if ((await commitsMissingFromLiveRemote(rec.path, execImpl)) !== 0) return { qualify: false, reason: "no merged pull request, and the live remote lacks commits or could not be read" };
|
|
584
|
+
if (!look.lowSpace) return { qualify: false, reason: "no merged pull request, and space is not low" };
|
|
585
|
+
return { qualify: true, reason: "pushed, and space is low" };
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/** Remove one proven copy with `git worktree remove` (never forced, never its branch); drop it from the repo's records. */
|
|
589
|
+
async function removeRepoCopy(rec, repo, execImpl) {
|
|
590
|
+
if (dirname(realpathSync(rec.path)) !== repo.realWtRoot) throw new Error("escapes its root");
|
|
591
|
+
await git(["-C", repo.realRepo, "worktree", "remove", rec.path], execImpl);
|
|
592
|
+
// Gone now, so its scratch folder can go in this same run.
|
|
593
|
+
repo.records = repo.records.filter((r) => r !== rec);
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/**
|
|
597
|
+
* Every copy of one repository through evaluateRepoCopy; a proven copy is
|
|
598
|
+
* checked again from scratch (registry, git's own list, a fresh look, gh)
|
|
599
|
+
* just before its removal.
|
|
600
|
+
*/
|
|
601
|
+
async function sweepRepo(repo, out, { registryPath, listed, look, probe, apply, gh, home, execImpl }) {
|
|
602
|
+
for (const rec of repo.records) {
|
|
603
|
+
const verdict = await evaluateRepoCopy(rec, { repo, listed, look, gh, execImpl });
|
|
604
|
+
if (!verdict.qualify) {
|
|
605
|
+
if (verdict.reason !== "not a session copy") out.kept.push({ path: rec.path, reason: verdict.reason, repo: repo.realRepo });
|
|
606
|
+
continue;
|
|
607
|
+
}
|
|
608
|
+
try {
|
|
609
|
+
const bytes = await duBytes(rec.path, { execImpl });
|
|
610
|
+
if (apply) {
|
|
611
|
+
const check = async () => {
|
|
612
|
+
const fresh = await resolveRepo(repo.realRepo, { home, execImpl });
|
|
613
|
+
const again = fresh?.records.find((r) => r.path === rec.path);
|
|
614
|
+
const nowListed = registryListed(registryPath);
|
|
615
|
+
if (!again || !nowListed) return false;
|
|
616
|
+
return (await evaluateRepoCopy(again, { repo: fresh, listed: nowListed, look: await probe(), gh, execImpl })).qualify;
|
|
617
|
+
};
|
|
618
|
+
if (!(await stillGoes({ check }))) throw new Error(RECHECK_REASON);
|
|
619
|
+
await removeRepoCopy(rec, repo, execImpl);
|
|
620
|
+
}
|
|
621
|
+
out.removed.push({ path: rec.path, bytes, branch: rec.branch, repo: repo.realRepo, reason: verdict.reason });
|
|
622
|
+
out.bytes += bytes;
|
|
623
|
+
} catch (e) {
|
|
624
|
+
out.kept.push({ path: rec.path, reason: e.message, repo: repo.realRepo });
|
|
625
|
+
if (e.message !== RECHECK_REASON) out.errors += 1;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* The worktree rule for the repositories the registry names. Off entirely
|
|
632
|
+
* unless the registry reads with schemaVersion 2. Returns the resolved repos
|
|
633
|
+
* and the listed paths so the repoRoots and scratch rules can use them.
|
|
634
|
+
*/
|
|
635
|
+
export async function sweepRepoCopies({ registryPath = CLAUDE_WORKTREE_REGISTRY, look, probe, apply = false, gh = findGh(), home = homedir(), execImpl = execFileP }) {
|
|
636
|
+
const out = { removed: [], kept: [], errors: 0, bytes: 0, skipped: null, repos: [], listedPaths: [], registryOk: false };
|
|
637
|
+
const reg = readWorktreeRegistry(registryPath);
|
|
638
|
+
if (!reg.ok) {
|
|
639
|
+
out.skipped = reg.reason;
|
|
640
|
+
return out;
|
|
641
|
+
}
|
|
642
|
+
out.registryOk = true;
|
|
643
|
+
if (!gh) out.skipped = "gh unavailable";
|
|
644
|
+
const listed = new Set(reg.entries.flatMap((e) => (typeof e.path === "string" ? pathKeys(e.path) : [])));
|
|
645
|
+
out.listedPaths = reg.entries.map((e) => e.path).filter((p) => typeof p === "string");
|
|
646
|
+
const baseRepos = [...new Set(reg.entries.map((e) => e.baseRepo).filter((r) => typeof r === "string"))];
|
|
647
|
+
for (const baseRepo of baseRepos) {
|
|
648
|
+
const repo = await resolveRepo(baseRepo, { home, execImpl });
|
|
649
|
+
if (!repo) continue;
|
|
650
|
+
out.repos.push(repo);
|
|
651
|
+
await sweepRepo(repo, out, { registryPath, listed, look, probe, apply, gh, home, execImpl });
|
|
652
|
+
}
|
|
653
|
+
if (!out.skipped && out.kept.some((k) => k.reason === "gh failed")) out.skipped = "gh failed for some copies";
|
|
654
|
+
return out;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// ── repoRoots ───────────────────────────────────────────────────────────────
|
|
658
|
+
|
|
659
|
+
/**
|
|
660
|
+
* Git repositories (a `.git` directory, never a worktree's `.git` file) up to
|
|
661
|
+
* two levels under each folder of `repoRoots`. A root that is missing or a
|
|
662
|
+
* link is refused by name.
|
|
663
|
+
*/
|
|
664
|
+
export function findCodeRepos(repoRoots = DEFAULTS.repoRoots) {
|
|
665
|
+
const found = [];
|
|
666
|
+
const refused = [];
|
|
667
|
+
const walk = (dir, depth) => {
|
|
668
|
+
let ents;
|
|
669
|
+
try {
|
|
670
|
+
ents = readdirSync(dir, { withFileTypes: true });
|
|
671
|
+
} catch {
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
for (const ent of ents) {
|
|
675
|
+
if (!ent.isDirectory() || ent.name.startsWith(".") || ent.name === "node_modules") continue;
|
|
676
|
+
const p = join(dir, ent.name);
|
|
677
|
+
let isRepo = false;
|
|
678
|
+
try {
|
|
679
|
+
isRepo = lstatSync(join(p, ".git")).isDirectory();
|
|
680
|
+
} catch {
|
|
681
|
+
// not a repository
|
|
682
|
+
}
|
|
683
|
+
if (isRepo) found.push(p);
|
|
684
|
+
else if (depth < 2) walk(p, depth + 1);
|
|
685
|
+
}
|
|
686
|
+
};
|
|
687
|
+
for (const root of repoRoots) {
|
|
688
|
+
let st;
|
|
689
|
+
try {
|
|
690
|
+
st = lstatSync(root);
|
|
691
|
+
} catch {
|
|
692
|
+
refused.push(`${root} (missing)`);
|
|
693
|
+
continue;
|
|
694
|
+
}
|
|
695
|
+
if (st.isSymbolicLink()) refused.push(`${root} (a link)`);
|
|
696
|
+
else if (!st.isDirectory()) refused.push(`${root} (not a folder)`);
|
|
697
|
+
else walk(root, 1);
|
|
698
|
+
}
|
|
699
|
+
return { found, refused };
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
/**
|
|
703
|
+
* The worktree rule for every repository under the settings' `repoRoots`,
|
|
704
|
+
* with exactly the checks of the registry rule. A repository the registry
|
|
705
|
+
* rule already visited is not visited twice. Off when the registry cannot be
|
|
706
|
+
* read (it cannot tell which copies are leased).
|
|
707
|
+
*/
|
|
708
|
+
export async function sweepCodeFolder({ repoRoots = DEFAULTS.repoRoots, registryPath = CLAUDE_WORKTREE_REGISTRY, registryOk, visited = [], look, probe, apply = false, gh = findGh(), home = homedir(), execImpl = execFileP }) {
|
|
709
|
+
const out = { removed: [], kept: [], errors: 0, bytes: 0, skipped: null, repos: [], refused: [] };
|
|
710
|
+
if (!repoRoots.length) return out;
|
|
711
|
+
if (!registryOk) {
|
|
712
|
+
out.skipped = "no readable app worktree registry";
|
|
713
|
+
return out;
|
|
714
|
+
}
|
|
715
|
+
const { found, refused } = findCodeRepos(repoRoots);
|
|
716
|
+
out.refused = refused;
|
|
717
|
+
if (refused.length) out.skipped = `refused ${refused.join(", ")}`;
|
|
718
|
+
const listed = registryListed(registryPath) ?? new Set();
|
|
719
|
+
const seen = new Set(visited);
|
|
720
|
+
for (const repoPath of found) {
|
|
721
|
+
const repo = await resolveRepo(repoPath, { home, execImpl });
|
|
722
|
+
if (!repo || seen.has(repo.realRepo)) continue;
|
|
723
|
+
seen.add(repo.realRepo);
|
|
724
|
+
out.repos.push(repo);
|
|
725
|
+
await sweepRepo(repo, out, { registryPath, listed, look, probe, apply, gh, home, execImpl });
|
|
726
|
+
}
|
|
727
|
+
return out;
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/** The `limit` largest folders directly under `dir`, from one `du` pass (partial output kept on timeout). */
|
|
731
|
+
export async function largestFolders(dir, { execImpl = execFileP, limit = 3 } = {}) {
|
|
732
|
+
let stdout = "";
|
|
733
|
+
try {
|
|
734
|
+
({ stdout } = await execImpl("/usr/bin/du", ["-k", "-d", "1", dir], { timeout: 120_000, maxBuffer: 16 * 1024 * 1024 }));
|
|
735
|
+
} catch (e) {
|
|
736
|
+
stdout = e?.stdout ?? "";
|
|
737
|
+
}
|
|
738
|
+
const root = dir.replace(/\/+$/, "");
|
|
739
|
+
return String(stdout)
|
|
740
|
+
.split("\n")
|
|
741
|
+
.map((l) => l.match(/^(\d+)\s+(.+)$/))
|
|
742
|
+
.filter((m) => m && m[2].replace(/\/+$/, "") !== root)
|
|
743
|
+
.map((m) => ({ path: m[2], bytes: Number(m[1]) * 1024 }))
|
|
744
|
+
.sort((a, b) => b.bytes - a.bytes)
|
|
745
|
+
.slice(0, limit);
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// ── scratch ─────────────────────────────────────────────────────────────────
|
|
749
|
+
|
|
750
|
+
/** The folder name Claude derives from a working directory. */
|
|
751
|
+
export const claudeScratchName = (p) => String(p).replace(/[^a-zA-Z0-9]/g, "-");
|
|
752
|
+
|
|
753
|
+
/** Every git copy at or under `dir` (a folder holding `.git`), never following a link. */
|
|
754
|
+
function gitCopiesIn(dir) {
|
|
755
|
+
const out = [];
|
|
756
|
+
const stack = [dir];
|
|
757
|
+
while (stack.length) {
|
|
758
|
+
const cur = stack.pop();
|
|
759
|
+
for (const ent of readdirSync(cur, { withFileTypes: true })) {
|
|
760
|
+
if (ent.name === ".git") out.push(cur);
|
|
761
|
+
else if (ent.isDirectory()) stack.push(join(cur, ent.name));
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
return out;
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/** The app session records that name the copy a scratch folder belongs to. */
|
|
768
|
+
const sessionsNaming = (look, name) => look.sessions.filter((s) => s.paths.some((p) => claudeScratchName(p).toLowerCase() === name));
|
|
769
|
+
|
|
770
|
+
/** Why one scratch folder stays, or null when it may go. */
|
|
771
|
+
async function scratchKeeps(path, name, look, execImpl) {
|
|
772
|
+
if (!Array.isArray(look.sessions)) return "app session records unreadable";
|
|
773
|
+
if (!look.history) return "Claude history unreadable";
|
|
774
|
+
const named = sessionsNaming(look, name);
|
|
775
|
+
if (named.some((s) => !s.archived)) return "an unarchived app session names it";
|
|
776
|
+
if (!named.length && look.history.has(name)) return "its session can still resume";
|
|
777
|
+
const used = inUse(path, look);
|
|
778
|
+
if (used) return used;
|
|
779
|
+
for (const copy of gitCopiesIn(path)) {
|
|
780
|
+
const files = await filesThatKeep(copy, execImpl);
|
|
781
|
+
if (files) return files === DIRTY_REASON ? "a git copy inside has a local change" : `a git copy inside has ${files}`;
|
|
782
|
+
// Every branch and the stash go with the folder, not only HEAD.
|
|
783
|
+
if ((await commitsMissingFromLiveRemote(copy, execImpl, { revs: ["--all"], doomed: dirname(path) })) !== 0) return "a git copy inside has commits its live remote lacks";
|
|
784
|
+
}
|
|
785
|
+
return null;
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
/**
|
|
789
|
+
* The scratch rule. A folder is a candidate when its name is a session-copy
|
|
790
|
+
* path of one of `repos` (forwarded through claudeScratchName) and no existing
|
|
791
|
+
* or registered copy forwards to it or to a parent of it; scratchKeeps then
|
|
792
|
+
* decides, and again just before the delete.
|
|
793
|
+
*/
|
|
794
|
+
export async function sweepScratch({ scratchRoot = `/private/tmp/claude-${process.getuid()}`, repos, listedPaths = [], look, probe, apply = false, execImpl = execFileP }) {
|
|
795
|
+
const out = { removed: [], kept: [], errors: 0, bytes: 0, skipped: null };
|
|
796
|
+
let realRoot;
|
|
797
|
+
try {
|
|
798
|
+
realRoot = realpathSync(scratchRoot);
|
|
799
|
+
} catch {
|
|
800
|
+
out.skipped = "no scratch folder";
|
|
801
|
+
return out;
|
|
802
|
+
}
|
|
803
|
+
const live = new Set(listedPaths.map((p) => claudeScratchName(p).toLowerCase()));
|
|
804
|
+
const prefixes = [];
|
|
805
|
+
for (const repo of repos) {
|
|
806
|
+
prefixes.push(`${claudeScratchName(repo.realWtRoot)}-`.toLowerCase());
|
|
807
|
+
// Session copies only: the main checkout's own name prefixes every one.
|
|
808
|
+
for (const r of repo.records) if (r.path !== repo.realRepo) live.add(claudeScratchName(r.path).toLowerCase());
|
|
809
|
+
try {
|
|
810
|
+
for (const n of readdirSync(repo.realWtRoot)) live.add(claudeScratchName(join(repo.realWtRoot, n)).toLowerCase());
|
|
811
|
+
} catch {
|
|
812
|
+
// unreadable — no copy here can be proven gone
|
|
813
|
+
return { ...out, skipped: "session-copy folder unreadable" };
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
for (const ent of readdirSync(realRoot, { withFileTypes: true })) {
|
|
817
|
+
const name = ent.name.toLowerCase();
|
|
818
|
+
const prefix = prefixes.find((p) => name.startsWith(p) && name.length > p.length);
|
|
819
|
+
if (!prefix) continue;
|
|
820
|
+
if ([...live].some((l) => name === l || name.startsWith(`${l}-`))) continue;
|
|
821
|
+
const path = join(realRoot, ent.name);
|
|
822
|
+
try {
|
|
823
|
+
if (!ent.isDirectory()) throw new Error("not a plain directory");
|
|
824
|
+
const why = await scratchKeeps(path, name, look, execImpl);
|
|
825
|
+
if (why) throw new Error(why);
|
|
826
|
+
const bytes = await duBytes(path, { execImpl });
|
|
827
|
+
if (apply) {
|
|
828
|
+
if (!(await stillGoes({ check: async () => (await scratchKeeps(path, name, await probe(), execImpl)) === null }))) throw new Error(RECHECK_REASON);
|
|
829
|
+
await removeDirectChild(path, realRoot);
|
|
830
|
+
}
|
|
831
|
+
const reason = sessionsNaming(look, name).length ? "its worktree is gone, its app session is archived, and nothing uses it" : "its worktree and its Claude history are gone, and nothing uses it";
|
|
832
|
+
out.removed.push({ path, bytes, reason });
|
|
833
|
+
out.bytes += bytes;
|
|
834
|
+
} catch (e) {
|
|
835
|
+
out.kept.push({ path, reason: e.message });
|
|
836
|
+
if (e.code) out.errors += 1;
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
return out;
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
// ── one run ─────────────────────────────────────────────────────────────────
|
|
843
|
+
|
|
844
|
+
// A rule a run was not asked for (--only): nothing removed, nothing listed.
|
|
845
|
+
const notInOnly = (extra) => ({ removed: [], kept: [], errors: 0, bytes: 0, skipped: "not in --only", ...extra });
|
|
846
|
+
|
|
847
|
+
/**
|
|
848
|
+
* Every rule once (or the rules of one class, `only`; see CLASSES), with free
|
|
849
|
+
* space measured on the data volume before and after. It deletes only when
|
|
850
|
+
* `apply` is asked for and the settings say `preview: false`; otherwise it
|
|
851
|
+
* reports what it would remove. The repo rules are always read, never changed
|
|
852
|
+
* outside their class, because the other rules name what is gone from them.
|
|
853
|
+
*/
|
|
854
|
+
export async function runLeftoversCleanup({ apply = false, only = null, limit = Number.POSITIVE_INFINITY, now = Date.now(), volume = DATA_VOLUME, deps = {} } = {}) {
|
|
855
|
+
const execImpl = deps.execImpl ?? execFileP;
|
|
856
|
+
const { settings, problems } = deps.settings ? { settings: { ...DEFAULTS, ...deps.settings }, problems: [] } : readSettings(deps.settingsPath);
|
|
857
|
+
const deletes = apply && settings.preview === false;
|
|
858
|
+
const allowed = only === null ? null : new Set(CLASSES[only]);
|
|
859
|
+
const want = (key) => allowed === null || allowed.has(key);
|
|
860
|
+
const statfsImpl = deps.statfsImpl ?? statfsSync;
|
|
861
|
+
const probe = () => lookAround({ execImpl, sessionsDir: deps.sessionsDir, historyDir: deps.historyDir, volume, statfsImpl, lowMarkPct: settings.lowMarkPct });
|
|
862
|
+
const before = freeBytes(volume, { statfsImpl });
|
|
863
|
+
const look = await probe();
|
|
864
|
+
const gh = deps.gh === undefined ? findGh() : deps.gh;
|
|
865
|
+
const common = { look, probe, gh, home: deps.home, execImpl };
|
|
866
|
+
const chrome = want("chrome") ? await sweepChromeCopies({ roots: deps.chromeRoots ?? chromeCopyRoots(), look, probe, apply: deletes, rootRe: deps.chromeRootRe, execImpl }) : notInOnly();
|
|
867
|
+
const repoScan = await sweepRepoCopies({ registryPath: deps.registryPath, ...common, apply: deletes && want("repos") });
|
|
868
|
+
const codeScan = await sweepCodeFolder({ repoRoots: settings.repoRoots, registryPath: deps.registryPath, registryOk: repoScan.registryOk, visited: repoScan.repos.map((r) => r.realRepo), ...common, apply: deletes && want("codeFolder") });
|
|
869
|
+
const repos = want("repos") ? repoScan : notInOnly({ repos: repoScan.repos, listedPaths: repoScan.listedPaths, registryOk: repoScan.registryOk });
|
|
870
|
+
const codeFolder = want("codeFolder") ? codeScan : notInOnly({ repos: codeScan.repos });
|
|
871
|
+
const scratch = want("scratch") ? await sweepScratch({ scratchRoot: deps.scratchRoot, repos: [...repos.repos, ...codeFolder.repos], listedPaths: repos.listedPaths, look, probe, apply: deletes, execImpl }) : notInOnly();
|
|
872
|
+
const visited = [...new Map([...repos.repos, ...codeFolder.repos].map((r) => [r.realRepo, r])).values()];
|
|
873
|
+
const { cwds, openPaths, lowSpace } = look;
|
|
874
|
+
const records = want("records") ? await pruneWorktreeRecords({ repos: visited, apply: deletes, execImpl }) : notInOnly();
|
|
875
|
+
const playwright = want("playwright") ? await sweepPlaywright({ root: deps.playwrightRoot === undefined ? PLAYWRIGHT_ROOT : deps.playwrightRoot, repos: visited, openPaths, apply: deletes, execImpl }) : notInOnly();
|
|
876
|
+
const rebuild = want("rebuild") ? await sweepRebuildables({ repos: visited, listedPaths: repos.listedPaths, cwds, openPaths, lowSpace, apply: deletes, execImpl }) : notInOnly();
|
|
877
|
+
const tests = want("tests") ? await sweepTestFolders({ dirs: settings.testDirs, openPaths, apply: deletes, limit, alive: deps.alive, execImpl }) : notInOnly();
|
|
878
|
+
const caches = want("caches") ? await sweepModuleCaches({ dirs: settings.moduleCacheDirs, repos: visited, cwds, openPaths, apply: deletes, execImpl }) : notInOnly();
|
|
879
|
+
const uv = want("uv") ? await pruneUvCache({ uvBin: deps.uvBin === undefined ? findUv() : deps.uvBin, apply: deletes, execImpl }) : notInOnly();
|
|
880
|
+
// Last: its pauses must not delay another rule. Nothing listed asks for no folder.
|
|
881
|
+
const temp = want("temp") ? await sweepTempEntries({ root: settings.tempPrefixes.length ? (deps.tempRoot ?? userTempDir()) : null, rootRe: deps.tempRootRe, settings, apply: deletes, now, alive: deps.alive, sleep: deps.sleep, execImpl }) : notInOnly();
|
|
882
|
+
const diskAfter = diskSpace(volume, { statfsImpl });
|
|
883
|
+
// The size scan runs here, in the detached apply run, and only when space is low.
|
|
884
|
+
const largest = isLowSpace(diskAfter, settings.lowMarkPct) && settings.repoRoots.length ? (await Promise.all(settings.repoRoots.map((r) => largestFolders(r, { execImpl })))).flat().sort((a, b) => b.bytes - a.bytes).slice(0, 3) : [];
|
|
885
|
+
const rules = { chrome, repos, codeFolder, scratch, rebuild, tests, caches, uv, playwright, records, temp };
|
|
886
|
+
return {
|
|
887
|
+
at: new Date(now).toISOString(),
|
|
888
|
+
apply: deletes,
|
|
889
|
+
preview: settings.preview,
|
|
890
|
+
settingsProblems: problems,
|
|
891
|
+
...rules,
|
|
892
|
+
duBytes: CLEANUP_RULES.reduce((n, { key }) => n + rules[key].bytes, 0),
|
|
893
|
+
dfDeltaBytes: before === null || diskAfter.freeBytes === null ? null : diskAfter.freeBytes - before,
|
|
894
|
+
freeBytesAfter: diskAfter.freeBytes,
|
|
895
|
+
disk: diskAfter,
|
|
896
|
+
largest,
|
|
897
|
+
};
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
/**
|
|
901
|
+
* Removed and kept copies per repository, both repo rules together. A copy the
|
|
902
|
+
* first rule kept and the second removed counts once, as removed.
|
|
903
|
+
*/
|
|
904
|
+
function copiesPerRepo(r) {
|
|
905
|
+
const byPath = new Map();
|
|
906
|
+
for (const rule of [r.repos, r.codeFolder]) {
|
|
907
|
+
for (const k of rule.kept) byPath.set(k.path, { ...k, removed: false });
|
|
908
|
+
for (const x of rule.removed) byPath.set(x.path, { ...x, removed: true });
|
|
909
|
+
}
|
|
910
|
+
const perRepo = new Map();
|
|
911
|
+
for (const c of byPath.values()) {
|
|
912
|
+
const name = basename(c.repo);
|
|
913
|
+
const row = perRepo.get(name) ?? { removed: 0, kept: 0, dirty: [] };
|
|
914
|
+
if (c.removed) row.removed += 1;
|
|
915
|
+
else row.kept += 1;
|
|
916
|
+
if (!c.removed && c.reason === DIRTY_REASON) row.dirty.push(basename(c.path));
|
|
917
|
+
perRepo.set(name, row);
|
|
918
|
+
}
|
|
919
|
+
return [...perRepo].sort(([a], [b]) => a.localeCompare(b));
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
/** The one line the session-start hook prints for a run. */
|
|
923
|
+
export function summaryLine(r) {
|
|
924
|
+
const verb = r.apply ? "removed" : "would remove";
|
|
925
|
+
const count = (n, what, bytes) => `${n} ${what}${bytes === undefined ? "" : ` (${formatGb(bytes)})`}`;
|
|
926
|
+
const both = [r.repos, r.codeFolder];
|
|
927
|
+
const parts = [
|
|
928
|
+
count(r.chrome.removed.length, "Chrome copies", r.chrome.bytes),
|
|
929
|
+
count(both.reduce((n, x) => n + x.removed.length, 0), "repo copies", both.reduce((n, x) => n + x.bytes, 0)),
|
|
930
|
+
count(r.scratch.removed.length, "scratch folders", r.scratch.bytes),
|
|
931
|
+
count(r.rebuild.removed.length, "rebuildable folders", r.rebuild.bytes),
|
|
932
|
+
count(r.tests.removed.length, "test folders", r.tests.bytes),
|
|
933
|
+
count(r.caches.removed.length, "module caches", r.caches.bytes),
|
|
934
|
+
count(r.playwright.removed.length, "old Playwright builds", r.playwright.bytes),
|
|
935
|
+
count(r.records.removed.length, "stale worktree records"),
|
|
936
|
+
];
|
|
937
|
+
const uvState = r.apply && r.uv.removed.length ? `pruned, ${formatGb(r.uv.bytes)} measured` : !r.apply && r.uv.wouldPrune ? "would be pruned" : "not pruned";
|
|
938
|
+
let line = `Claude leftovers cleanup ${r.at}: ${verb} ${parts.join(", ")}, uv cache ${uvState}; up to ${formatGb(r.duBytes)} listed by size (copies can share disk space, so a delete can free less)`;
|
|
939
|
+
if (r.apply && r.dfDeltaBytes !== null) line += `, ${formatGb(r.dfDeltaBytes)} of free space gained (measured)`;
|
|
940
|
+
if (r.freeBytesAfter !== null) line += `, ${formatGb(r.freeBytesAfter)} free now`;
|
|
941
|
+
const perRepo = copiesPerRepo(r).map(([name, c]) => `${name} ${c.removed} ${verb}, ${c.kept} kept${c.dirty.length ? ` (dirty: ${c.dirty.join(", ")})` : ""}`);
|
|
942
|
+
if (perRepo.length) line += `. Worktrees: ${perRepo.join("; ")}`;
|
|
943
|
+
line += tempReport(r.temp, verb);
|
|
944
|
+
const skipped = CLEANUP_RULES.map(({ key, label }) => [label, r[key].skipped]).filter(([, why]) => why);
|
|
945
|
+
if (skipped.length) line += `. Skipped: ${skipped.map(([what, why]) => `${what} (${why})`).join(", ")}`;
|
|
946
|
+
if (r.preview !== false) line += ". Nothing was deleted: preview is on until settings.json sets preview to false";
|
|
947
|
+
if (r.settingsProblems?.length) line += `. Settings problems: ${r.settingsProblems.join(", ")}`;
|
|
948
|
+
return `${line}.`;
|
|
949
|
+
}
|