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/LICENSE +21 -0
- package/README.md +272 -2
- package/bin/cleandrive.js +190 -0
- package/config.example.json +33 -0
- package/docs/offload-strategy.md +132 -0
- package/lib/actions.js +215 -0
- package/lib/offload.js +472 -0
- package/lib/scan.js +253 -0
- package/lib/server.js +208 -0
- package/lib/util.js +118 -0
- package/package.json +60 -4
- package/ui/index.html +489 -0
package/lib/actions.js
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { appendFileSync, existsSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {
|
|
4
|
+
HOME, DATA_DIR, loadConfig, readJson, writeJson, run, runShell, ensureDataDir,
|
|
5
|
+
} from './util.js';
|
|
6
|
+
|
|
7
|
+
const PLAN_FILE = path.join(DATA_DIR, 'plan.json');
|
|
8
|
+
const LOG_FILE = path.join(DATA_DIR, 'actions.log');
|
|
9
|
+
|
|
10
|
+
// Categories whose items may be deleted directly (regenerable data only).
|
|
11
|
+
const RM_ALLOWED = new Set(['pkgcache', 'cache', 'node_modules']);
|
|
12
|
+
// Review-only categories where rm unlocks only after an explicit human review
|
|
13
|
+
// (plan.reviewed === true). Apps stay manual: outside $HOME, often root-owned.
|
|
14
|
+
const REVIEW_RM_UNLOCK = new Set(['appdata', 'models']);
|
|
15
|
+
// Never touch these paths or anything above them, whatever the plan says.
|
|
16
|
+
const DENY = ['~', '~/Documents', '~/Desktop', '~/Downloads', '~/Pictures', '~/Library']
|
|
17
|
+
.map((p) => (p === '~' ? HOME : path.join(HOME, p.slice(2))));
|
|
18
|
+
|
|
19
|
+
export function loadPlan() {
|
|
20
|
+
return readJson(PLAN_FILE, { items: {} });
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function savePlan(plan) {
|
|
24
|
+
ensureDataDir();
|
|
25
|
+
writeJson(PLAN_FILE, plan);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function setPlanItem(id, patch) {
|
|
29
|
+
const plan = loadPlan();
|
|
30
|
+
plan.items[id] = { ...(plan.items[id] || {}), ...patch, updated: new Date().toISOString() };
|
|
31
|
+
savePlan(plan);
|
|
32
|
+
return plan.items[id];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Apply many plan changes in one read/write (dashboard one-click presets).
|
|
36
|
+
export function setPlanItems(changes) {
|
|
37
|
+
const plan = loadPlan();
|
|
38
|
+
const updated = new Date().toISOString();
|
|
39
|
+
for (const { id, ...patch } of changes) {
|
|
40
|
+
if (!id) continue;
|
|
41
|
+
plan.items[id] = { ...(plan.items[id] || {}), ...patch, updated };
|
|
42
|
+
}
|
|
43
|
+
savePlan(plan);
|
|
44
|
+
return plan;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function log(entry) {
|
|
48
|
+
ensureDataDir();
|
|
49
|
+
appendFileSync(LOG_FILE, JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function latestScan() {
|
|
53
|
+
return readJson(path.join(DATA_DIR, 'latest.json'));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// A path is only actionable if it came out of the scan (allowlist by construction),
|
|
57
|
+
// lives under $HOME, and is not a protected root.
|
|
58
|
+
function validateTarget(item) {
|
|
59
|
+
const p = path.resolve(item.path);
|
|
60
|
+
if (!p.startsWith(HOME + path.sep)) throw new Error(`refusing: ${p} is outside ${HOME}`);
|
|
61
|
+
if (p.includes('..')) throw new Error('refusing: path traversal');
|
|
62
|
+
if (DENY.includes(p)) throw new Error(`refusing: ${p} is a protected directory`);
|
|
63
|
+
const cfg = loadConfig();
|
|
64
|
+
const protectedPaths = (cfg.protected || []).map((x) => path.resolve(x.replace(/^~/, HOME)));
|
|
65
|
+
// Exact config.extraCaches entries are user-declared regenerable and exempt
|
|
66
|
+
// from the protected lock (subpaths of them are NOT — only the listed dir).
|
|
67
|
+
const extraCaches = new Set((cfg.extraCaches || []).map((x) => path.resolve(x.replace(/^~/, HOME))));
|
|
68
|
+
for (const pp of protectedPaths) {
|
|
69
|
+
if ((p === pp || p.startsWith(pp + path.sep)) && !extraCaches.has(p)) {
|
|
70
|
+
throw new Error(`refusing: ${p} is user-protected (config.protected)`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return p;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function remoteTarget(cfg) {
|
|
77
|
+
const { host, user, path: rpath } = cfg.remote || {};
|
|
78
|
+
if (!host || !rpath) throw new Error('remote not configured (set remote.host and remote.path in config.json)');
|
|
79
|
+
return `${user ? user + '@' : ''}${host}:${rpath.replace(/\/$/, '')}/`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Extra ssh flags from config.remote (custom identity file / non-22 port).
|
|
83
|
+
// sshKey is expanded from ~ and validated to exist so a typo fails loudly.
|
|
84
|
+
export function sshOpts(cfg) {
|
|
85
|
+
const { sshKey, sshPort } = cfg.remote || {};
|
|
86
|
+
const opts = [];
|
|
87
|
+
if (sshPort && Number(sshPort) !== 22) opts.push('-p', String(Number(sshPort)));
|
|
88
|
+
if (sshKey) {
|
|
89
|
+
const keyPath = path.resolve(sshKey.replace(/^~/, HOME));
|
|
90
|
+
if (!existsSync(keyPath)) throw new Error(`remote.sshKey not found: ${keyPath}`);
|
|
91
|
+
opts.push('-i', keyPath);
|
|
92
|
+
}
|
|
93
|
+
return opts;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// The `-e` transport string rsync uses to invoke ssh, mirroring sshOpts().
|
|
97
|
+
function rsyncShell(cfg) {
|
|
98
|
+
const opts = sshOpts(cfg);
|
|
99
|
+
return opts.length ? ['-e', ['ssh', ...opts].join(' ')] : [];
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// The archive path must live on the real archive drive, not on an empty mount
|
|
103
|
+
// point of the remote's system disk (drive unplugged / not mounted). With
|
|
104
|
+
// remote.uuid set, the filesystem holding remote.path must have that UUID;
|
|
105
|
+
// without it, it must at least not be the remote's root filesystem.
|
|
106
|
+
// needKB (+5% margin) is checked against the drive's free space.
|
|
107
|
+
export async function checkRemoteDrive(cfg, needKB = 0) {
|
|
108
|
+
const { host, user, path: rpath, uuid } = cfg.remote || {};
|
|
109
|
+
const dest = `${user ? user + '@' : ''}${host}`;
|
|
110
|
+
const base = ['-o', 'ConnectTimeout=5', '-o', 'BatchMode=yes', ...sshOpts(cfg)];
|
|
111
|
+
const q = `'${rpath.replace(/'/g, `'\\''`)}'`;
|
|
112
|
+
const r = await run('ssh', [...base, dest, `findmnt -n -b -o UUID,TARGET,AVAIL -T ${q}`]);
|
|
113
|
+
if (r.code === 255) return { ok: false, reachable: false, mounted: false, msg: (r.err || 'unreachable').trim().split('\n').pop() };
|
|
114
|
+
const [fsUuid, target, avail] = r.out.trim().split(/\s+/);
|
|
115
|
+
if (r.code !== 0 || !target) return { ok: false, reachable: true, mounted: false, msg: `archive path ${rpath} not found — is the archive drive mounted?` };
|
|
116
|
+
const freeKB = Math.floor(Number(avail) / 1024);
|
|
117
|
+
const mounted = uuid ? fsUuid === uuid : target !== '/';
|
|
118
|
+
if (!mounted) {
|
|
119
|
+
return { ok: false, reachable: true, mounted, freeKB, msg: `archive drive not mounted: ${rpath} is on ${target} (uuid ${fsUuid || '?'})${uuid ? `, expected uuid ${uuid}` : ''}` };
|
|
120
|
+
}
|
|
121
|
+
if (needKB && freeKB < needKB * 1.05) {
|
|
122
|
+
return { ok: false, reachable: true, mounted, freeKB, msg: `not enough space on archive drive: ${Math.round(freeKB / 1024)} MB free, need ~${Math.round(needKB * 1.05 / 1024)} MB` };
|
|
123
|
+
}
|
|
124
|
+
return { ok: true, reachable: true, mounted, freeKB, msg: `archive drive mounted at ${target} — ${(freeKB / 1048576).toFixed(0)} GB free` };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export async function testRemote() {
|
|
128
|
+
const cfg = loadConfig();
|
|
129
|
+
const { host, path: rpath } = cfg.remote || {};
|
|
130
|
+
if (!host || !rpath) return { ok: false, reachable: false, mounted: false, msg: 'remote not configured (set remote.host and remote.path in config.json)' };
|
|
131
|
+
try { return await checkRemoteDrive(cfg); } catch (e) { return { ok: false, reachable: false, mounted: false, msg: e.message }; }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// rsync src into remote archive, preserving the path relative to $HOME.
|
|
135
|
+
// Returns { ok, verified, output }.
|
|
136
|
+
export async function archive(item, { dryRun = false, onData } = {}) {
|
|
137
|
+
const cfg = loadConfig();
|
|
138
|
+
const src = validateTarget(item);
|
|
139
|
+
const rel = './' + path.relative(HOME, src);
|
|
140
|
+
const dest = remoteTarget(cfg);
|
|
141
|
+
const transport = rsyncShell(cfg);
|
|
142
|
+
const drive = await checkRemoteDrive(cfg, item.kb || 0);
|
|
143
|
+
if (!drive.ok) return { ok: false, verified: false, output: `refusing archive: ${drive.msg}` };
|
|
144
|
+
// Portable flags only: macOS ships openrsync ("2.6.9 compatible"), which
|
|
145
|
+
// rejects rsync 3.x options like --info=. --stats/--partial work everywhere.
|
|
146
|
+
const args = ['-aHR', '--partial', '--stats', ...transport];
|
|
147
|
+
if (dryRun) args.push('-n');
|
|
148
|
+
const r = await run('rsync', [...args, rel, dest], { cwd: HOME, onData });
|
|
149
|
+
if (r.code !== 0) return { ok: false, verified: false, output: r.err || r.out };
|
|
150
|
+
if (dryRun) return { ok: true, verified: false, output: r.out };
|
|
151
|
+
// Verify: checksum dry-run must report no differing files. Metadata-only
|
|
152
|
+
// lines (times/perms/owner, e.g. symlink perms unrepresentable on ext4) are
|
|
153
|
+
// ignored; content differences always carry a 'c' (checksum), 's' (size) or
|
|
154
|
+
// '+' (missing on remote) flag, or a non-'.' update type (*deleting, >f…).
|
|
155
|
+
const v = await run('rsync', ['-aHRnc', '--itemize-changes', ...transport, rel, dest], { cwd: HOME });
|
|
156
|
+
const changes = v.out.trim().split('\n').filter(Boolean).filter((l) => {
|
|
157
|
+
const flags = l.split(' ')[0];
|
|
158
|
+
return flags[0] !== '.' || flags.includes('c') || flags.includes('s') || flags.includes('+');
|
|
159
|
+
}).length;
|
|
160
|
+
const verified = v.code === 0 && changes === 0;
|
|
161
|
+
return { ok: true, verified, output: r.out + (verified ? '\nVERIFIED: checksums match' : `\nVERIFY FAILED: ${changes} differences`) };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export async function executeItem(item, { onData = () => {} } = {}) {
|
|
165
|
+
const p = validateTarget(item);
|
|
166
|
+
const action = item.plannedAction || item.suggest;
|
|
167
|
+
log({ event: 'start', id: item.id, path: p, action });
|
|
168
|
+
|
|
169
|
+
let result;
|
|
170
|
+
if (action === 'clean' && item.cleanCmd) {
|
|
171
|
+
result = await runShell(item.cleanCmd, { onData });
|
|
172
|
+
// Some caches keep residue after the official clean (e.g. npm _cacache logs) — that's fine.
|
|
173
|
+
result = { ok: result.code === 0, output: (result.out + result.err).slice(-4000) };
|
|
174
|
+
} else if (action === 'rm') {
|
|
175
|
+
const reviewUnlocked = REVIEW_RM_UNLOCK.has(item.category) && item.reviewed === true;
|
|
176
|
+
if (!RM_ALLOWED.has(item.category) && !reviewUnlocked) {
|
|
177
|
+
const hint = REVIEW_RM_UNLOCK.has(item.category) ? ' (mark it reviewed first)' : '';
|
|
178
|
+
throw new Error(`refusing rm: category '${item.category}' is not deletable${hint}`);
|
|
179
|
+
}
|
|
180
|
+
const r = await run('rm', ['-rf', p], { onData });
|
|
181
|
+
result = { ok: r.code === 0, output: r.err || 'removed' };
|
|
182
|
+
} else if (action === 'archive' || action === 'archive+rm') {
|
|
183
|
+
const a = await archive(item, { onData });
|
|
184
|
+
result = { ok: a.ok, verified: a.verified, output: a.output.slice(-4000) };
|
|
185
|
+
if (action === 'archive+rm') {
|
|
186
|
+
if (!a.ok || !a.verified) {
|
|
187
|
+
result.output += '\nlocal copy KEPT (transfer not verified)';
|
|
188
|
+
} else {
|
|
189
|
+
const r = await run('rm', ['-rf', p]);
|
|
190
|
+
result.output += r.code === 0 ? '\nlocal copy removed after verification' : `\nrm failed: ${r.err}`;
|
|
191
|
+
result.ok = r.code === 0;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
} else {
|
|
195
|
+
result = { ok: false, output: `no executable action for '${action}' (review items are manual)` };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
log({ event: 'done', id: item.id, path: p, action, ok: result.ok, verified: result.verified });
|
|
199
|
+
setPlanItem(item.id, { status: result.ok ? 'done' : 'failed', lastOutput: result.output.slice(-2000) });
|
|
200
|
+
return result;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Merge scan + plan into actionable approved items
|
|
204
|
+
export function approvedItems() {
|
|
205
|
+
const scan = latestScan();
|
|
206
|
+
const plan = loadPlan();
|
|
207
|
+
if (!scan) return [];
|
|
208
|
+
return scan.items
|
|
209
|
+
.filter((it) => plan.items[it.id]?.status === 'approved')
|
|
210
|
+
.map((it) => ({
|
|
211
|
+
...it,
|
|
212
|
+
plannedAction: plan.items[it.id].action || it.suggest,
|
|
213
|
+
reviewed: plan.items[it.id].reviewed === true,
|
|
214
|
+
}));
|
|
215
|
+
}
|