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,188 @@
1
+ import { readdir, readFile, readlink, stat } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { pool, UUID } from "./scan.js";
4
+ const PROC = "/proc";
5
+ const PROC_CONCURRENCY = 32;
6
+ // A record from another process namespace is trusted while this fresh
7
+ const FOREIGN_MS = 24 * 3_600_000;
8
+ // Start time in /proc/<pid>/stat, after the command name (field 22)
9
+ const START_FIELD = 19;
10
+ // Options of the claude command that name the session it runs
11
+ const SESSION_FLAGS = new Set(["--resume", "-r", "--session-id"]);
12
+ /**
13
+ * Tells whether a process exists.
14
+ *
15
+ * @param pid - Process id, a positive integer
16
+ * @returns True when the process runs, even under another user
17
+ */
18
+ function alive(pid) {
19
+ try {
20
+ process.kill(pid, 0);
21
+ return true;
22
+ }
23
+ catch (error) {
24
+ return error.code === "EPERM";
25
+ }
26
+ }
27
+ /**
28
+ * Start time of a process, as the kernel counts it.
29
+ *
30
+ * @param pid - Process id
31
+ * @returns The start time in clock ticks since boot, or undefined without /proc
32
+ */
33
+ async function processStart(pid) {
34
+ try {
35
+ const stat = await readFile(join(PROC, String(pid), "stat"), "utf8");
36
+ // The command name may hold spaces: count after its parenthesis.
37
+ return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[START_FIELD];
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ }
43
+ /**
44
+ * Process namespace of this program, as Claude Code writes it at the end of `pidDomain`.
45
+ *
46
+ * @returns A value such as `pid:[4026531836]`, or undefined without /proc
47
+ */
48
+ async function ownNamespace() {
49
+ try {
50
+ return await readlink(join(PROC, "self", "ns", "pid"));
51
+ }
52
+ catch {
53
+ return undefined;
54
+ }
55
+ }
56
+ /**
57
+ * Tells whether a record was written by Claude Code lately.
58
+ *
59
+ * @param path - Path of the record
60
+ * @returns True when the file changed less than FOREIGN_MS ago
61
+ */
62
+ async function fresh(path) {
63
+ try {
64
+ return Date.now() - (await stat(path)).mtimeMs < FOREIGN_MS;
65
+ }
66
+ catch {
67
+ return false;
68
+ }
69
+ }
70
+ /**
71
+ * Reads one record that Claude Code keeps for each running instance.
72
+ *
73
+ * @param path - Path of a `sessions/<pid>.json` file
74
+ * @param namespace - Process namespace of this program, when known
75
+ * @returns The session id when its process still runs, else undefined
76
+ */
77
+ async function registeredSession(path, namespace) {
78
+ let record;
79
+ try {
80
+ record = JSON.parse(await readFile(path, "utf8"));
81
+ }
82
+ catch {
83
+ return undefined;
84
+ }
85
+ const { pid, sessionId, procStart, pidDomain } = record;
86
+ if (typeof sessionId !== "string" || !UUID.test(sessionId))
87
+ return undefined;
88
+ // Its process ids mean nothing here: rely on the file date.
89
+ if (namespace && typeof pidDomain === "string" && !pidDomain.endsWith(namespace)) {
90
+ return (await fresh(path)) ? sessionId : undefined;
91
+ }
92
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0)
93
+ return undefined;
94
+ if (!alive(pid))
95
+ return undefined;
96
+ // A reused process id belongs to another program, started at another time.
97
+ if (typeof procStart === "string") {
98
+ const start = await processStart(pid);
99
+ if (start !== undefined && start !== procStart)
100
+ return undefined;
101
+ }
102
+ return sessionId;
103
+ }
104
+ /**
105
+ * Sessions that Claude Code declares running, from `<config>/sessions/<pid>.json`.
106
+ *
107
+ * @param configDir - Claude Code config folder
108
+ * @returns Session ids whose process still runs; none when the folder is missing
109
+ */
110
+ async function registeredSessions(configDir) {
111
+ const dir = join(configDir, "sessions");
112
+ let names;
113
+ try {
114
+ names = await readdir(dir);
115
+ }
116
+ catch {
117
+ return [];
118
+ }
119
+ const files = names.filter((name) => /^\d+\.json$/.test(name));
120
+ const namespace = await ownNamespace();
121
+ const ids = await pool(files, PROC_CONCURRENCY, (name) => registeredSession(join(dir, name), namespace));
122
+ return ids.filter((id) => id !== undefined);
123
+ }
124
+ /**
125
+ * Session ids named on a command line, as `--resume <id>`, `--resume=<id>`, `-r <id>` or
126
+ * `--session-id <id>`.
127
+ *
128
+ * @param args - Arguments of a process
129
+ * @returns The ids found, possibly none
130
+ */
131
+ export function sessionArgs(args) {
132
+ const ids = [];
133
+ args.forEach((arg, i) => {
134
+ const equal = arg.indexOf("=");
135
+ const flag = equal === -1 ? arg : arg.slice(0, equal);
136
+ if (!SESSION_FLAGS.has(flag))
137
+ return;
138
+ const value = equal === -1 ? args[i + 1] : arg.slice(equal + 1);
139
+ if (value !== undefined && UUID.test(value))
140
+ ids.push(value);
141
+ });
142
+ return ids;
143
+ }
144
+ /**
145
+ * Sessions resumed by a running process, from the command lines in /proc.
146
+ *
147
+ * Any process counts, not only claude: a false match only protects a session longer.
148
+ *
149
+ * @returns Session ids found; none off Linux
150
+ */
151
+ async function resumedSessions() {
152
+ if (process.platform !== "linux")
153
+ return [];
154
+ let pids;
155
+ try {
156
+ pids = (await readdir(PROC)).filter((name) => /^\d+$/.test(name));
157
+ }
158
+ catch {
159
+ return [];
160
+ }
161
+ const found = await pool(pids, PROC_CONCURRENCY, async (pid) => {
162
+ try {
163
+ const cmdline = await readFile(join(PROC, pid, "cmdline"), "utf8");
164
+ return sessionArgs(cmdline.split("\0"));
165
+ }
166
+ catch {
167
+ return [];
168
+ }
169
+ });
170
+ return found.flat();
171
+ }
172
+ /**
173
+ * Sessions open right now in a Claude Code instance, so they are never deleted.
174
+ *
175
+ * Two sources are merged: the records Claude Code keeps per running instance, checked
176
+ * against the live processes, and on Linux the session ids passed to running commands.
177
+ * A record from another process namespace counts as open for a day after its last write.
178
+ *
179
+ * @param configDirs - Claude Code config folders, each with its own records
180
+ * @returns Ids of the open sessions, lowercase
181
+ */
182
+ export async function openSessions(configDirs) {
183
+ const [registered, resumed] = await Promise.all([
184
+ Promise.all(configDirs.map(registeredSessions)),
185
+ resumedSessions(),
186
+ ]);
187
+ return new Set([...registered.flat(), ...resumed].map((id) => id.toLowerCase()));
188
+ }
@@ -0,0 +1,189 @@
1
+ import { execFile } from "node:child_process";
2
+ import { mkdir, realpath, rm, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { promisify } from "node:util";
7
+ import { messages } from "../i18n/messages.js";
8
+ import { DAY, formatSize } from "../lib/format.js";
9
+ import { DEFAULT_OLDER_THAN } from "./args.js";
10
+ import { matches } from "./select.js";
11
+ /**
12
+ * Runs a command without a shell and waits for it.
13
+ *
14
+ * @param file - Executable, looked up in PATH
15
+ * @param args - Arguments, passed as is
16
+ * @returns Its stdout and stderr; rejects on a non-zero exit or a missing command
17
+ */
18
+ const run = promisify(execFile);
19
+ const UNIT = "ccleanup-reminder";
20
+ /**
21
+ * Prints what `--check` would clean, and sends a notification when it is above the
22
+ * threshold and `--notify` is set.
23
+ *
24
+ * @param sessions - Measured sessions
25
+ * @param options - Parsed options: filters, notify flag and threshold
26
+ * @param lang - Language of the messages
27
+ * @param now - Reference time of the scan
28
+ */
29
+ export async function check(sessions, options, lang, now) {
30
+ const m = messages(lang);
31
+ const olderThan = options.olderThan ?? DEFAULT_OLDER_THAN;
32
+ const days = Math.round(olderThan / DAY);
33
+ const filter = {
34
+ olderThan,
35
+ minSize: options.minSize,
36
+ includeRecent: options.includeRecent,
37
+ now,
38
+ };
39
+ const targets = sessions.filter((session) => matches(session, filter));
40
+ const bytes = targets.reduce((total, session) => total + session.bytes, 0);
41
+ if (targets.length === 0) {
42
+ console.log(m.checkNothing(days));
43
+ return;
44
+ }
45
+ const size = formatSize(bytes, lang);
46
+ console.log(m.checkLine(targets.length, days, size));
47
+ if (options.notify && bytes >= options.notifyAbove) {
48
+ const sent = await sendNotification(m.notifyTitle, m.notifyBody(targets.length, days, size));
49
+ if (!sent)
50
+ console.error(m.notifyFailed);
51
+ }
52
+ }
53
+ /**
54
+ * Sends a desktop notification.
55
+ *
56
+ * @param title - Notification title
57
+ * @param text - Notification body
58
+ * @returns False when the command is missing or fails; $CCLEANUP_NOTIFY, when set, is run with the text then the title, else notify-send
59
+ */
60
+ export async function sendNotification(title, text) {
61
+ try {
62
+ const custom = process.env.CCLEANUP_NOTIFY;
63
+ if (custom)
64
+ await run("sh", ["-c", `${custom} "$@"`, "ccleanup", text, title]);
65
+ else
66
+ await run("notify-send", ["--app-name=ccleanup", title, text]);
67
+ return true;
68
+ }
69
+ catch {
70
+ return false;
71
+ }
72
+ }
73
+ /**
74
+ * Folder of the systemd user units.
75
+ *
76
+ * @returns $XDG_CONFIG_HOME/systemd/user, ~/.config by default
77
+ */
78
+ function unitDir() {
79
+ const base = process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
80
+ return join(base, "systemd", "user");
81
+ }
82
+ /**
83
+ * Quotes a value for a systemd unit file.
84
+ *
85
+ * @param value - Raw value; backslashes and quotes are escaped, % is doubled so systemd does not expand it
86
+ * @returns The value between double quotes
87
+ */
88
+ function quote(value) {
89
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`;
90
+ }
91
+ /**
92
+ * Writes the text of the reminder service and timer.
93
+ *
94
+ * @param cli - Absolute path of the installed cli.js
95
+ * @param options - Parsed options: period and filter flags to repeat in the service
96
+ * @param lang - Language the notifications keep, whatever the session locale
97
+ * @returns Contents of the .service and .timer files
98
+ */
99
+ function units(cli, options, lang) {
100
+ const environment = [`PATH=${process.env.PATH ?? ""}`, `CCLEANUP_LANG=${lang}`];
101
+ // The service does not inherit the shell: carry the folder variables.
102
+ for (const name of ["CCLEANUP_NOTIFY", "CLAUDE_CONFIG_DIR", "XDG_CONFIG_HOME"]) {
103
+ const value = process.env[name];
104
+ if (value)
105
+ environment.push(`${name}=${value}`);
106
+ }
107
+ const command = [process.execPath, cli, "--check", "--notify", ...options.reminderArgs]
108
+ .map(quote)
109
+ .join(" ");
110
+ const service = [
111
+ "[Unit]",
112
+ "Description=Remind to clean old Claude Code sessions (ccleanup)",
113
+ "",
114
+ "[Service]",
115
+ "Type=oneshot",
116
+ ...environment.map((line) => `Environment=${quote(line)}`),
117
+ `ExecStart=${command}`,
118
+ "",
119
+ ].join("\n");
120
+ const timer = [
121
+ "[Unit]",
122
+ "Description=Periodic ccleanup reminder",
123
+ "",
124
+ "[Timer]",
125
+ `OnCalendar=${options.every}`,
126
+ "Persistent=true",
127
+ "",
128
+ "[Install]",
129
+ "WantedBy=timers.target",
130
+ "",
131
+ ].join("\n");
132
+ return { service, timer };
133
+ }
134
+ /**
135
+ * Installs and enables the systemd user timer that runs `--check --notify`.
136
+ *
137
+ * With `--dry-run`, prints the units and the commands instead of writing anything.
138
+ *
139
+ * @param options - Parsed options: period, filters and dry-run flag
140
+ * @param lang - Language of the messages and of the future notifications
141
+ * @throws Error off Linux, or when ccleanup runs from the temporary npx cache
142
+ */
143
+ export async function installReminder(options, lang) {
144
+ const m = messages(lang);
145
+ if (process.platform !== "linux")
146
+ throw new Error(m.reminderNeedsSystemd);
147
+ const cli = await realpath(fileURLToPath(new URL("../cli.js", import.meta.url)));
148
+ if (cli.includes("/_npx/"))
149
+ throw new Error(m.reminderNeedsGlobal);
150
+ const { service, timer } = units(cli, options, lang);
151
+ const servicePath = join(unitDir(), `${UNIT}.service`);
152
+ const timerPath = join(unitDir(), `${UNIT}.timer`);
153
+ if (options.dryRun) {
154
+ console.log(`# ${servicePath}\n${service}`);
155
+ console.log(`# ${timerPath}\n${timer}`);
156
+ console.log(`# systemctl --user daemon-reload && systemctl --user enable --now ${UNIT}.timer`);
157
+ console.log(m.reminderDry);
158
+ return;
159
+ }
160
+ await mkdir(unitDir(), { recursive: true });
161
+ await writeFile(servicePath, service);
162
+ await writeFile(timerPath, timer);
163
+ await run("systemctl", ["--user", "daemon-reload"]);
164
+ await run("systemctl", ["--user", "enable", "--now", `${UNIT}.timer`]);
165
+ console.log(m.reminderInstalled(options.every));
166
+ }
167
+ /**
168
+ * Disables the reminder timer and removes its unit files.
169
+ *
170
+ * @param options - Parsed options; with --dry-run, only prints what would happen
171
+ * @param lang - Language of the messages
172
+ */
173
+ export async function uninstallReminder(options, lang) {
174
+ const m = messages(lang);
175
+ const servicePath = join(unitDir(), `${UNIT}.service`);
176
+ const timerPath = join(unitDir(), `${UNIT}.timer`);
177
+ if (options.dryRun) {
178
+ console.log(`# systemctl --user disable --now ${UNIT}.timer`);
179
+ console.log(`# rm ${servicePath} ${timerPath}`);
180
+ console.log(m.reminderDry);
181
+ return;
182
+ }
183
+ // Disabling fails when the timer was never installed, which is fine here.
184
+ await run("systemctl", ["--user", "disable", "--now", `${UNIT}.timer`]).catch(() => undefined);
185
+ await rm(servicePath, { force: true });
186
+ await rm(timerPath, { force: true });
187
+ await run("systemctl", ["--user", "daemon-reload"]).catch(() => undefined);
188
+ console.log(m.reminderRemoved);
189
+ }
@@ -0,0 +1,48 @@
1
+ import { rm } from "node:fs/promises";
2
+ import { basename, resolve, sep } from "node:path";
3
+ import { UUID } from "./scan.js";
4
+ /**
5
+ * Deletion refused by the safety checks, before anything was removed.
6
+ */
7
+ export class UnsafePathError extends Error {
8
+ path;
9
+ /**
10
+ * Builds the error.
11
+ *
12
+ * @param path - Path that failed the checks
13
+ */
14
+ constructor(path) {
15
+ super(`Refusing to delete ${path}`);
16
+ this.path = path;
17
+ }
18
+ }
19
+ /**
20
+ * Refuses any path that is not named after the session or lies outside the config folder.
21
+ *
22
+ * @param configDir - Claude config folder, the only tree deletions may touch
23
+ * @param path - Path about to be deleted
24
+ * @param id - Session UUID the path must be named after
25
+ * @throws UnsafePathError when one of the checks fails
26
+ */
27
+ function assertSafe(configDir, path, id) {
28
+ const root = resolve(configDir) + sep;
29
+ const target = resolve(path);
30
+ if (!UUID.test(id) || !target.startsWith(root) || !basename(target).startsWith(id)) {
31
+ throw new UnsafePathError(path);
32
+ }
33
+ }
34
+ /**
35
+ * Deletes a session: its transcript and the folders that belong to it.
36
+ *
37
+ * Every path is checked before the first one is removed, so a bad path deletes nothing.
38
+ *
39
+ * @param configDir - Claude config folder the session was found in
40
+ * @param session - Measured session; its `paths` list what goes
41
+ * @throws UnsafePathError when a path fails the safety checks, else the file system error
42
+ */
43
+ export async function removeSession(configDir, session) {
44
+ for (const path of session.paths)
45
+ assertSafe(configDir, path, session.id);
46
+ for (const path of session.paths)
47
+ await rm(path, { recursive: true, force: true });
48
+ }