agent-cleandrive 0.0.0-stage → 0.3.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/LICENSE +21 -0
- package/README.md +357 -2
- package/bin/cleandrive.js +280 -0
- package/config.example.json +35 -0
- package/docs/offload-strategy.md +132 -0
- package/lib/actions.js +263 -0
- package/lib/archives.js +242 -0
- package/lib/catalog.js +222 -0
- package/lib/offload.js +534 -0
- package/lib/projects.js +114 -0
- package/lib/scan.js +236 -0
- package/lib/server.js +261 -0
- package/lib/util.js +134 -0
- package/package.json +60 -4
- package/ui/index.html +521 -0
package/lib/scan.js
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { existsSync, readdirSync, statSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { discoverProjects, inspectProject, projectScanItems } from './projects.js';
|
|
4
|
+
import {
|
|
5
|
+
HOME, DATA_DIR, expandHome, loadConfig, idFor, ensureDataDir, writeJson, run, pool,
|
|
6
|
+
} from './util.js';
|
|
7
|
+
|
|
8
|
+
// Categories (fixed order — drives the dashboard's categorical color slots)
|
|
9
|
+
export const CATEGORIES = {
|
|
10
|
+
pkgcache: { label: 'Package caches', risk: 'low', desc: 'Package-manager caches with an official clean command. Fully regenerable.' },
|
|
11
|
+
cache: { label: 'App & tool caches', risk: 'low', desc: 'Cache directories apps rebuild on demand. Safe to delete.' },
|
|
12
|
+
node_modules: { label: 'node_modules', risk: 'low', desc: 'Reinstallable with npm/pnpm/bun install in each project.' },
|
|
13
|
+
projects: { label: 'Projects', risk: 'medium', desc: 'Your work. Archive to the remote drive, verify, then optionally remove locally.' },
|
|
14
|
+
appdata: { label: 'App data', risk: 'review', desc: 'Large app storage (chats, models, wallpapers). Review manually — not auto-deletable.' },
|
|
15
|
+
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).' },
|
|
16
|
+
models: { label: 'AI models', risk: 'review', desc: 'Local model weights. Remove via the owning tool (e.g. ollama rm).' },
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export const APP_ROOTS = ['/Applications', '~/Applications'];
|
|
20
|
+
|
|
21
|
+
// Package caches that have a proper clean command
|
|
22
|
+
export const PKG_CACHES = [
|
|
23
|
+
{ p: '~/.cache/uv', cmd: 'uv cache clean', label: 'uv package cache' },
|
|
24
|
+
{ p: '~/.npm', cmd: 'npm cache clean --force', label: 'npm cache' },
|
|
25
|
+
{ p: '~/Library/Caches/Homebrew', cmd: 'brew cleanup -s --prune=all', label: 'Homebrew downloads' },
|
|
26
|
+
{ p: '~/Library/pnpm', cmd: 'pnpm store prune', label: 'pnpm store' },
|
|
27
|
+
{ p: '~/.bun/install/cache', cmd: 'bun pm cache rm', label: 'bun cache' },
|
|
28
|
+
{ p: '~/.pub-cache', cmd: null, label: 'dart pub cache' },
|
|
29
|
+
];
|
|
30
|
+
|
|
31
|
+
export const APPDATA_ROOTS = [
|
|
32
|
+
'~/Library/Application Support',
|
|
33
|
+
'~/Library/Group Containers',
|
|
34
|
+
'~/Library/Containers',
|
|
35
|
+
];
|
|
36
|
+
|
|
37
|
+
// Paths the scan could not (fully) measure, reported in scan.blocked so the
|
|
38
|
+
// gap between `df` and the scan is explained instead of silently dropped.
|
|
39
|
+
let blocked = [];
|
|
40
|
+
let duTimeoutMs = 60000;
|
|
41
|
+
|
|
42
|
+
async function duKB(p) {
|
|
43
|
+
const r = await run('du', ['-xsk', p], { timeoutMs: duTimeoutMs });
|
|
44
|
+
if (r.timedOut) {
|
|
45
|
+
blocked.push({ path: p, reason: `du timed out after ${duTimeoutMs / 1000}s — likely needs Full Disk Access` });
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
if (/Operation not permitted/.test(r.err)) {
|
|
49
|
+
blocked.push({ path: p, reason: 'partly unreadable — needs Full Disk Access' });
|
|
50
|
+
}
|
|
51
|
+
if (r.code !== 0 && !r.out) return null;
|
|
52
|
+
const kb = parseInt(r.out.split('\t')[0], 10);
|
|
53
|
+
return Number.isFinite(kb) ? kb : null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function dfData() {
|
|
57
|
+
const r = await run('df', ['-k', '/System/Volumes/Data']);
|
|
58
|
+
const line = r.out.trim().split('\n').pop().split(/\s+/);
|
|
59
|
+
// APFS: df's "used" counts only the Data volume, but "size" is the whole shared
|
|
60
|
+
// container — so used = size - avail, else used/size/free contradict each other
|
|
61
|
+
const sizeKB = Number(line[1]), availKB = Number(line[3]), usedKB = sizeKB - availKB;
|
|
62
|
+
return { sizeKB, usedKB, availKB, pct: Math.round((usedKB / sizeKB) * 100) };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function safeStatMtime(p) {
|
|
66
|
+
try { return statSync(p).mtimeMs; } catch { return 0; }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function listDirs(root) {
|
|
70
|
+
try {
|
|
71
|
+
return readdirSync(root, { withFileTypes: true })
|
|
72
|
+
.filter((d) => d.isDirectory() && !d.name.startsWith('.'))
|
|
73
|
+
.map((d) => path.join(root, d.name));
|
|
74
|
+
} catch {
|
|
75
|
+
return [];
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export async function runScan(onProgress = () => {}) {
|
|
80
|
+
ensureDataDir();
|
|
81
|
+
const cfg = loadConfig();
|
|
82
|
+
const staleDays = cfg.staleDays ?? 90;
|
|
83
|
+
blocked = [];
|
|
84
|
+
duTimeoutMs = (cfg.duTimeoutSec ?? 60) * 1000;
|
|
85
|
+
const minCacheKB = (cfg.minCacheMB ?? 100) * 1024;
|
|
86
|
+
const minAppDataKB = (cfg.minAppDataMB ?? 500) * 1024;
|
|
87
|
+
const items = [];
|
|
88
|
+
const claimed = new Set();
|
|
89
|
+
const scanStartedIso = new Date().toISOString();
|
|
90
|
+
|
|
91
|
+
const add = (p, category, extra = {}) => {
|
|
92
|
+
items.push({ id: idFor(p), path: p, category, ...extra });
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
// 1. Package caches
|
|
96
|
+
onProgress('scanning package caches');
|
|
97
|
+
for (const c of PKG_CACHES) {
|
|
98
|
+
const p = expandHome(c.p);
|
|
99
|
+
if (!existsSync(p)) continue;
|
|
100
|
+
claimed.add(p);
|
|
101
|
+
const kb = await duKB(p);
|
|
102
|
+
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' });
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// 2. Generic caches: ~/.cache/* and ~/Library/Caches/* above threshold
|
|
106
|
+
onProgress('scanning cache directories');
|
|
107
|
+
const cacheDirs = [...listDirs(expandHome('~/.cache')), ...listDirs(expandHome('~/Library/Caches'))]
|
|
108
|
+
.filter((p) => !claimed.has(p));
|
|
109
|
+
const cacheSizes = await pool(cacheDirs, 4, (p) => duKB(p));
|
|
110
|
+
cacheDirs.forEach((p, i) => {
|
|
111
|
+
const kb = cacheSizes[i];
|
|
112
|
+
if (kb && kb >= minCacheKB) add(p, 'cache', { kb, suggest: 'rm', note: 'rebuilt automatically by the app' });
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
// 2b. Explicit regenerable caches from config.extraCaches — may live under a
|
|
116
|
+
// protected root (e.g. Claude desktop's vm_bundles); exempted by exact path.
|
|
117
|
+
for (const raw of cfg.extraCaches || []) {
|
|
118
|
+
const p = expandHome(raw);
|
|
119
|
+
if (!existsSync(p) || claimed.has(p)) continue;
|
|
120
|
+
claimed.add(p);
|
|
121
|
+
const kb = await duKB(p);
|
|
122
|
+
if (kb) add(p, 'cache', { kb, suggest: 'rm', note: 'regenerable — re-downloaded/rebuilt on next use (quit the owning app first)' });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// 3. node_modules in project roots
|
|
126
|
+
onProgress('finding node_modules');
|
|
127
|
+
const projectRoots = [...(cfg.projectRoots || []), ...(cfg.extraDirs || [])].map(expandHome).filter(existsSync);
|
|
128
|
+
const nmDirs = [];
|
|
129
|
+
for (const root of projectRoots) {
|
|
130
|
+
const r = await run('find', [root, '-maxdepth', '5', '-type', 'd', '-name', 'node_modules', '-prune']);
|
|
131
|
+
nmDirs.push(...r.out.trim().split('\n').filter(Boolean));
|
|
132
|
+
}
|
|
133
|
+
const nmSizes = await pool(nmDirs, 4, (p) => duKB(p));
|
|
134
|
+
const nmByPath = new Map();
|
|
135
|
+
nmDirs.forEach((p, i) => { if (nmSizes[i]) nmByPath.set(p, nmSizes[i]); });
|
|
136
|
+
for (const [p, kb] of nmByPath) {
|
|
137
|
+
if (kb >= 50 * 1024) add(p, 'node_modules', { kb, suggest: 'rm', note: 'reinstall with the project\'s package manager' });
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Disjoint project boundaries keep generated churn in one project from hiding siblings.
|
|
141
|
+
onProgress('scanning project activity');
|
|
142
|
+
const projects = await discoverProjects(projectRoots, cfg);
|
|
143
|
+
const projDirs = projects.map(p => p.path);
|
|
144
|
+
const projSizes = await pool(projDirs, 4, p => duKB(p));
|
|
145
|
+
const evidence = await pool(projects, 4, entry => entry.kind === 'group' ? Promise.resolve({band:'unknown',suggest:'keep',note:'grouping folder — select individual projects'}) : inspectProject(entry.path, cfg));
|
|
146
|
+
for (const it of projectScanItems(projects, projSizes, evidence, nmByPath, blocked)) {
|
|
147
|
+
add(it.path, 'projects', { ...it, mtime: safeStatMtime(it.path) });
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// 5. Large app data (review only)
|
|
151
|
+
onProgress('scanning app data');
|
|
152
|
+
const adDirs = APPDATA_ROOTS.flatMap((r) => listDirs(expandHome(r)));
|
|
153
|
+
const adSizes = await pool(adDirs, 4, (p) => duKB(p));
|
|
154
|
+
adDirs.forEach((p, i) => {
|
|
155
|
+
const kb = adSizes[i];
|
|
156
|
+
if (kb && kb >= minAppDataKB) add(p, 'appdata', { kb, suggest: 'review', note: 'inspect before touching — may hold chats, settings, licenses' });
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
// 6. Applications — bundle size + last-used date, correlated with app-support data
|
|
160
|
+
onProgress('scanning applications');
|
|
161
|
+
const appBundles = [];
|
|
162
|
+
for (const root of APP_ROOTS) {
|
|
163
|
+
const dir = expandHome(root);
|
|
164
|
+
if (!existsSync(dir)) continue;
|
|
165
|
+
try {
|
|
166
|
+
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
167
|
+
if (e.name.endsWith('.app')) appBundles.push(path.join(dir, e.name));
|
|
168
|
+
}
|
|
169
|
+
} catch { /* skip */ }
|
|
170
|
+
}
|
|
171
|
+
const appSizes = await pool(appBundles, 4, (p) => duKB(p));
|
|
172
|
+
const appUsed = await pool(appBundles, 6, async (p) => {
|
|
173
|
+
// Primary: Spotlight last-used date. Fallback: latest access time seen across
|
|
174
|
+
// the bundle's Info.plist / executable (survives when Spotlight has no usage record).
|
|
175
|
+
const r = await run('mdls', ['-raw', '-name', 'kMDItemLastUsedDate', p]);
|
|
176
|
+
const v = r.out.trim();
|
|
177
|
+
if (v && Number.isFinite(Date.parse(v))) return v;
|
|
178
|
+
const a = await run('stat', ['-f', '%a', path.join(p, 'Contents', 'Info.plist')]);
|
|
179
|
+
const secs = parseInt(a.out.trim(), 10);
|
|
180
|
+
return Number.isFinite(secs) ? new Date(secs * 1000).toISOString() : null;
|
|
181
|
+
});
|
|
182
|
+
// Index appdata sizes by lowercased basename for correlation
|
|
183
|
+
const adIndex = new Map();
|
|
184
|
+
for (const it of items.filter((i) => i.category === 'appdata')) {
|
|
185
|
+
adIndex.set(path.basename(it.path).toLowerCase(), it.kb);
|
|
186
|
+
}
|
|
187
|
+
const nowMs = Date.parse(scanStartedIso);
|
|
188
|
+
appBundles.forEach((p, i) => {
|
|
189
|
+
const kb = appSizes[i];
|
|
190
|
+
if (!kb || kb < 50 * 1024) return;
|
|
191
|
+
const name = path.basename(p, '.app');
|
|
192
|
+
const lastUsed = appUsed[i];
|
|
193
|
+
const daysIdle = lastUsed ? Math.round((nowMs - Date.parse(lastUsed)) / 86400000) : null;
|
|
194
|
+
// Correlate app-support footprint by fuzzy name match
|
|
195
|
+
let dataKb = 0;
|
|
196
|
+
const key = name.toLowerCase();
|
|
197
|
+
for (const [adName, adKb] of adIndex) {
|
|
198
|
+
if (adName.includes(key) || key.includes(adName.split('.').pop())) dataKb += adKb;
|
|
199
|
+
}
|
|
200
|
+
const stale = daysIdle != null && daysIdle >= 120;
|
|
201
|
+
add(p, 'apps', {
|
|
202
|
+
kb, lastUsed, daysIdle, dataKb,
|
|
203
|
+
suggest: 'review',
|
|
204
|
+
note: (daysIdle == null ? 'last-used unknown' : `last opened ${daysIdle}d ago`)
|
|
205
|
+
+ (dataKb ? ` · +${Math.round(dataKb / 1024)}MB app data` : '')
|
|
206
|
+
+ (stale ? ' · idle 120d+ — uninstall candidate' : ''),
|
|
207
|
+
});
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
// 7. Models
|
|
211
|
+
const ollama = expandHome('~/.ollama');
|
|
212
|
+
if (existsSync(ollama)) {
|
|
213
|
+
const kb = await duKB(ollama);
|
|
214
|
+
if (kb) add(ollama, 'models', { kb, suggest: 'review', note: 'ollama list && ollama rm <model>' });
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// User-protected paths (e.g. Claude agent/coding history): always keep, never actionable
|
|
218
|
+
// — except exact config.extraCaches entries, which the user declared regenerable.
|
|
219
|
+
const protectedPaths = (cfg.protected || []).map(expandHome);
|
|
220
|
+
const extraCacheSet = new Set((cfg.extraCaches || []).map(expandHome));
|
|
221
|
+
for (const it of items) {
|
|
222
|
+
if (extraCacheSet.has(it.path)) continue;
|
|
223
|
+
if (protectedPaths.some((pp) => it.path === pp || it.path.startsWith(pp + path.sep))) {
|
|
224
|
+
it.protected = true;
|
|
225
|
+
it.suggest = 'keep';
|
|
226
|
+
it.note = 'protected in config.json — never touched by cleandrive';
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
items.sort((a, b) => b.kb - a.kb);
|
|
231
|
+
const disk = await dfData();
|
|
232
|
+
const scan = { ts: new Date().toISOString(), disk, staleDays, items, blocked };
|
|
233
|
+
writeJson(path.join(DATA_DIR, 'latest.json'), scan);
|
|
234
|
+
onProgress('done');
|
|
235
|
+
return scan;
|
|
236
|
+
}
|
package/lib/server.js
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
3
|
+
import { listArchives } from './archives.js';
|
|
4
|
+
import { readFileSync, existsSync } from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { ROOT, DATA_DIR, loadConfig, saveConfig, readJson, fmtGB, run } from './util.js';
|
|
7
|
+
import { runScan } from './scan.js';
|
|
8
|
+
import { loadPlan, setPlanItem, setPlanItems, approvedItems, executeItem, testRemote, archive, log, actionRefusal, scanItem } from './actions.js';
|
|
9
|
+
import { offloadPaths, fetchPaths, listOffloaded, findCandidates, loadCandidates, setPin } from './offload.js';
|
|
10
|
+
|
|
11
|
+
const state = {
|
|
12
|
+
scanning: false,
|
|
13
|
+
scanStep: '',
|
|
14
|
+
executing: false,
|
|
15
|
+
current: null,
|
|
16
|
+
liveLog: [],
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
function pushLog(line) {
|
|
20
|
+
for (const l of String(line).split('\n')) {
|
|
21
|
+
if (l.trim()) state.liveLog.push(l.trimEnd());
|
|
22
|
+
}
|
|
23
|
+
if (state.liveLog.length > 400) state.liveLog = state.liveLog.slice(-300);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function dfNow() {
|
|
27
|
+
const r = await run('df', ['-k', '/System/Volumes/Data']);
|
|
28
|
+
const f = r.out.trim().split('\n').pop().split(/\s+/);
|
|
29
|
+
// APFS: df's "used" counts only the Data volume, but "size" is the whole shared
|
|
30
|
+
// container — so used = size - avail, else used/size/free contradict each other
|
|
31
|
+
const sizeKB = +f[1], availKB = +f[3], usedKB = sizeKB - availKB;
|
|
32
|
+
return { sizeKB, usedKB, availKB, pct: Math.round((usedKB / sizeKB) * 100) };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Same gate as `cleandrive approve`: an approval the executor would refuse is never recorded.
|
|
36
|
+
function approvalRefusal(id, status, action) {
|
|
37
|
+
const plan = loadPlan();
|
|
38
|
+
const willBeApproved = status === 'approved' || (!status && plan.items[id]?.status === 'approved');
|
|
39
|
+
if (!willBeApproved) return null;
|
|
40
|
+
const it = scanItem(id);
|
|
41
|
+
if (!it) return 'not in the current scan';
|
|
42
|
+
return actionRefusal({ ...it, reviewed: plan.items[id]?.reviewed === true },
|
|
43
|
+
action || plan.items[id]?.action || it.suggest);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function handleApi(req, res, url, body) {
|
|
47
|
+
const send = (code, obj) => {
|
|
48
|
+
res.writeHead(code, { 'Content-Type': 'application/json' });
|
|
49
|
+
res.end(JSON.stringify(obj));
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
if (req.method === 'GET' && url.pathname === '/api/state') {
|
|
53
|
+
const scan = readJson(path.join(DATA_DIR, 'latest.json'));
|
|
54
|
+
return send(200, {
|
|
55
|
+
scan,
|
|
56
|
+
archives: listArchives(),
|
|
57
|
+
plan: loadPlan(),
|
|
58
|
+
config: loadConfig(),
|
|
59
|
+
disk: await dfNow(),
|
|
60
|
+
scanning: state.scanning,
|
|
61
|
+
scanStep: state.scanStep,
|
|
62
|
+
executing: state.executing,
|
|
63
|
+
current: state.current,
|
|
64
|
+
log: state.liveLog.slice(-120),
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (req.method === 'POST' && url.pathname === '/api/scan') {
|
|
69
|
+
if (state.scanning) return send(409, { error: 'scan already running' });
|
|
70
|
+
state.scanning = true;
|
|
71
|
+
state.scanStep = 'starting';
|
|
72
|
+
runScan((step) => { state.scanStep = step; })
|
|
73
|
+
.catch((e) => pushLog('scan error: ' + e.message))
|
|
74
|
+
.finally(() => { state.scanning = false; });
|
|
75
|
+
return send(202, { started: true });
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if (req.method === 'POST' && url.pathname === '/api/plan') {
|
|
79
|
+
const { id, status, action, reviewed } = body || {};
|
|
80
|
+
if (!id) return send(400, { error: 'id required' });
|
|
81
|
+
const why = approvalRefusal(id, status, action);
|
|
82
|
+
if (why) return send(409, { error: why });
|
|
83
|
+
return send(200, setPlanItem(id, {
|
|
84
|
+
...(status && { status }),
|
|
85
|
+
...(action && { action }),
|
|
86
|
+
...(typeof reviewed === 'boolean' && { reviewed }),
|
|
87
|
+
}));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (req.method === 'POST' && url.pathname === '/api/plan/bulk') {
|
|
91
|
+
const changes = Array.isArray(body?.changes) ? body.changes : [];
|
|
92
|
+
if (!changes.length) return send(400, { error: 'changes required' });
|
|
93
|
+
const refused = changes.map((c) => ({ id: c.id, error: approvalRefusal(c.id, c.status, c.action) })).filter((r) => r.error);
|
|
94
|
+
const ok = changes.filter((c) => !refused.some((r) => r.id === c.id));
|
|
95
|
+
return send(200, { ...setPlanItems(ok), refused });
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (req.method === 'POST' && url.pathname === '/api/execute') {
|
|
99
|
+
if (state.executing) return send(409, { error: 'already executing' });
|
|
100
|
+
if ((body?.confirm || '') !== 'FREE') return send(400, { error: 'confirmation word missing' });
|
|
101
|
+
const items = approvedItems();
|
|
102
|
+
const wanted = body?.ids ? items.filter((i) => body.ids.includes(i.id)) : items;
|
|
103
|
+
if (!wanted.length) return send(400, { error: 'no approved items' });
|
|
104
|
+
state.executing = true;
|
|
105
|
+
(async () => {
|
|
106
|
+
for (const item of wanted) {
|
|
107
|
+
state.current = { id: item.id, path: item.path, action: item.plannedAction };
|
|
108
|
+
pushLog(`▶ ${item.plannedAction}: ${item.path} (${fmtGB(item.kb)})`);
|
|
109
|
+
try {
|
|
110
|
+
const r = await executeItem(item, { onData: pushLog });
|
|
111
|
+
pushLog(r.ok ? `✓ done: ${item.path}` : `✗ failed: ${item.path} — ${r.output.split('\n').pop()}`);
|
|
112
|
+
} catch (e) {
|
|
113
|
+
pushLog(`✗ refused: ${e.message}`);
|
|
114
|
+
setPlanItem(item.id, { status: 'failed', lastOutput: e.message });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
state.current = null;
|
|
118
|
+
state.executing = false;
|
|
119
|
+
pushLog('— run complete —');
|
|
120
|
+
})();
|
|
121
|
+
return send(202, { started: true, count: wanted.length });
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (req.method === 'POST' && url.pathname === '/api/remote/test') {
|
|
125
|
+
return send(200, await testRemote());
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (req.method === 'POST' && url.pathname === '/api/remote/config') {
|
|
129
|
+
const cfg = loadConfig();
|
|
130
|
+
cfg.remote = { ...cfg.remote, ...body, enabled: !!body.host };
|
|
131
|
+
saveConfig(cfg);
|
|
132
|
+
log({ event: 'remote-config', host: body.host, path: body.path });
|
|
133
|
+
return send(200, cfg.remote);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (req.method === 'POST' && url.pathname === '/api/offload/dryrun') {
|
|
137
|
+
const items = approvedItems().filter((i) => (i.plannedAction || '').startsWith('archive'));
|
|
138
|
+
if (!items.length) return send(400, { error: 'no approved archive items' });
|
|
139
|
+
state.executing = true;
|
|
140
|
+
(async () => {
|
|
141
|
+
for (const item of items) {
|
|
142
|
+
pushLog(`▶ dry-run archive: ${item.path}`);
|
|
143
|
+
try {
|
|
144
|
+
const r = await archive(item, { dryRun: true, removeLocal: item.plannedAction === 'archive+rm', onData: pushLog });
|
|
145
|
+
pushLog(r.ok ? '✓ dry-run ok' : `✗ ${r.output.split('\n').pop()}`);
|
|
146
|
+
} catch (e) { pushLog(`✗ ${e.message}`); }
|
|
147
|
+
}
|
|
148
|
+
state.executing = false;
|
|
149
|
+
pushLog('— dry-run complete —');
|
|
150
|
+
})();
|
|
151
|
+
return send(202, { started: true, count: items.length });
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// ---- offload / fetch (docs/offload-strategy.md) ----
|
|
155
|
+
if (req.method === 'GET' && url.pathname === '/api/offload') {
|
|
156
|
+
const l = listOffloaded();
|
|
157
|
+
const c = loadCandidates();
|
|
158
|
+
const pinned = (p) => l.pins.some((pp) => p === pp || p.startsWith(pp + '/'));
|
|
159
|
+
if (c) c.candidates = c.candidates.filter((x) => !pinned(x.path));
|
|
160
|
+
return send(200, { ...l, candidates: c, finding: state.finding || false });
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
if (req.method === 'POST' && url.pathname === '/api/offload/candidates') {
|
|
164
|
+
if (state.finding) return send(409, { error: 'already searching' });
|
|
165
|
+
state.finding = true;
|
|
166
|
+
pushLog('▶ searching offload candidates…');
|
|
167
|
+
findCandidates({ minMB: Number(body?.minMB) || 200, days: Number(body?.days) || 30, onData: pushLog })
|
|
168
|
+
.then((r) => pushLog(`✓ ${r.candidates.length} offload candidate(s)${r.unreadable ? ` — ${r.unreadable} paths unreadable (Full Disk Access)` : ''}`))
|
|
169
|
+
.catch((e) => pushLog('✗ candidates: ' + e.message))
|
|
170
|
+
.finally(() => { state.finding = false; });
|
|
171
|
+
return send(202, { started: true });
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (req.method === 'POST' && (url.pathname === '/api/offload/run' || url.pathname === '/api/offload/fetch')) {
|
|
175
|
+
const isFetch = url.pathname.endsWith('/fetch');
|
|
176
|
+
if (state.executing) return send(409, { error: 'already executing' });
|
|
177
|
+
const paths = Array.isArray(body?.paths) ? body.paths.filter((p) => typeof p === 'string') : [];
|
|
178
|
+
if (!paths.length) return send(400, { error: 'paths required' });
|
|
179
|
+
if (!isFetch && body?.confirm !== 'OFFLOAD') return send(400, { error: 'confirmation word missing' });
|
|
180
|
+
state.executing = true;
|
|
181
|
+
(isFetch ? fetchPaths : offloadPaths)(paths, { onData: pushLog })
|
|
182
|
+
.then((r) => pushLog(`— ${isFetch ? 'fetch' : 'offload'} complete: ${r.filter((x) => x.ok).length}/${r.length} ok —`))
|
|
183
|
+
.catch((e) => pushLog('✗ ' + e.message))
|
|
184
|
+
.finally(() => { state.executing = false; });
|
|
185
|
+
return send(202, { started: true, count: paths.length });
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (req.method === 'POST' && url.pathname === '/api/offload/pin') {
|
|
189
|
+
if (typeof body?.path !== 'string') return send(400, { error: 'path required' });
|
|
190
|
+
return send(200, { path: setPin(body.path, body.pinned !== false) });
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
send(404, { error: 'not found' });
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Browser-facing hardening. Binding to 127.0.0.1 alone does not stop a web page
|
|
197
|
+
// from POSTing to localhost (text/plain is a CORS "simple request") or from
|
|
198
|
+
// DNS-rebinding a hostname onto it. So: the Host header must be our loopback
|
|
199
|
+
// origin (defeats rebinding), a cross-site Origin is refused, and every API call
|
|
200
|
+
// must carry a per-process token that only our own served page knows. A custom
|
|
201
|
+
// header also forces a CORS preflight, which this server never approves.
|
|
202
|
+
export const TOKEN_HEADER = 'x-cleandrive-token';
|
|
203
|
+
|
|
204
|
+
export function requestRefusal(req, port, token) {
|
|
205
|
+
const allowed = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
|
|
206
|
+
if (!allowed.has(String(req.headers.host || '').toLowerCase())) return 'bad host';
|
|
207
|
+
const origin = req.headers.origin;
|
|
208
|
+
if (origin && !allowed.has(origin.replace(/^http:\/\//, '').toLowerCase())) return 'cross-origin request';
|
|
209
|
+
const url = new URL(req.url, `http://127.0.0.1:${port}`);
|
|
210
|
+
if (!url.pathname.startsWith('/api/')) return null;
|
|
211
|
+
const given = Buffer.from(String(req.headers[TOKEN_HEADER] || ''));
|
|
212
|
+
const want = Buffer.from(token);
|
|
213
|
+
if (given.length !== want.length || !timingSafeEqual(given, want)) return 'missing or wrong token';
|
|
214
|
+
if (req.method === 'POST' && !/^application\/json\b/i.test(req.headers['content-type'] || '')) return 'content-type must be application/json';
|
|
215
|
+
return null;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export function serve() {
|
|
219
|
+
const cfg = loadConfig();
|
|
220
|
+
const port = cfg.port || 4499;
|
|
221
|
+
const token = randomBytes(24).toString('hex');
|
|
222
|
+
const server = http.createServer((req, res) => {
|
|
223
|
+
const why = requestRefusal(req, port, token);
|
|
224
|
+
if (why) {
|
|
225
|
+
res.writeHead(403, { 'Content-Type': 'application/json' });
|
|
226
|
+
return res.end(JSON.stringify({ error: `forbidden: ${why}` }));
|
|
227
|
+
}
|
|
228
|
+
const url = new URL(req.url, `http://127.0.0.1:${port}`);
|
|
229
|
+
if (url.pathname.startsWith('/api/')) {
|
|
230
|
+
let raw = '';
|
|
231
|
+
req.on('data', (d) => { raw += d; });
|
|
232
|
+
req.on('end', () => {
|
|
233
|
+
let body = null;
|
|
234
|
+
try { body = raw ? JSON.parse(raw) : null; } catch { /* ignore */ }
|
|
235
|
+
handleApi(req, res, url, body).catch((e) => {
|
|
236
|
+
res.writeHead(500, { 'Content-Type': 'application/json' });
|
|
237
|
+
res.end(JSON.stringify({ error: e.message }));
|
|
238
|
+
});
|
|
239
|
+
});
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
const ui = path.join(ROOT, 'ui', 'index.html');
|
|
243
|
+
if (url.pathname === '/' && existsSync(ui)) {
|
|
244
|
+
res.writeHead(200, {
|
|
245
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
246
|
+
'Cache-Control': 'no-store',
|
|
247
|
+
'X-Frame-Options': 'DENY',
|
|
248
|
+
'Referrer-Policy': 'no-referrer',
|
|
249
|
+
});
|
|
250
|
+
const html = readFileSync(ui, 'utf8')
|
|
251
|
+
.replace('<head>', `<head>\n<meta name="cleandrive-token" content="${token}">`);
|
|
252
|
+
return res.end(html);
|
|
253
|
+
}
|
|
254
|
+
res.writeHead(404);
|
|
255
|
+
res.end('not found');
|
|
256
|
+
});
|
|
257
|
+
server.listen(port, '127.0.0.1', () => {
|
|
258
|
+
console.log(`cleandrive dashboard → http://localhost:${port}`);
|
|
259
|
+
});
|
|
260
|
+
return server;
|
|
261
|
+
}
|
package/lib/util.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
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
|
+
// The SQLite catalog is an advisory index (node:sqlite needs Node >= 22.13). Load it
|
|
97
|
+
// lazily so a missing sqlite module never breaks scan/execute/archive/offload, and
|
|
98
|
+
// never let a catalog error fail an operation whose durable records are already written.
|
|
99
|
+
let catalogMod;
|
|
100
|
+
export async function loadCatalog() {
|
|
101
|
+
if (catalogMod === undefined) {
|
|
102
|
+
try { catalogMod = await import('./catalog.js'); } catch { catalogMod = null; }
|
|
103
|
+
}
|
|
104
|
+
return catalogMod;
|
|
105
|
+
}
|
|
106
|
+
export async function withCatalog(fn) {
|
|
107
|
+
const c = await loadCatalog();
|
|
108
|
+
if (!c) return;
|
|
109
|
+
try { fn(c); } catch { /* advisory */ }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Run through a login zsh so PATH includes homebrew/uv/etc.
|
|
113
|
+
export function runShell(cmdline, opts = {}) {
|
|
114
|
+
return run('zsh', ['-lc', cmdline], opts);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function fmtGB(kb) {
|
|
118
|
+
const gb = kb / 1024 / 1024;
|
|
119
|
+
return gb >= 10 ? gb.toFixed(0) + ' GB' : gb >= 1 ? gb.toFixed(1) + ' GB' : (kb / 1024).toFixed(0) + ' MB';
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Simple concurrency pool
|
|
123
|
+
export async function pool(items, limit, fn) {
|
|
124
|
+
const results = new Array(items.length);
|
|
125
|
+
let i = 0;
|
|
126
|
+
async function worker() {
|
|
127
|
+
while (i < items.length) {
|
|
128
|
+
const idx = i++;
|
|
129
|
+
results[idx] = await fn(items[idx], idx);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
133
|
+
return results;
|
|
134
|
+
}
|