agent-cleandrive 0.0.0-stage → 0.2.2

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/lib/scan.js ADDED
@@ -0,0 +1,253 @@
1
+ import { existsSync, readdirSync, statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import {
4
+ HOME, DATA_DIR, expandHome, loadConfig, idFor, ensureDataDir, writeJson, run, pool,
5
+ } from './util.js';
6
+
7
+ // Categories (fixed order — drives the dashboard's categorical color slots)
8
+ export const CATEGORIES = {
9
+ pkgcache: { label: 'Package caches', risk: 'low', desc: 'Package-manager caches with an official clean command. Fully regenerable.' },
10
+ cache: { label: 'App & tool caches', risk: 'low', desc: 'Cache directories apps rebuild on demand. Safe to delete.' },
11
+ node_modules: { label: 'node_modules', risk: 'low', desc: 'Reinstallable with npm/pnpm/bun install in each project.' },
12
+ projects: { label: 'Projects', risk: 'medium', desc: 'Your work. Archive to the remote drive, verify, then optionally remove locally.' },
13
+ appdata: { label: 'App data', risk: 'review', desc: 'Large app storage (chats, models, wallpapers). Review manually — not auto-deletable.' },
14
+ apps: { label: 'Applications', risk: 'review', desc: 'Installed .app bundles with size and last-used date. Uninstall the ones you no longer open (review-only here).' },
15
+ models: { label: 'AI models', risk: 'review', desc: 'Local model weights. Remove via the owning tool (e.g. ollama rm).' },
16
+ };
17
+
18
+ const APP_ROOTS = ['/Applications', '~/Applications'];
19
+
20
+ // Package caches that have a proper clean command
21
+ const PKG_CACHES = [
22
+ { p: '~/.cache/uv', cmd: 'uv cache clean', label: 'uv package cache' },
23
+ { p: '~/.npm', cmd: 'npm cache clean --force', label: 'npm cache' },
24
+ { p: '~/Library/Caches/Homebrew', cmd: 'brew cleanup -s --prune=all', label: 'Homebrew downloads' },
25
+ { p: '~/Library/pnpm', cmd: 'pnpm store prune', label: 'pnpm store' },
26
+ { p: '~/.bun/install/cache', cmd: 'bun pm cache rm', label: 'bun cache' },
27
+ { p: '~/.pub-cache', cmd: null, label: 'dart pub cache' },
28
+ ];
29
+
30
+ const APPDATA_ROOTS = [
31
+ '~/Library/Application Support',
32
+ '~/Library/Group Containers',
33
+ '~/Library/Containers',
34
+ ];
35
+
36
+ // Paths the scan could not (fully) measure, reported in scan.blocked so the
37
+ // gap between `df` and the scan is explained instead of silently dropped.
38
+ let blocked = [];
39
+ let duTimeoutMs = 60000;
40
+
41
+ async function duKB(p) {
42
+ const r = await run('du', ['-xsk', p], { timeoutMs: duTimeoutMs });
43
+ if (r.timedOut) {
44
+ blocked.push({ path: p, reason: `du timed out after ${duTimeoutMs / 1000}s — likely needs Full Disk Access` });
45
+ return null;
46
+ }
47
+ if (/Operation not permitted/.test(r.err)) {
48
+ blocked.push({ path: p, reason: 'partly unreadable — needs Full Disk Access' });
49
+ }
50
+ if (r.code !== 0 && !r.out) return null;
51
+ const kb = parseInt(r.out.split('\t')[0], 10);
52
+ return Number.isFinite(kb) ? kb : null;
53
+ }
54
+
55
+ async function dfData() {
56
+ const r = await run('df', ['-k', '/System/Volumes/Data']);
57
+ const line = r.out.trim().split('\n').pop().split(/\s+/);
58
+ // APFS: df's "used" counts only the Data volume, but "size" is the whole shared
59
+ // container — so used = size - avail, else used/size/free contradict each other
60
+ const sizeKB = Number(line[1]), availKB = Number(line[3]), usedKB = sizeKB - availKB;
61
+ return { sizeKB, usedKB, availKB, pct: Math.round((usedKB / sizeKB) * 100) };
62
+ }
63
+
64
+ // Was anything inside touched in the last N days? (cheap: stop at first hit)
65
+ async function activeWithin(p, days) {
66
+ const r = await run('find', [p, '-type', 'f', '-mtime', `-${days}`, '-print', '-quit']);
67
+ return r.out.trim().length > 0;
68
+ }
69
+
70
+ function safeStatMtime(p) {
71
+ try { return statSync(p).mtimeMs; } catch { return 0; }
72
+ }
73
+
74
+ function listDirs(root) {
75
+ try {
76
+ return readdirSync(root, { withFileTypes: true })
77
+ .filter((d) => d.isDirectory() && !d.name.startsWith('.'))
78
+ .map((d) => path.join(root, d.name));
79
+ } catch {
80
+ return [];
81
+ }
82
+ }
83
+
84
+ export async function runScan(onProgress = () => {}) {
85
+ ensureDataDir();
86
+ const cfg = loadConfig();
87
+ const staleDays = cfg.staleDays ?? 60;
88
+ blocked = [];
89
+ duTimeoutMs = (cfg.duTimeoutSec ?? 60) * 1000;
90
+ const minCacheKB = (cfg.minCacheMB ?? 100) * 1024;
91
+ const minAppDataKB = (cfg.minAppDataMB ?? 500) * 1024;
92
+ const items = [];
93
+ const claimed = new Set();
94
+ const scanStartedIso = new Date().toISOString();
95
+
96
+ const add = (p, category, extra = {}) => {
97
+ items.push({ id: idFor(p), path: p, category, ...extra });
98
+ };
99
+
100
+ // 1. Package caches
101
+ onProgress('scanning package caches');
102
+ for (const c of PKG_CACHES) {
103
+ const p = expandHome(c.p);
104
+ if (!existsSync(p)) continue;
105
+ claimed.add(p);
106
+ const kb = await duKB(p);
107
+ if (kb) add(p, 'pkgcache', { kb, label: c.label, cleanCmd: c.cmd, suggest: c.cmd ? 'clean' : 'rm', note: c.cmd ? `runs: ${c.cmd}` : 'no clean command — removed directly, rebuilt on next use' });
108
+ }
109
+
110
+ // 2. Generic caches: ~/.cache/* and ~/Library/Caches/* above threshold
111
+ onProgress('scanning cache directories');
112
+ const cacheDirs = [...listDirs(expandHome('~/.cache')), ...listDirs(expandHome('~/Library/Caches'))]
113
+ .filter((p) => !claimed.has(p));
114
+ const cacheSizes = await pool(cacheDirs, 4, (p) => duKB(p));
115
+ cacheDirs.forEach((p, i) => {
116
+ const kb = cacheSizes[i];
117
+ if (kb && kb >= minCacheKB) add(p, 'cache', { kb, suggest: 'rm', note: 'rebuilt automatically by the app' });
118
+ });
119
+
120
+ // 2b. Explicit regenerable caches from config.extraCaches — may live under a
121
+ // protected root (e.g. Claude desktop's vm_bundles); exempted by exact path.
122
+ for (const raw of cfg.extraCaches || []) {
123
+ const p = expandHome(raw);
124
+ if (!existsSync(p) || claimed.has(p)) continue;
125
+ claimed.add(p);
126
+ const kb = await duKB(p);
127
+ if (kb) add(p, 'cache', { kb, suggest: 'rm', note: 'regenerable — re-downloaded/rebuilt on next use (quit the owning app first)' });
128
+ }
129
+
130
+ // 3. node_modules in project roots
131
+ onProgress('finding node_modules');
132
+ const projectRoots = [...(cfg.projectRoots || []), ...(cfg.extraDirs || [])].map(expandHome).filter(existsSync);
133
+ const nmDirs = [];
134
+ for (const root of projectRoots) {
135
+ const r = await run('find', [root, '-maxdepth', '5', '-type', 'd', '-name', 'node_modules', '-prune']);
136
+ nmDirs.push(...r.out.trim().split('\n').filter(Boolean));
137
+ }
138
+ const nmSizes = await pool(nmDirs, 4, (p) => duKB(p));
139
+ const nmByPath = new Map();
140
+ nmDirs.forEach((p, i) => { if (nmSizes[i]) nmByPath.set(p, nmSizes[i]); });
141
+ for (const [p, kb] of nmByPath) {
142
+ if (kb >= 50 * 1024) add(p, 'node_modules', { kb, suggest: 'rm', note: 'reinstall with the project\'s package manager' });
143
+ }
144
+
145
+ // 4. Project directories (top level of each project root, plus extraDirs themselves)
146
+ onProgress('scanning projects');
147
+ const projDirs = [];
148
+ for (const root of (cfg.projectRoots || []).map(expandHome).filter(existsSync)) projDirs.push(...listDirs(root));
149
+ for (const d of (cfg.extraDirs || []).map(expandHome).filter(existsSync)) projDirs.push(d);
150
+ const projSizes = await pool(projDirs, 4, (p) => duKB(p));
151
+ const projActive = await pool(projDirs, 4, (p) => activeWithin(p, staleDays));
152
+ projDirs.forEach((p, i) => {
153
+ const kb = projSizes[i];
154
+ if (!kb || kb < 20 * 1024) return;
155
+ // size excluding contained node_modules (those are their own line items)
156
+ let nmKb = 0;
157
+ for (const [nm, nkb] of nmByPath) if (nm.startsWith(p + path.sep)) nmKb += nkb;
158
+ const netKb = Math.max(0, kb - nmKb);
159
+ const active = projActive[i];
160
+ add(p, 'projects', {
161
+ kb: netKb, grossKb: kb, active, mtime: safeStatMtime(p),
162
+ suggest: active ? 'keep' : 'archive',
163
+ note: active ? `touched within ${staleDays} days` : `no changes in ${staleDays}+ days — archive candidate`,
164
+ });
165
+ });
166
+
167
+ // 5. Large app data (review only)
168
+ onProgress('scanning app data');
169
+ const adDirs = APPDATA_ROOTS.flatMap((r) => listDirs(expandHome(r)));
170
+ const adSizes = await pool(adDirs, 4, (p) => duKB(p));
171
+ adDirs.forEach((p, i) => {
172
+ const kb = adSizes[i];
173
+ if (kb && kb >= minAppDataKB) add(p, 'appdata', { kb, suggest: 'review', note: 'inspect before touching — may hold chats, settings, licenses' });
174
+ });
175
+
176
+ // 6. Applications — bundle size + last-used date, correlated with app-support data
177
+ onProgress('scanning applications');
178
+ const appBundles = [];
179
+ for (const root of APP_ROOTS) {
180
+ const dir = expandHome(root);
181
+ if (!existsSync(dir)) continue;
182
+ try {
183
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
184
+ if (e.name.endsWith('.app')) appBundles.push(path.join(dir, e.name));
185
+ }
186
+ } catch { /* skip */ }
187
+ }
188
+ const appSizes = await pool(appBundles, 4, (p) => duKB(p));
189
+ const appUsed = await pool(appBundles, 6, async (p) => {
190
+ // Primary: Spotlight last-used date. Fallback: latest access time seen across
191
+ // the bundle's Info.plist / executable (survives when Spotlight has no usage record).
192
+ const r = await run('mdls', ['-raw', '-name', 'kMDItemLastUsedDate', p]);
193
+ const v = r.out.trim();
194
+ if (v && v !== '(null)') return v;
195
+ const a = await run('stat', ['-f', '%a', path.join(p, 'Contents', 'Info.plist')]);
196
+ const secs = parseInt(a.out.trim(), 10);
197
+ return Number.isFinite(secs) ? new Date(secs * 1000).toISOString() : null;
198
+ });
199
+ // Index appdata sizes by lowercased basename for correlation
200
+ const adIndex = new Map();
201
+ for (const it of items.filter((i) => i.category === 'appdata')) {
202
+ adIndex.set(path.basename(it.path).toLowerCase(), it.kb);
203
+ }
204
+ const nowMs = Date.parse(scanStartedIso);
205
+ appBundles.forEach((p, i) => {
206
+ const kb = appSizes[i];
207
+ if (!kb || kb < 50 * 1024) return;
208
+ const name = path.basename(p, '.app');
209
+ const lastUsed = appUsed[i];
210
+ const daysIdle = lastUsed ? Math.round((nowMs - Date.parse(lastUsed)) / 86400000) : null;
211
+ // Correlate app-support footprint by fuzzy name match
212
+ let dataKb = 0;
213
+ const key = name.toLowerCase();
214
+ for (const [adName, adKb] of adIndex) {
215
+ if (adName.includes(key) || key.includes(adName.split('.').pop())) dataKb += adKb;
216
+ }
217
+ const stale = daysIdle != null && daysIdle >= 120;
218
+ add(p, 'apps', {
219
+ kb, lastUsed, daysIdle, dataKb,
220
+ suggest: 'review',
221
+ note: (daysIdle == null ? 'last-used unknown' : `last opened ${daysIdle}d ago`)
222
+ + (dataKb ? ` · +${Math.round(dataKb / 1024)}MB app data` : '')
223
+ + (stale ? ' · idle 120d+ — uninstall candidate' : ''),
224
+ });
225
+ });
226
+
227
+ // 7. Models
228
+ const ollama = expandHome('~/.ollama');
229
+ if (existsSync(ollama)) {
230
+ const kb = await duKB(ollama);
231
+ if (kb) add(ollama, 'models', { kb, suggest: 'review', note: 'ollama list && ollama rm <model>' });
232
+ }
233
+
234
+ // User-protected paths (e.g. Claude agent/coding history): always keep, never actionable
235
+ // — except exact config.extraCaches entries, which the user declared regenerable.
236
+ const protectedPaths = (cfg.protected || []).map(expandHome);
237
+ const extraCacheSet = new Set((cfg.extraCaches || []).map(expandHome));
238
+ for (const it of items) {
239
+ if (extraCacheSet.has(it.path)) continue;
240
+ if (protectedPaths.some((pp) => it.path === pp || it.path.startsWith(pp + path.sep))) {
241
+ it.protected = true;
242
+ it.suggest = 'keep';
243
+ it.note = 'protected in config.json — never touched by cleandrive';
244
+ }
245
+ }
246
+
247
+ items.sort((a, b) => b.kb - a.kb);
248
+ const disk = await dfData();
249
+ const scan = { ts: new Date().toISOString(), disk, staleDays, items, blocked };
250
+ writeJson(path.join(DATA_DIR, 'latest.json'), scan);
251
+ onProgress('done');
252
+ return scan;
253
+ }
package/lib/server.js ADDED
@@ -0,0 +1,208 @@
1
+ import http from 'node:http';
2
+ import { readFileSync, existsSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { ROOT, DATA_DIR, loadConfig, saveConfig, readJson, fmtGB, run } from './util.js';
5
+ import { runScan } from './scan.js';
6
+ import { loadPlan, setPlanItem, setPlanItems, approvedItems, executeItem, testRemote, archive, log } from './actions.js';
7
+ import { offloadPaths, fetchPaths, listOffloaded, findCandidates, loadCandidates, setPin } from './offload.js';
8
+
9
+ const state = {
10
+ scanning: false,
11
+ scanStep: '',
12
+ executing: false,
13
+ current: null,
14
+ liveLog: [],
15
+ };
16
+
17
+ function pushLog(line) {
18
+ for (const l of String(line).split('\n')) {
19
+ if (l.trim()) state.liveLog.push(l.trimEnd());
20
+ }
21
+ if (state.liveLog.length > 400) state.liveLog = state.liveLog.slice(-300);
22
+ }
23
+
24
+ async function dfNow() {
25
+ const r = await run('df', ['-k', '/System/Volumes/Data']);
26
+ const f = r.out.trim().split('\n').pop().split(/\s+/);
27
+ // APFS: df's "used" counts only the Data volume, but "size" is the whole shared
28
+ // container — so used = size - avail, else used/size/free contradict each other
29
+ const sizeKB = +f[1], availKB = +f[3], usedKB = sizeKB - availKB;
30
+ return { sizeKB, usedKB, availKB, pct: Math.round((usedKB / sizeKB) * 100) };
31
+ }
32
+
33
+ async function handleApi(req, res, url, body) {
34
+ const send = (code, obj) => {
35
+ res.writeHead(code, { 'Content-Type': 'application/json' });
36
+ res.end(JSON.stringify(obj));
37
+ };
38
+
39
+ if (req.method === 'GET' && url.pathname === '/api/state') {
40
+ const scan = readJson(path.join(DATA_DIR, 'latest.json'));
41
+ return send(200, {
42
+ scan,
43
+ plan: loadPlan(),
44
+ config: loadConfig(),
45
+ disk: await dfNow(),
46
+ scanning: state.scanning,
47
+ scanStep: state.scanStep,
48
+ executing: state.executing,
49
+ current: state.current,
50
+ log: state.liveLog.slice(-120),
51
+ });
52
+ }
53
+
54
+ if (req.method === 'POST' && url.pathname === '/api/scan') {
55
+ if (state.scanning) return send(409, { error: 'scan already running' });
56
+ state.scanning = true;
57
+ state.scanStep = 'starting';
58
+ runScan((step) => { state.scanStep = step; })
59
+ .catch((e) => pushLog('scan error: ' + e.message))
60
+ .finally(() => { state.scanning = false; });
61
+ return send(202, { started: true });
62
+ }
63
+
64
+ if (req.method === 'POST' && url.pathname === '/api/plan') {
65
+ const { id, status, action, reviewed } = body || {};
66
+ if (!id) return send(400, { error: 'id required' });
67
+ return send(200, setPlanItem(id, {
68
+ ...(status && { status }),
69
+ ...(action && { action }),
70
+ ...(typeof reviewed === 'boolean' && { reviewed }),
71
+ }));
72
+ }
73
+
74
+ if (req.method === 'POST' && url.pathname === '/api/plan/bulk') {
75
+ const changes = Array.isArray(body?.changes) ? body.changes : [];
76
+ if (!changes.length) return send(400, { error: 'changes required' });
77
+ return send(200, setPlanItems(changes));
78
+ }
79
+
80
+ if (req.method === 'POST' && url.pathname === '/api/execute') {
81
+ if (state.executing) return send(409, { error: 'already executing' });
82
+ if ((body?.confirm || '') !== 'FREE') return send(400, { error: 'confirmation word missing' });
83
+ const items = approvedItems();
84
+ const wanted = body?.ids ? items.filter((i) => body.ids.includes(i.id)) : items;
85
+ if (!wanted.length) return send(400, { error: 'no approved items' });
86
+ state.executing = true;
87
+ (async () => {
88
+ for (const item of wanted) {
89
+ state.current = { id: item.id, path: item.path, action: item.plannedAction };
90
+ pushLog(`▶ ${item.plannedAction}: ${item.path} (${fmtGB(item.kb)})`);
91
+ try {
92
+ const r = await executeItem(item, { onData: pushLog });
93
+ pushLog(r.ok ? `✓ done: ${item.path}` : `✗ failed: ${item.path} — ${r.output.split('\n').pop()}`);
94
+ } catch (e) {
95
+ pushLog(`✗ refused: ${e.message}`);
96
+ setPlanItem(item.id, { status: 'failed', lastOutput: e.message });
97
+ }
98
+ }
99
+ state.current = null;
100
+ state.executing = false;
101
+ pushLog('— run complete —');
102
+ })();
103
+ return send(202, { started: true, count: wanted.length });
104
+ }
105
+
106
+ if (req.method === 'POST' && url.pathname === '/api/remote/test') {
107
+ return send(200, await testRemote());
108
+ }
109
+
110
+ if (req.method === 'POST' && url.pathname === '/api/remote/config') {
111
+ const cfg = loadConfig();
112
+ cfg.remote = { ...cfg.remote, ...body, enabled: !!body.host };
113
+ saveConfig(cfg);
114
+ log({ event: 'remote-config', host: body.host, path: body.path });
115
+ return send(200, cfg.remote);
116
+ }
117
+
118
+ if (req.method === 'POST' && url.pathname === '/api/offload/dryrun') {
119
+ const items = approvedItems().filter((i) => (i.plannedAction || '').startsWith('archive'));
120
+ if (!items.length) return send(400, { error: 'no approved archive items' });
121
+ state.executing = true;
122
+ (async () => {
123
+ for (const item of items) {
124
+ pushLog(`▶ dry-run archive: ${item.path}`);
125
+ try {
126
+ const r = await archive(item, { dryRun: true, onData: pushLog });
127
+ pushLog(r.ok ? '✓ dry-run ok' : `✗ ${r.output.split('\n').pop()}`);
128
+ } catch (e) { pushLog(`✗ ${e.message}`); }
129
+ }
130
+ state.executing = false;
131
+ pushLog('— dry-run complete —');
132
+ })();
133
+ return send(202, { started: true, count: items.length });
134
+ }
135
+
136
+ // ---- offload / fetch (docs/offload-strategy.md) ----
137
+ if (req.method === 'GET' && url.pathname === '/api/offload') {
138
+ const l = listOffloaded();
139
+ const c = loadCandidates();
140
+ const pinned = (p) => l.pins.some((pp) => p === pp || p.startsWith(pp + '/'));
141
+ if (c) c.candidates = c.candidates.filter((x) => !pinned(x.path));
142
+ return send(200, { ...l, candidates: c, finding: state.finding || false });
143
+ }
144
+
145
+ if (req.method === 'POST' && url.pathname === '/api/offload/candidates') {
146
+ if (state.finding) return send(409, { error: 'already searching' });
147
+ state.finding = true;
148
+ pushLog('▶ searching offload candidates…');
149
+ findCandidates({ minMB: Number(body?.minMB) || 200, days: Number(body?.days) || 30, onData: pushLog })
150
+ .then((r) => pushLog(`✓ ${r.candidates.length} offload candidate(s)${r.unreadable ? ` — ${r.unreadable} paths unreadable (Full Disk Access)` : ''}`))
151
+ .catch((e) => pushLog('✗ candidates: ' + e.message))
152
+ .finally(() => { state.finding = false; });
153
+ return send(202, { started: true });
154
+ }
155
+
156
+ if (req.method === 'POST' && (url.pathname === '/api/offload/run' || url.pathname === '/api/offload/fetch')) {
157
+ const isFetch = url.pathname.endsWith('/fetch');
158
+ if (state.executing) return send(409, { error: 'already executing' });
159
+ const paths = Array.isArray(body?.paths) ? body.paths.filter((p) => typeof p === 'string') : [];
160
+ if (!paths.length) return send(400, { error: 'paths required' });
161
+ if (!isFetch && body?.confirm !== 'OFFLOAD') return send(400, { error: 'confirmation word missing' });
162
+ state.executing = true;
163
+ (isFetch ? fetchPaths : offloadPaths)(paths, { onData: pushLog })
164
+ .then((r) => pushLog(`— ${isFetch ? 'fetch' : 'offload'} complete: ${r.filter((x) => x.ok).length}/${r.length} ok —`))
165
+ .catch((e) => pushLog('✗ ' + e.message))
166
+ .finally(() => { state.executing = false; });
167
+ return send(202, { started: true, count: paths.length });
168
+ }
169
+
170
+ if (req.method === 'POST' && url.pathname === '/api/offload/pin') {
171
+ if (typeof body?.path !== 'string') return send(400, { error: 'path required' });
172
+ return send(200, { path: setPin(body.path, body.pinned !== false) });
173
+ }
174
+
175
+ send(404, { error: 'not found' });
176
+ }
177
+
178
+ export function serve() {
179
+ const cfg = loadConfig();
180
+ const port = cfg.port || 4499;
181
+ const server = http.createServer((req, res) => {
182
+ const url = new URL(req.url, `http://127.0.0.1:${port}`);
183
+ if (url.pathname.startsWith('/api/')) {
184
+ let raw = '';
185
+ req.on('data', (d) => { raw += d; });
186
+ req.on('end', () => {
187
+ let body = null;
188
+ try { body = raw ? JSON.parse(raw) : null; } catch { /* ignore */ }
189
+ handleApi(req, res, url, body).catch((e) => {
190
+ res.writeHead(500, { 'Content-Type': 'application/json' });
191
+ res.end(JSON.stringify({ error: e.message }));
192
+ });
193
+ });
194
+ return;
195
+ }
196
+ const ui = path.join(ROOT, 'ui', 'index.html');
197
+ if (url.pathname === '/' && existsSync(ui)) {
198
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
199
+ return res.end(readFileSync(ui));
200
+ }
201
+ res.writeHead(404);
202
+ res.end('not found');
203
+ });
204
+ server.listen(port, '127.0.0.1', () => {
205
+ console.log(`cleandrive dashboard → http://localhost:${port}`);
206
+ });
207
+ return server;
208
+ }
package/lib/util.js ADDED
@@ -0,0 +1,118 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { homedir } from 'node:os';
4
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync, openSync, fsyncSync, closeSync } from 'node:fs';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ export const HOME = homedir();
9
+ export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
10
+
11
+ // Where config.json and data/ live:
12
+ // 1. $CLEANDRIVE_HOME if set (tests, custom setups)
13
+ // 2. the repo itself when run from a git clone that already has a config.json
14
+ // 3. ~/.config/cleandrive otherwise (npm / npx installs: the package dir is read-only)
15
+ export const APP_HOME = process.env.CLEANDRIVE_HOME
16
+ ? path.resolve(process.env.CLEANDRIVE_HOME)
17
+ : existsSync(path.join(ROOT, 'config.json'))
18
+ ? ROOT
19
+ : path.join(HOME, '.config', 'cleandrive');
20
+ export const CONFIG_FILE = path.join(APP_HOME, 'config.json');
21
+ // CLEANDRIVE_DATA_DIR lets tests run against a throwaway data dir.
22
+ export const DATA_DIR = process.env.CLEANDRIVE_DATA_DIR
23
+ ? path.resolve(process.env.CLEANDRIVE_DATA_DIR)
24
+ : path.join(APP_HOME, 'data');
25
+
26
+ export function expandHome(p) {
27
+ return p.startsWith('~') ? path.join(HOME, p.slice(1)) : p;
28
+ }
29
+
30
+ // First run: seed config.json from the shipped example.
31
+ export function loadConfig() {
32
+ if (!existsSync(CONFIG_FILE)) {
33
+ mkdirSync(APP_HOME, { recursive: true });
34
+ writeFileSync(CONFIG_FILE, readFileSync(path.join(ROOT, 'config.example.json'), 'utf8'));
35
+ process.stderr.write(`cleandrive: created ${CONFIG_FILE} — edit projectRoots and remote there\n`);
36
+ }
37
+ return JSON.parse(readFileSync(CONFIG_FILE, 'utf8'));
38
+ }
39
+
40
+ export function saveConfig(cfg) {
41
+ writeFileSync(CONFIG_FILE, JSON.stringify(cfg, null, 2) + '\n');
42
+ }
43
+
44
+ export function idFor(p) {
45
+ return createHash('sha1').update(p).digest('hex').slice(0, 10);
46
+ }
47
+
48
+ export function ensureDataDir() {
49
+ mkdirSync(DATA_DIR, { recursive: true });
50
+ }
51
+
52
+ export function readJson(file, fallback = null) {
53
+ try {
54
+ return JSON.parse(readFileSync(file, 'utf8'));
55
+ } catch {
56
+ return fallback;
57
+ }
58
+ }
59
+
60
+ // Atomic write: a crash mid-write leaves the old file intact, never a torn one.
61
+ export function writeJson(file, obj) {
62
+ writeFileAtomic(file, JSON.stringify(obj, null, 2));
63
+ }
64
+
65
+ export function writeFileAtomic(file, data) {
66
+ const tmp = `${file}.tmp-${process.pid}`;
67
+ const fd = openSync(tmp, 'w');
68
+ try {
69
+ writeFileSync(fd, data);
70
+ fsyncSync(fd);
71
+ } finally {
72
+ closeSync(fd);
73
+ }
74
+ renameSync(tmp, file);
75
+ }
76
+
77
+ // Run a command without a shell. Resolves with {code, out, err}; never rejects.
78
+ // opts.timeoutMs kills the child and resolves {code: -1, timedOut: true}: `du`
79
+ // over another app's privacy-protected container can block forever at 0% CPU.
80
+ export function run(cmd, args = [], opts = {}) {
81
+ const { timeoutMs, onData, ...spawnOpts } = opts;
82
+ return new Promise((resolve) => {
83
+ const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'], ...spawnOpts });
84
+ let out = '', err = '', timedOut = false;
85
+ const timer = timeoutMs ? setTimeout(() => { timedOut = true; child.kill('SIGKILL'); }, timeoutMs) : null;
86
+ child.stdout.on('data', (d) => { out += d; onData?.(String(d)); });
87
+ child.stderr.on('data', (d) => { err += d; onData?.(String(d)); });
88
+ child.on('error', (e) => { clearTimeout(timer); resolve({ code: -1, out, err: String(e) }); });
89
+ child.on('close', (code) => {
90
+ clearTimeout(timer);
91
+ resolve(timedOut ? { code: -1, out, err: `timed out after ${timeoutMs / 1000}s`, timedOut } : { code, out, err });
92
+ });
93
+ });
94
+ }
95
+
96
+ // Run through a login zsh so PATH includes homebrew/uv/etc.
97
+ export function runShell(cmdline, opts = {}) {
98
+ return run('zsh', ['-lc', cmdline], opts);
99
+ }
100
+
101
+ export function fmtGB(kb) {
102
+ const gb = kb / 1024 / 1024;
103
+ return gb >= 10 ? gb.toFixed(0) + ' GB' : gb >= 1 ? gb.toFixed(1) + ' GB' : (kb / 1024).toFixed(0) + ' MB';
104
+ }
105
+
106
+ // Simple concurrency pool
107
+ export async function pool(items, limit, fn) {
108
+ const results = new Array(items.length);
109
+ let i = 0;
110
+ async function worker() {
111
+ while (i < items.length) {
112
+ const idx = i++;
113
+ results[idx] = await fn(items[idx], idx);
114
+ }
115
+ }
116
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
117
+ return results;
118
+ }
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "agent-cleandrive",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.2",
4
+ "description": "Safe disk cleanup that any AI agent can drive: the agent proposes, you approve, the tool enforces. Risk-tiered cleaning, checksum-verified archives to your own drive, iCloud-style offload. macOS today, Linux next. Zero dependencies.",
5
+ "type": "module",
6
+ "bin": {
7
+ "cleandrive": "bin/cleandrive.js"
8
+ },
9
+ "files": [
10
+ "bin/cleandrive.js",
11
+ "lib/",
12
+ "ui/",
13
+ "config.example.json",
14
+ "docs/offload-strategy.md"
15
+ ],
16
+ "scripts": {
17
+ "scan": "node bin/cleandrive.js scan",
18
+ "serve": "node bin/cleandrive.js serve",
19
+ "state": "node bin/cleandrive.js state",
20
+ "test": "node --test test/*.test.mjs",
21
+ "prepublishOnly": "node --test test/*.test.mjs"
22
+ },
23
+ "engines": {
24
+ "node": ">=20"
25
+ },
26
+ "os": [
27
+ "darwin"
28
+ ],
29
+ "keywords": [
30
+ "agent",
31
+ "agentic",
32
+ "ai-agent",
33
+ "apple-silicon",
34
+ "archive",
35
+ "claude-code",
36
+ "cleanup",
37
+ "cli",
38
+ "codex",
39
+ "cursor",
40
+ "dashboard",
41
+ "disk-cleanup",
42
+ "disk-space",
43
+ "low-resource",
44
+ "macos",
45
+ "mcp",
46
+ "offload",
47
+ "rsync",
48
+ "swap",
49
+ "tailscale",
50
+ "zero-dependencies"
51
+ ],
52
+ "author": "Martin Kaiser (https://github.com/kaiser-data)",
53
+ "license": "MIT",
54
+ "homepage": "https://github.com/kaiser-data/agent-cleandrive#readme",
55
+ "repository": {
56
+ "type": "git",
57
+ "url": "git+https://github.com/kaiser-data/agent-cleandrive.git"
58
+ },
59
+ "bugs": {
60
+ "url": "https://github.com/kaiser-data/agent-cleandrive/issues"
61
+ }
62
+ }