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.
package/LICENSE ADDED
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, Sylvain L.
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md ADDED
@@ -0,0 +1,128 @@
1
+ <h1 align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="assets/logo-dark.svg" />
4
+ <img src="assets/logo-light.svg" alt="ccleanup" width="420" />
5
+ </picture>
6
+ </h1>
7
+
8
+ Interactive cleanup of [Claude Code](https://claude.com/claude-code) sessions. Claude Code keeps every conversation as a transcript in `~/.claude/projects`, and a few long sessions quickly weigh several gigabytes. `ccleanup` lists them by size, shows what each one was about, lets you mark the ones to delete, and can remind you to come back.
9
+
10
+ The list opens at once and grows while the sessions are measured. The header shows the totals, what is marked, what could be freed and what was freed, and deletions run in the background with a per-row state, so the list stays usable.
11
+
12
+ <picture>
13
+ <source media="(prefers-color-scheme: light)" srcset="assets/hero-light.svg" />
14
+ <img src="assets/hero-dark.svg" alt="The scan fills the list, three sessions are marked, a search and the details of a session, then the confirmation box" />
15
+ </picture>
16
+
17
+ Sessions open in Claude Code are tagged `open` and recent ones `recent`, and neither can be marked.
18
+
19
+ **Scan.** The list fills in as the sessions are measured, a firefly on the scan line and embers under the rows.
20
+
21
+ ![The scan in progress](assets/scan.svg)
22
+
23
+ **Confirmation.** Before anything goes, a box lists the marked sessions and the space they free.
24
+
25
+ ![The confirmation box](assets/confirm.svg)
26
+
27
+ **Search and details.** `/` narrows the list, `i` shows what a session is made of and how to resume it.
28
+
29
+ ![A search with the details of a session](assets/details.svg)
30
+
31
+ Drawn from the real interface, on made-up sessions.
32
+
33
+ ## Usage
34
+
35
+ ```bash
36
+ npx ccleanup # interactive list
37
+ npx ccleanup --older-than 14d # same, with sessions older than 14 days pre-marked
38
+ npx ccleanup --list # print the list and exit
39
+ npx ccleanup --older-than 30d --min-size 100M --dry-run # preview a bulk cleanup
40
+ npx ccleanup --older-than 30d --yes # delete without the UI
41
+ ```
42
+
43
+ ### From a clone
44
+
45
+ ```bash
46
+ git clone git@github.com:20syldev/ccleanup.git
47
+ cd ccleanup
48
+ npm install # also builds dist/
49
+ npm link # puts `ccleanup` on the PATH (or run `node dist/cli.js`)
50
+ ```
51
+
52
+ ### Keys
53
+
54
+ | Key | Action |
55
+ | ------------------------ | ----------------------------------------------------------------------------------------- |
56
+ | Up, Down / `j` `k` | Move |
57
+ | `PgUp` `PgDn` / `g` `G` | Page up or down, top, bottom |
58
+ | `space` | Mark or unmark the session, then move the way you last moved |
59
+ | `a` | Mark or unmark everything |
60
+ | `o` | Mark sessions older than `--older-than` (14 days by default) |
61
+ | `s`, `S` | Cycle the sort: size, age, project; reverse the order |
62
+ | `/` | Search by project, title, folder or id; `enter` keeps it, `esc` clears it |
63
+ | `i` | Show the details of the session under the cursor |
64
+ | `?` | Help and legend |
65
+ | `enter` | Delete the marked sessions, after a confirmation box listing them |
66
+ | `e` | Show the deletion errors |
67
+ | `q`, `esc` | Quit, or stop after the current deletion; `esc` first closes a panel or clears the search |
68
+ | `Ctrl+C` twice, `Ctrl+Z` | Quit, suspend |
69
+
70
+ ### Options
71
+
72
+ | Option | Description |
73
+ | ---------------------- | ----------------------------------------------------------------------------------------------------- |
74
+ | `-l`, `--list` | Print the list instead of opening the UI (also the default when not in a terminal) |
75
+ | `--older-than <d>` | Only target sessions older than `<d>`: `12h`, `14d`, `2w`, `3m` |
76
+ | `--min-size <s>` | Only target sessions bigger than `<s>`: `100K`, `500M`, `1G` |
77
+ | `-y`, `--yes` | Delete the targeted sessions without the UI. Requires `--older-than` or `--min-size` |
78
+ | `-n`, `--dry-run` | Show what would be deleted, delete nothing |
79
+ | `--include-recent` | Allow deleting sessions modified less than 30 minutes ago |
80
+ | `--claude-dir <dir>` | Claude config folder, repeatable (default: every folder found, see below) |
81
+ | `--install-reminder` | Install a systemd user timer that notifies when there is cleaning to do |
82
+ | `--every <p>` | Reminder period: `daily`, `weekly` (default) or `monthly` |
83
+ | `--notify-above <s>` | Notification threshold (default `1G`) |
84
+ | `--uninstall-reminder` | Remove that timer |
85
+ | `--check` | What the reminder runs, by hand: summarize what could be cleaned (14 days by default), delete nothing |
86
+ | `--notify` | With `--check`: send a desktop notification above the threshold |
87
+
88
+ ### Environment
89
+
90
+ | Variable | Effect |
91
+ | ------------------------- | ----------------------------------------------------------------------- |
92
+ | `CCLEANUP_LANG=fr\|en` | Interface language; by default French for a French locale, else English |
93
+ | `CCLEANUP_ASCII=1` | Draw the interface with ASCII glyphs only |
94
+ | `CCLEANUP_NOTIFY=<cmd>` | Notification command, called with the text then the title |
95
+ | `NO_COLOR`, `FORCE_COLOR` | Disable or force colors |
96
+
97
+ The colors follow the terminal: true color, 256 or 16 colors, or none. The background is asked to the terminal (OSC 11, then `COLORFGBG`), and a light background gets a darker palette.
98
+
99
+ ## Reminder
100
+
101
+ ```bash
102
+ npm i -g ccleanup
103
+ ccleanup --install-reminder --every weekly --older-than 14d --notify-above 1G
104
+ ```
105
+
106
+ This writes `ccleanup-reminder.service` and `.timer` in `~/.config/systemd/user` and enables the timer. Once a week, it checks the sessions and sends a desktop notification, only when more than 1 GB can be freed. `--dry-run` prints the units without writing anything, and `--uninstall-reminder` removes them. The notification uses `notify-send`; set `CCLEANUP_NOTIFY` to your own command to use something else.
107
+
108
+ ## What is deleted, and what is not
109
+
110
+ A session is a transcript `<uuid>.jsonl` in `~/.claude/projects/<project>/`, plus what Claude Code stores next to it: the `<uuid>/` folder (tool results, subagents, workflows), `file-history/<uuid>`, `session-env/<uuid>` and `debug/<uuid>.txt`. These are deleted together, and their sizes are counted together.
111
+
112
+ Without `--claude-dir`, every config folder found is listed together: `$CLAUDE_CONFIG_DIR`, `~/.claude` and `~/.config/claude` (or `$XDG_CONFIG_HOME/claude`), each one counted once even through a symbolic link. A folder that exists but cannot be read is reported with its path, instead of an empty list.
113
+
114
+ Only entries named after a session UUID are ever listed or deleted. Everything else is left alone: the `memory/` folder of a project, `history.jsonl`, settings, skills, plugins. Every path is checked to be inside the config folder and named after the session before anything is removed. Sessions open in a running Claude Code are tagged `open` and never deleted, even with `--include-recent`: ccleanup reads the record Claude Code keeps for each running instance (`sessions/<pid>.json`) and checks that its process still runs, and on Linux it also looks for session ids passed to running commands (`--resume <id>`). It checks again right before deleting. Sessions modified less than 30 minutes ago are tagged `recent`, since one of them may be running without a record, and are protected unless you pass `--include-recent`.
115
+
116
+ A deleted session can no longer be resumed with `claude --resume`.
117
+
118
+ ## Scripts
119
+
120
+ | Script | Description |
121
+ | --------------------- | ---------------------------------------------------------------------- |
122
+ | `npm run build` | Clean `dist/`, then compile `src/` into it (also run by `npm install`) |
123
+ | `npm run dev` | Compile in watch mode |
124
+ | `npm run clean` | Remove `dist/` |
125
+ | `npm test` | Run the tests with `node --test` (Node 22.18+ for TS) |
126
+ | `npm run check` | `tsc --noEmit` + ESLint + Prettier (check) |
127
+ | `npm run format` | Prettier + ESLint (write) |
128
+ | `npm run screenshots` | Draw the screenshots of `assets/` from the real view (Node 22.18+) |
package/dist/cli.js ADDED
@@ -0,0 +1,223 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { parseArgs, UsageError } from "./core/args.js";
4
+ import { findConfigDirs } from "./core/config.js";
5
+ import { openSessions } from "./core/live.js";
6
+ import { check, installReminder, uninstallReminder } from "./core/remind.js";
7
+ import { removeSession, UnsafePathError } from "./core/remove.js";
8
+ import { discover, scan } from "./core/scan.js";
9
+ import { hasFilter, select, sortSessions } from "./core/select.js";
10
+ import { messages } from "./i18n/messages.js";
11
+ import { detectLang, formatSize, tildify } from "./lib/format.js";
12
+ import { createTheme } from "./ui/theme.js";
13
+ import { runTui } from "./ui/tui.js";
14
+ import { exitSummary, table } from "./ui/view.js";
15
+ const RECENT_MS = 30 * 60_000;
16
+ /**
17
+ * Reads the version of the package.
18
+ *
19
+ * @returns The version field of package.json, one folder above the compiled cli.js
20
+ */
21
+ function version() {
22
+ const url = new URL("../package.json", import.meta.url);
23
+ return JSON.parse(readFileSync(url, "utf8")).version;
24
+ }
25
+ /**
26
+ * Prints the plain table of sessions, biggest first.
27
+ *
28
+ * @param sessions - Sessions to print
29
+ * @param lang - Language of the headers and units
30
+ * @param now - Time of the scan, for ages
31
+ */
32
+ function printTable(sessions, lang, now) {
33
+ const theme = createTheme(process.stdout);
34
+ const cols = process.stdout.columns || 120;
35
+ for (const row of table(sortSessions(sessions, "size"), theme, lang, now, cols)) {
36
+ console.log(row);
37
+ }
38
+ }
39
+ /**
40
+ * Explains an error in the language of the interface.
41
+ *
42
+ * @param error - Anything thrown: usage errors and refused paths are translated, others keep their message
43
+ * @param m - Texts of the interface
44
+ * @returns One line, without the program name
45
+ */
46
+ function describeError(error, m) {
47
+ if (error instanceof UnsafePathError)
48
+ return m.refusing(error.path);
49
+ if (!(error instanceof UsageError))
50
+ return error instanceof Error ? error.message : String(error);
51
+ switch (error.code) {
52
+ case "unknownOption":
53
+ return m.usage.unknownOption(error.option);
54
+ case "missingValue":
55
+ return m.usage.missingValue(error.option);
56
+ case "invalidValue":
57
+ return m.usage.invalidValue(error.option, error.value ?? "", m.usage.expected[error.option] ?? "");
58
+ case "yesNeedsFilter":
59
+ return m.usage.yesNeedsFilter;
60
+ }
61
+ }
62
+ /**
63
+ * Explains why no session was found: folders that refuse reading, or none to read.
64
+ *
65
+ * @param searched - Every config folder looked at
66
+ * @param denied - Folders that exist but cannot be read
67
+ * @param m - Messages in the language of the interface
68
+ * @returns The exit code: 1 when a folder could not be read, else 0
69
+ */
70
+ function reportEmpty(searched, denied, m) {
71
+ if (denied.length > 0) {
72
+ console.error(m.denied(denied.map((path) => tildify(path))));
73
+ return 1;
74
+ }
75
+ console.log(m.noSessions(searched.map((path) => tildify(path))));
76
+ return 0;
77
+ }
78
+ /**
79
+ * Deletes sessions without the interface, for --yes, keeping those opened since the scan.
80
+ *
81
+ * @param configDirs - Claude config folders the sessions were found in, for the re-check
82
+ * @param sessions - Sessions to delete, in order
83
+ * @param lang - Language of the summary
84
+ * @returns Number of failed deletions, each already reported on stderr
85
+ */
86
+ async function deleteAll(configDirs, sessions, lang) {
87
+ let deleted = 0;
88
+ let failed = 0;
89
+ let freed = 0;
90
+ // A session may have opened during the scan: check again.
91
+ const open = await openSessions(configDirs);
92
+ const kept = sessions.filter((session) => open.has(session.id.toLowerCase()));
93
+ if (kept.length > 0)
94
+ console.log(messages(lang).openSkipped(kept.length));
95
+ for (const session of sessions) {
96
+ if (open.has(session.id.toLowerCase()))
97
+ continue;
98
+ try {
99
+ await removeSession(session.configDir, session);
100
+ deleted++;
101
+ freed += session.bytes;
102
+ }
103
+ catch (error) {
104
+ failed++;
105
+ console.error(`${session.id}: ${describeError(error, messages(lang))}`);
106
+ }
107
+ }
108
+ const m = messages(lang);
109
+ console.log(m.done(deleted, formatSize(freed, lang)));
110
+ if (failed > 0)
111
+ console.error(m.failed(failed));
112
+ return failed;
113
+ }
114
+ /**
115
+ * Entry point: parses the options and runs the matching mode.
116
+ *
117
+ * @returns Exit code: 0 on success, 1 when a deletion failed
118
+ * @throws UsageError for a bad command line
119
+ */
120
+ async function main() {
121
+ const lang = detectLang();
122
+ const m = messages(lang);
123
+ const options = parseArgs(process.argv.slice(2));
124
+ if (options.help) {
125
+ process.stdout.write(m.help);
126
+ return 0;
127
+ }
128
+ if (options.version) {
129
+ console.log(version());
130
+ return 0;
131
+ }
132
+ if (options.installReminder) {
133
+ await installReminder(options, lang);
134
+ return 0;
135
+ }
136
+ if (options.uninstallReminder) {
137
+ await uninstallReminder(options, lang);
138
+ return 0;
139
+ }
140
+ if (options.yes && !hasFilter(options))
141
+ throw new UsageError("yesNeedsFilter", "--yes");
142
+ const now = Date.now();
143
+ const search = await findConfigDirs(options.claudeDirs);
144
+ const denied = new Set(search.denied);
145
+ const onDenied = (path) => denied.add(path);
146
+ const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY) &&
147
+ process.env.TERM !== "dumb" &&
148
+ !options.list &&
149
+ !options.check &&
150
+ !options.yes &&
151
+ !options.dryRun;
152
+ if (interactive) {
153
+ // Measuring happens inside the interface, so it opens at once.
154
+ const open = openSessions(search.dirs);
155
+ const found = await Promise.all(search.dirs.map((dir) => discover(dir, onDenied)));
156
+ const entries = found.flat();
157
+ if (entries.length === 0)
158
+ return reportEmpty(search.searched, [...denied], m);
159
+ // Printed before the interface, so it stays after it.
160
+ if (denied.size > 0)
161
+ console.error(m.denied([...denied].map((path) => tildify(path))));
162
+ const result = await runTui({
163
+ configDirs: search.dirs,
164
+ entries,
165
+ open,
166
+ denied: [...denied].map((path) => tildify(path)),
167
+ lang,
168
+ version: version(),
169
+ now,
170
+ recentMs: RECENT_MS,
171
+ olderThan: options.olderThan,
172
+ minSize: options.minSize,
173
+ includeRecent: options.includeRecent,
174
+ });
175
+ for (const row of exitSummary(result, result.theme, lang))
176
+ console.log(row);
177
+ return result.errors.length > 0 ? 1 : 0;
178
+ }
179
+ const open = await openSessions(search.dirs);
180
+ const sessions = await scan(search.dirs, { now, recentMs: RECENT_MS, open }, onDenied);
181
+ if (sessions.length === 0)
182
+ return reportEmpty(search.searched, [...denied], m);
183
+ if (denied.size > 0)
184
+ console.error(m.denied([...denied].map((path) => tildify(path))));
185
+ if (options.check) {
186
+ await check(sessions, options, lang, now);
187
+ return 0;
188
+ }
189
+ const targets = select(sessions, {
190
+ olderThan: options.olderThan,
191
+ minSize: options.minSize,
192
+ includeRecent: options.includeRecent,
193
+ now,
194
+ });
195
+ if (options.yes || options.dryRun) {
196
+ if (targets.length === 0) {
197
+ console.log(m.nothingMatches);
198
+ return 0;
199
+ }
200
+ printTable(targets, lang, now);
201
+ if (options.dryRun) {
202
+ const bytes = targets.reduce((total, session) => total + session.bytes, 0);
203
+ console.log(m.wouldDelete(targets.length, formatSize(bytes, lang)));
204
+ return 0;
205
+ }
206
+ return (await deleteAll(search.dirs, targets, lang)) > 0 ? 1 : 0;
207
+ }
208
+ const shown = hasFilter(options) ? targets : sessions;
209
+ if (shown.length === 0)
210
+ console.log(m.nothingMatches);
211
+ else
212
+ printTable(shown, lang, now);
213
+ return 0;
214
+ }
215
+ main().then((code) => {
216
+ process.exitCode = code;
217
+ }, (error) => {
218
+ const m = messages(detectLang());
219
+ console.error(`ccleanup: ${describeError(error, m)}`);
220
+ if (error instanceof UsageError)
221
+ console.error(m.usage.hint);
222
+ process.exitCode = error instanceof UsageError ? 2 : 1;
223
+ });
@@ -0,0 +1,136 @@
1
+ import { resolve } from "node:path";
2
+ import { DAY, GB, parseDuration, parseSize } from "../lib/format.js";
3
+ export const DEFAULT_OLDER_THAN = 14 * DAY;
4
+ /**
5
+ * Error in the command line itself. It carries a code, the option and the value at
6
+ * fault, so the entry point can explain it in the language of the interface.
7
+ */
8
+ export class UsageError extends Error {
9
+ code;
10
+ option;
11
+ value;
12
+ /**
13
+ * Builds the error.
14
+ *
15
+ * @param code - Kind of mistake
16
+ * @param option - Option at fault, as typed
17
+ * @param value - Value at fault, for invalidValue
18
+ */
19
+ constructor(code, option, value) {
20
+ super(`${code}: ${option}${value === undefined ? "" : ` ${value}`}`);
21
+ this.code = code;
22
+ this.option = option;
23
+ this.value = value;
24
+ }
25
+ }
26
+ // Boolean flags and the option they turn on
27
+ const FLAGS = {
28
+ "-h": "help",
29
+ "--help": "help",
30
+ "-v": "version",
31
+ "--version": "version",
32
+ "-l": "list",
33
+ "--list": "list",
34
+ "-y": "yes",
35
+ "--yes": "yes",
36
+ "-n": "dryRun",
37
+ "--dry-run": "dryRun",
38
+ "--include-recent": "includeRecent",
39
+ "--check": "check",
40
+ "--notify": "notify",
41
+ "--install-reminder": "installReminder",
42
+ "--uninstall-reminder": "uninstallReminder",
43
+ };
44
+ // Options that take a value, as "--name value" or "--name=value"
45
+ const VALUES = ["--older-than", "--min-size", "--notify-above", "--every", "--claude-dir"];
46
+ const EVERY = ["daily", "weekly", "monthly"];
47
+ /**
48
+ * Builds the default options, before any flag is read.
49
+ *
50
+ * @returns Options with every flag off, a weekly reminder and a 1 GB notification threshold
51
+ */
52
+ function defaults() {
53
+ return {
54
+ help: false,
55
+ version: false,
56
+ list: false,
57
+ yes: false,
58
+ dryRun: false,
59
+ includeRecent: false,
60
+ check: false,
61
+ notify: false,
62
+ installReminder: false,
63
+ uninstallReminder: false,
64
+ every: "weekly",
65
+ notifyAbove: GB,
66
+ claudeDirs: [],
67
+ reminderArgs: [],
68
+ };
69
+ }
70
+ /**
71
+ * Applies one option that takes a value.
72
+ *
73
+ * @param options - Options being built, changed in place
74
+ * @param name - Option name, one of VALUES
75
+ * @param value - Raw value from the command line
76
+ * @throws Error when the value does not parse
77
+ */
78
+ function applyValue(options, name, value) {
79
+ switch (name) {
80
+ case "--older-than":
81
+ options.olderThan = parseDuration(value);
82
+ options.reminderArgs.push(name, value);
83
+ break;
84
+ case "--min-size":
85
+ options.minSize = parseSize(value);
86
+ options.reminderArgs.push(name, value);
87
+ break;
88
+ case "--notify-above":
89
+ options.notifyAbove = parseSize(value);
90
+ options.reminderArgs.push(name, value);
91
+ break;
92
+ case "--every":
93
+ if (!EVERY.includes(value)) {
94
+ throw new Error(`Invalid --every "${value}" (daily, weekly or monthly)`);
95
+ }
96
+ options.every = value;
97
+ break;
98
+ case "--claude-dir":
99
+ options.claudeDirs.push(value);
100
+ // The reminder runs from the home folder: resolve it from here.
101
+ options.reminderArgs.push(name, resolve(value));
102
+ break;
103
+ }
104
+ }
105
+ /**
106
+ * Parses the command line arguments.
107
+ *
108
+ * @param argv - Arguments after the script name, as in process.argv.slice(2)
109
+ * @returns The options, defaults filled in
110
+ * @throws UsageError for an unknown option, a missing value or a value that does not parse
111
+ */
112
+ export function parseArgs(argv) {
113
+ const options = defaults();
114
+ const flags = options;
115
+ for (let i = 0; i < argv.length; i++) {
116
+ const arg = argv[i];
117
+ const [name = arg, inline] = arg.startsWith("--") ? arg.split(/=(.*)/s, 2) : [arg];
118
+ const flag = FLAGS[name];
119
+ if (flag) {
120
+ flags[flag] = true;
121
+ continue;
122
+ }
123
+ if (!VALUES.includes(name))
124
+ throw new UsageError("unknownOption", arg);
125
+ const value = inline ?? argv[++i];
126
+ if (value === undefined)
127
+ throw new UsageError("missingValue", name);
128
+ try {
129
+ applyValue(options, name, value);
130
+ }
131
+ catch {
132
+ throw new UsageError("invalidValue", name, value);
133
+ }
134
+ }
135
+ return options;
136
+ }
@@ -0,0 +1,60 @@
1
+ import { readdir, realpath } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ /**
5
+ * Folders that may hold Claude Code sessions, in order of preference.
6
+ *
7
+ * @param overrides - Folders given with --claude-dir; when set, they are the only ones
8
+ * @param env - Environment, for CLAUDE_CONFIG_DIR, XDG_CONFIG_HOME and HOME
9
+ * @returns Absolute paths, without duplicates
10
+ */
11
+ export function configCandidates(overrides, env) {
12
+ const home = env.HOME || homedir();
13
+ const candidates = overrides.length > 0
14
+ ? overrides
15
+ : [
16
+ env.CLAUDE_CONFIG_DIR,
17
+ join(home, ".claude"),
18
+ join(env.XDG_CONFIG_HOME || join(home, ".config"), "claude"),
19
+ ];
20
+ const paths = candidates.filter((path) => Boolean(path));
21
+ return [...new Set(paths.map((path) => resolve(path)))];
22
+ }
23
+ /**
24
+ * Finds the Claude Code config folders that hold sessions.
25
+ *
26
+ * A folder counts when its `projects` subfolder exists. Two folders that lead to the same
27
+ * `projects` tree, through a symbolic link to either, count once: the first one wins.
28
+ *
29
+ * @param overrides - Folders given with --claude-dir; when set, nothing else is searched
30
+ * @param env - Environment, for CLAUDE_CONFIG_DIR, XDG_CONFIG_HOME and HOME
31
+ * @returns The readable folders, the unreadable ones and every folder searched
32
+ */
33
+ export async function findConfigDirs(overrides, env = process.env) {
34
+ const searched = configCandidates(overrides, env);
35
+ const dirs = [];
36
+ const denied = [];
37
+ const seen = new Set();
38
+ for (const dir of searched) {
39
+ const projects = join(dir, "projects");
40
+ let readable = true;
41
+ try {
42
+ await readdir(projects);
43
+ }
44
+ catch (error) {
45
+ const code = error.code;
46
+ if (code !== "EACCES" && code !== "EPERM")
47
+ continue;
48
+ readable = false;
49
+ }
50
+ const real = await realpath(projects).catch(() => projects);
51
+ if (seen.has(real))
52
+ continue;
53
+ seen.add(real);
54
+ if (readable)
55
+ dirs.push(dir);
56
+ else
57
+ denied.push(projects);
58
+ }
59
+ return { dirs, denied, searched };
60
+ }