ccleanup 1.0.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.
@@ -0,0 +1,412 @@
1
+ import { lstat, open, readdir } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { sanitize } from "../lib/text.js";
5
+ export const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
6
+ const EDGE = 64 * 1024;
7
+ const TITLE_MAX = 200;
8
+ export const CONCURRENCY = 8;
9
+ /**
10
+ * Identifies a session uniquely, even when its id appears in two project folders or two
11
+ * config folders.
12
+ *
13
+ * @param session - Session or entry, read for its config folder, project folder and id
14
+ * @returns "<configDir>/projects/<projectDir>/<id>"
15
+ */
16
+ export function sessionKey(session) {
17
+ return join(session.configDir, "projects", session.projectDir, session.id);
18
+ }
19
+ /**
20
+ * Measures a file or a whole folder without following symlinks.
21
+ *
22
+ * @param path - File or folder
23
+ * @returns Disk usage in bytes (allocated blocks) and newest modification time, or null when the path does not exist
24
+ */
25
+ async function measure(path) {
26
+ let info;
27
+ try {
28
+ info = await lstat(path);
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ const usage = (stat) => (stat.blocks > 0 ? stat.blocks * 512 : stat.size);
34
+ if (!info.isDirectory())
35
+ return { bytes: usage(info), mtime: info.mtimeMs };
36
+ let bytes = usage(info);
37
+ let mtime = info.mtimeMs;
38
+ const stack = [path];
39
+ while (stack.length > 0) {
40
+ const dir = stack.pop();
41
+ let entries;
42
+ try {
43
+ entries = await readdir(dir, { withFileTypes: true });
44
+ }
45
+ catch {
46
+ continue;
47
+ }
48
+ const stats = await Promise.all(entries.map(async (entry) => {
49
+ const full = join(dir, entry.name);
50
+ try {
51
+ return { full, isDir: entry.isDirectory(), stat: await lstat(full) };
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ }));
57
+ for (const item of stats) {
58
+ if (!item)
59
+ continue;
60
+ bytes += usage(item.stat);
61
+ mtime = Math.max(mtime, item.stat.mtimeMs);
62
+ if (item.isDir)
63
+ stack.push(item.full);
64
+ }
65
+ }
66
+ return { bytes, mtime };
67
+ }
68
+ /**
69
+ * Parses the JSON lines of a transcript chunk.
70
+ *
71
+ * @param text - Chunk of a .jsonl file
72
+ * @returns The records that parse; a line cut at a chunk boundary is skipped
73
+ */
74
+ function parseLines(text) {
75
+ const out = [];
76
+ for (const line of text.split("\n")) {
77
+ if (!line.startsWith("{"))
78
+ continue;
79
+ try {
80
+ out.push(JSON.parse(line));
81
+ }
82
+ catch {
83
+ continue;
84
+ }
85
+ }
86
+ return out;
87
+ }
88
+ /**
89
+ * Reads the first and last 64 KB of a transcript.
90
+ *
91
+ * A file of several hundred MB thus costs two small reads.
92
+ *
93
+ * @param file - Transcript path
94
+ * @returns Records of the head and of the tail; both hold the whole file when it is small
95
+ */
96
+ async function readEdges(file) {
97
+ const handle = await open(file, "r");
98
+ try {
99
+ const { size } = await handle.stat();
100
+ const read = async (position, length) => {
101
+ const buffer = Buffer.alloc(length);
102
+ const { bytesRead } = await handle.read(buffer, 0, length, position);
103
+ return buffer.toString("utf8", 0, bytesRead);
104
+ };
105
+ if (size <= EDGE * 2) {
106
+ const all = parseLines(await read(0, size));
107
+ return { head: all, tail: all };
108
+ }
109
+ const headText = await read(0, EDGE);
110
+ const tailText = await read(size - EDGE, EDGE);
111
+ return {
112
+ head: parseLines(headText.slice(0, headText.lastIndexOf("\n"))),
113
+ tail: parseLines(tailText.slice(tailText.indexOf("\n") + 1)),
114
+ };
115
+ }
116
+ finally {
117
+ await handle.close();
118
+ }
119
+ }
120
+ /**
121
+ * Extracts the text a user typed from a transcript record.
122
+ *
123
+ * @param record - Transcript record
124
+ * @returns The prompt text, or undefined for other records, meta records and injected context such as system reminders
125
+ */
126
+ function promptText(record) {
127
+ if (record.type !== "user" || record.isMeta === true)
128
+ return undefined;
129
+ const content = record.message?.content;
130
+ let text;
131
+ if (typeof content === "string") {
132
+ text = content;
133
+ }
134
+ else if (Array.isArray(content)) {
135
+ const part = content.find((item) => typeof item === "object" &&
136
+ item !== null &&
137
+ item.type === "text" &&
138
+ typeof item.text === "string");
139
+ text = part?.text;
140
+ }
141
+ if (!text || text.trimStart().startsWith("<"))
142
+ return undefined;
143
+ return text;
144
+ }
145
+ /**
146
+ * Turns transcript text into a one-line title.
147
+ *
148
+ * @param text - Raw title or prompt
149
+ * @returns Sanitized text on one line, at most 200 characters, empty when missing
150
+ */
151
+ function clean(text) {
152
+ return sanitize(text ?? "")
153
+ .replace(/\s+/g, " ")
154
+ .trim()
155
+ .slice(0, TITLE_MAX);
156
+ }
157
+ /**
158
+ * Short project label for the list.
159
+ *
160
+ * @param cwd - Working directory recorded in the transcript
161
+ * @param projectDir - Encoded project folder name, slashes turned into dashes by Claude Code
162
+ * @returns "~" for the home folder, the two last segments of the cwd, or a guess from the folder name when the cwd is unknown
163
+ */
164
+ export function shortProject(cwd, projectDir) {
165
+ if (!cwd)
166
+ return projectDir.replace(/^-/, "").split("-").slice(-2).join("/");
167
+ if (cwd === homedir())
168
+ return "~";
169
+ return sanitize(cwd.split("/").filter(Boolean).slice(-2).join("/"));
170
+ }
171
+ /**
172
+ * Finds the first value a picker returns over a list of records.
173
+ *
174
+ * @param records - Records to scan
175
+ * @param pick - Returns a value for a matching record, undefined otherwise
176
+ * @param last - Scan from the end, to get the latest value
177
+ * @returns The first value found, or undefined
178
+ */
179
+ function find(records, pick, last = false) {
180
+ const list = last ? [...records].reverse() : records;
181
+ for (const record of list) {
182
+ const value = pick(record);
183
+ if (value !== undefined)
184
+ return value;
185
+ }
186
+ return undefined;
187
+ }
188
+ /**
189
+ * Reads a non-empty string field of a record.
190
+ *
191
+ * @param record - Transcript record
192
+ * @param key - Field name
193
+ * @returns The value, or undefined when it is missing, empty or not a string
194
+ */
195
+ function field(record, key) {
196
+ const value = record[key];
197
+ return typeof value === "string" && value ? value : undefined;
198
+ }
199
+ /**
200
+ * Reads the title, the project and the working directory of a transcript.
201
+ *
202
+ * The title is the latest AI title, else the first prompt, else the last prompt.
203
+ *
204
+ * @param transcript - Path of the .jsonl transcript
205
+ * @param projectDir - Encoded project folder name, the fallback for the project label
206
+ * @returns Title, short project label and cwd; an unreadable transcript gives an empty title
207
+ */
208
+ async function describe(transcript, projectDir) {
209
+ let head = [];
210
+ let tail = [];
211
+ try {
212
+ ({ head, tail } = await readEdges(transcript));
213
+ }
214
+ catch {
215
+ head = [];
216
+ }
217
+ const aiTitle = (r) => (r.type === "ai-title" ? field(r, "aiTitle") : undefined);
218
+ const lastPrompt = (r) => r.type === "last-prompt" ? field(r, "lastPrompt") : undefined;
219
+ const cwdOf = (r) => field(r, "cwd");
220
+ const title = clean(find(tail, aiTitle, true) ??
221
+ find(head, aiTitle, true) ??
222
+ find(head, promptText) ??
223
+ find(tail, lastPrompt, true));
224
+ const found = find(head, cwdOf) ?? find(tail, cwdOf, true);
225
+ const cwd = found === undefined ? undefined : sanitize(found);
226
+ const started = Date.parse(find(head, (r) => field(r, "timestamp")) ?? "");
227
+ const startedAt = Number.isNaN(started) ? undefined : started;
228
+ return { title, project: shortProject(cwd, projectDir), cwd, startedAt };
229
+ }
230
+ /**
231
+ * Finds the sessions of `<configDir>/projects` without measuring them, which is fast.
232
+ *
233
+ * Only entries named after a session UUID count, so anything else in a project folder,
234
+ * such as `memory/`, is never listed and never deleted.
235
+ *
236
+ * @param configDir - Claude config folder
237
+ * @param onDenied - Called with each folder that exists but cannot be read
238
+ * @returns Sessions sorted by project folder then id; none when the folder does not exist
239
+ */
240
+ export async function discover(configDir, onDenied) {
241
+ const root = join(configDir, "projects");
242
+ const denied = (path, error) => {
243
+ const code = error.code;
244
+ if (code === "EACCES" || code === "EPERM")
245
+ onDenied?.(path);
246
+ };
247
+ let projectDirs;
248
+ try {
249
+ projectDirs = await readdir(root);
250
+ }
251
+ catch (error) {
252
+ denied(root, error);
253
+ return [];
254
+ }
255
+ const found = [];
256
+ await Promise.all(projectDirs.map(async (projectDir) => {
257
+ const dir = join(root, projectDir);
258
+ let entries;
259
+ try {
260
+ entries = await readdir(dir, { withFileTypes: true });
261
+ }
262
+ catch (error) {
263
+ denied(dir, error);
264
+ return;
265
+ }
266
+ const ids = new Set();
267
+ for (const entry of entries) {
268
+ const id = entry.name.endsWith(".jsonl") ? entry.name.slice(0, -6) : entry.name;
269
+ const kind = entry.name.endsWith(".jsonl") ? entry.isFile() : entry.isDirectory();
270
+ if (kind && UUID.test(id))
271
+ ids.add(id);
272
+ }
273
+ for (const id of ids) {
274
+ found.push({ id, configDir, projectDir, dir, ownsExtras: true });
275
+ }
276
+ }));
277
+ found.sort((a, b) => a.projectDir.localeCompare(b.projectDir) || a.id.localeCompare(b.id));
278
+ const owners = new Set();
279
+ for (const entry of found) {
280
+ entry.ownsExtras = !owners.has(entry.id);
281
+ owners.add(entry.id);
282
+ }
283
+ return found;
284
+ }
285
+ /**
286
+ * Builds the row shown for a session before it is measured.
287
+ *
288
+ * @param entry - Session found by discover
289
+ * @returns A pending session with no size, no age and a project guessed from the folder name
290
+ */
291
+ export function placeholder(entry) {
292
+ return {
293
+ id: entry.id,
294
+ configDir: entry.configDir,
295
+ projectDir: entry.projectDir,
296
+ project: shortProject(undefined, entry.projectDir),
297
+ title: "",
298
+ bytes: 0,
299
+ mtime: 0,
300
+ recent: false,
301
+ open: false,
302
+ pending: true,
303
+ paths: [],
304
+ parts: [],
305
+ };
306
+ }
307
+ /**
308
+ * Measures one session.
309
+ *
310
+ * It covers the transcript, its folder (tool results, subagents, workflows) and, when
311
+ * the entry owns them, the file history, session environment and debug log.
312
+ *
313
+ * @param entry - Session found by discover
314
+ * @param options - Reference time, recent delay and open sessions
315
+ * @returns The measured session, or null when it vanished since discover
316
+ */
317
+ export async function measureEntry(entry, options) {
318
+ const { now, recentMs } = options;
319
+ const { id, configDir, dir, projectDir } = entry;
320
+ const transcript = join(dir, `${id}.jsonl`);
321
+ const folder = join(dir, id);
322
+ const own = await Promise.all([measure(transcript), measure(folder)]);
323
+ if (!own[0] && !own[1])
324
+ return null;
325
+ const extras = entry.ownsExtras
326
+ ? [
327
+ join(configDir, "file-history", id),
328
+ join(configDir, "session-env", id),
329
+ join(configDir, "debug", `${id}.txt`),
330
+ ]
331
+ : [];
332
+ const extraSizes = await Promise.all(extras.map(measure));
333
+ const paths = [];
334
+ const parts = [];
335
+ let bytes = 0;
336
+ let mtime = 0;
337
+ const ownKinds = ["transcript", "folder"];
338
+ const extraKinds = ["history", "env", "debug"];
339
+ [transcript, folder].forEach((path, i) => {
340
+ const size = own[i];
341
+ if (!size)
342
+ return;
343
+ paths.push(path);
344
+ parts.push({ kind: ownKinds[i], bytes: size.bytes });
345
+ bytes += size.bytes;
346
+ mtime = Math.max(mtime, size.mtime);
347
+ });
348
+ extras.forEach((path, i) => {
349
+ const size = extraSizes[i];
350
+ if (!size)
351
+ return;
352
+ paths.push(path);
353
+ parts.push({ kind: extraKinds[i], bytes: size.bytes });
354
+ bytes += size.bytes;
355
+ });
356
+ const { title, project, cwd, startedAt } = own[0]
357
+ ? await describe(transcript, projectDir)
358
+ : { title: "", project: shortProject(undefined, projectDir) };
359
+ return {
360
+ id,
361
+ configDir,
362
+ projectDir,
363
+ project,
364
+ title,
365
+ bytes,
366
+ mtime,
367
+ startedAt,
368
+ recent: now - mtime < recentMs,
369
+ open: options.open.has(id.toLowerCase()),
370
+ cwd,
371
+ paths,
372
+ parts,
373
+ };
374
+ }
375
+ /**
376
+ * Runs an async task over items with a concurrency limit.
377
+ *
378
+ * @param items - Items to process
379
+ * @param limit - Maximum number of tasks running at once
380
+ * @param task - Work for one item
381
+ * @param onResult - Called as soon as each task settles, in completion order
382
+ * @returns The results in the order of the items
383
+ */
384
+ export async function pool(items, limit, task, onResult) {
385
+ const results = new Array(items.length);
386
+ let next = 0;
387
+ const worker = async () => {
388
+ while (next < items.length) {
389
+ const index = next++;
390
+ const item = items[index];
391
+ const result = await task(item);
392
+ results[index] = result;
393
+ onResult?.(result, item);
394
+ }
395
+ };
396
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
397
+ return results;
398
+ }
399
+ /**
400
+ * Discovers and measures every session of the given config folders.
401
+ *
402
+ * @param configDirs - Claude config folders, from findConfigDirs
403
+ * @param options - Reference time, recent delay and open sessions
404
+ * @param onDenied - Called with each folder that exists but cannot be read
405
+ * @returns The measured sessions, those that vanished meanwhile left out
406
+ */
407
+ export async function scan(configDirs, options, onDenied) {
408
+ const found = await Promise.all(configDirs.map((dir) => discover(dir, onDenied)));
409
+ const entries = found.flat();
410
+ const sessions = await pool(entries, CONCURRENCY, (entry) => measureEntry(entry, options));
411
+ return sessions.filter((session) => session !== null);
412
+ }
@@ -0,0 +1,78 @@
1
+ import { fold } from "../lib/text.js";
2
+ export const SORT_MODES = ["size", "age", "project"];
3
+ /**
4
+ * Tells whether any targeting filter is set.
5
+ *
6
+ * @param filter - Filters as given on the command line
7
+ * @returns True when --older-than or --min-size was given
8
+ */
9
+ export function hasFilter(filter) {
10
+ return filter.olderThan !== undefined || filter.minSize !== undefined;
11
+ }
12
+ /**
13
+ * Tells whether a session passes every given filter.
14
+ *
15
+ * @param session - Measured session; its age comes from its newest file
16
+ * @param filter - Filters to apply; a missing one lets everything through
17
+ * @returns False for an open session, and for a recent one unless the filter includes them
18
+ */
19
+ export function matches(session, filter) {
20
+ if (session.open)
21
+ return false;
22
+ if (!filter.includeRecent && session.recent)
23
+ return false;
24
+ if (filter.olderThan !== undefined && filter.now - session.mtime < filter.olderThan) {
25
+ return false;
26
+ }
27
+ if (filter.minSize !== undefined && session.bytes < filter.minSize)
28
+ return false;
29
+ return true;
30
+ }
31
+ /**
32
+ * Keeps the sessions targeted by the filters.
33
+ *
34
+ * @param sessions - Measured sessions
35
+ * @param filter - Filters to apply
36
+ * @returns The matching sessions, or none at all when no filter is set, so a bare call never targets everything
37
+ */
38
+ export function select(sessions, filter) {
39
+ return hasFilter(filter) ? sessions.filter((session) => matches(session, filter)) : [];
40
+ }
41
+ /**
42
+ * Sorts sessions without changing the given array.
43
+ *
44
+ * @param sessions - Sessions to sort
45
+ * @param mode - Biggest first, oldest first, or project name then oldest first
46
+ * @param reversed - Reverse the order: smallest, newest or last project first
47
+ * @returns A new sorted array
48
+ */
49
+ export function sortSessions(sessions, mode, reversed = false) {
50
+ const sorted = [...sessions];
51
+ switch (mode) {
52
+ case "size":
53
+ sorted.sort((a, b) => b.bytes - a.bytes);
54
+ break;
55
+ case "age":
56
+ sorted.sort((a, b) => a.mtime - b.mtime);
57
+ break;
58
+ case "project":
59
+ sorted.sort((a, b) => a.project.localeCompare(b.project) || a.mtime - b.mtime);
60
+ break;
61
+ }
62
+ return reversed ? sorted.reverse() : sorted;
63
+ }
64
+ /**
65
+ * Tells whether a session matches a search: every word of the query must appear in its
66
+ * project, title, working folder or id, whatever the case and the accents.
67
+ *
68
+ * @param session - Measured session
69
+ * @param query - Words typed after /, possibly empty
70
+ * @returns True for an empty query
71
+ */
72
+ export function searchMatches(session, query) {
73
+ const words = fold(query).split(/\s+/).filter(Boolean);
74
+ if (words.length === 0)
75
+ return true;
76
+ const haystack = fold(`${session.project} ${session.title} ${session.cwd ?? ""} ${session.id}`);
77
+ return words.every((word) => haystack.includes(word));
78
+ }