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/lib/offload.js ADDED
@@ -0,0 +1,534 @@
1
+ // offload / fetch: iCloud-style switch between a local file and a verified copy on
2
+ // the remote archive drive. No daemon anywhere: every step runs
3
+ // inside one command over on-demand ssh/rsync. Design + invariants:
4
+ // docs/offload-strategy.md. The rule that matters most: the local file is only
5
+ // unlinked after the remote copy's sha256 matches AND the local file is unchanged.
6
+ import { createHash } from 'node:crypto';
7
+ import {
8
+ createReadStream, lstatSync, statSync, realpathSync, readdirSync, readFileSync, existsSync,
9
+ unlinkSync, renameSync, utimesSync, statfsSync, openSync, writeFileSync, fsyncSync, closeSync, linkSync,
10
+ } from 'node:fs';
11
+ import path from 'node:path';
12
+ import {
13
+ HOME, DATA_DIR, loadConfig, readJson, writeJson, writeFileAtomic, run, ensureDataDir, expandHome, withCatalog,
14
+ } from './util.js';
15
+ import { checkRemoteDrive, sshOpts, log, remotePathRefusal } from './actions.js';
16
+
17
+ export const STUB_EXT = '.cloud';
18
+ const INDEX_FILE = path.join(DATA_DIR, 'offloaded.json');
19
+ const CANDIDATES_FILE = path.join(DATA_DIR, 'offload-candidates.json');
20
+ const LOCK_FILE = path.join(DATA_DIR, 'offload.lock');
21
+
22
+ // Never offload from here: app data, libraries other software owns, VCS internals.
23
+ const NEVER_SEGMENTS = new Set(['.git', 'node_modules', '.Trash', '.venv']);
24
+ const NEVER_SUFFIXES = ['.photoslibrary', '.fcpbundle', '.imovielibrary', '.musiclibrary', '.tvlibrary', '.app'];
25
+ const MEDIA_EXT = new Set([
26
+ 'mp4', 'mov', 'm4v', 'mkv', 'avi', 'webm', 'mts', 'm2ts', 'mpg', 'mpeg', 'wmv', 'flv', '3gp', 'braw', 'r3d',
27
+ 'wav', 'aif', 'aiff', 'flac', 'm4a', 'caf',
28
+ 'dmg', 'iso', 'img', 'zip', 'tar', 'gz', 'tgz', 'xz', 'bz2', '7z', 'rar',
29
+ 'psd', 'psb', 'tif', 'tiff', 'cr2', 'cr3', 'nef', 'arw', 'dng',
30
+ ]);
31
+ const DEFAULT_ROOTS = ['~/Movies', '~/Documents', '~/Desktop', '~/Downloads', '~/Pictures'];
32
+
33
+ // ---------- small helpers ----------
34
+
35
+ const opt = (cfg) => ({ retries: 5, timeoutSec: 120, ...(cfg.offload || {}) });
36
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
37
+ const q = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
38
+ const short = (p) => p.replace(HOME, '~');
39
+
40
+ export function sha256File(p) {
41
+ return new Promise((resolve, reject) => {
42
+ const h = createHash('sha256');
43
+ createReadStream(p).on('data', (d) => h.update(d)).on('error', reject).on('end', () => resolve(h.digest('hex')));
44
+ });
45
+ }
46
+
47
+ function remoteBase(cfg) {
48
+ const rpath = cfg.remote?.path;
49
+ if (!cfg.remote?.host || !rpath) throw new Error('remote not configured (config.remote.host/path)');
50
+ const bad = remotePathRefusal(rpath);
51
+ if (bad) throw new Error(bad);
52
+ return rpath.replace(/\/$/, '') + '/offload';
53
+ }
54
+ const objectRel = (sha) => `objects/${sha.slice(0, 2)}/${sha}`;
55
+ const remoteDest = (cfg) => `${cfg.remote.user ? cfg.remote.user + '@' : ''}${cfg.remote.host}`;
56
+ // Keepalives make a hung Tailscale link fail fast instead of blocking forever.
57
+ const sshBase = (cfg) => ['-o', 'ConnectTimeout=10', '-o', 'BatchMode=yes', '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=4', ...sshOpts(cfg)];
58
+
59
+ function ssh(cfg, cmd) {
60
+ return run('ssh', [...sshBase(cfg), remoteDest(cfg), cmd]);
61
+ }
62
+
63
+ // No -s (stock macOS openrsync lacks it): remote paths are remote.path (shell-inert, see
64
+ // remotePathRefusal) + objects/<sha>, so they pass the remote shell unquoted — same
65
+ // transport rule as lib/archives.js.
66
+ export function rsyncArgs(cfg) {
67
+ return ['--partial', `--timeout=${opt(cfg).timeoutSec}`, '-e', ['ssh', ...sshBase(cfg)].join(' ')];
68
+ }
69
+
70
+ async function withRetry(cfg, label, fn, onData) {
71
+ const n = Math.max(1, opt(cfg).retries);
72
+ let last;
73
+ for (let i = 1; i <= n; i++) {
74
+ last = await fn();
75
+ if (last.code === 0) return last;
76
+ const why = (last.err || last.out || '').trim().split('\n').pop();
77
+ onData?.(` ${label}: attempt ${i}/${n} failed (exit ${last.code}) ${why}\n`);
78
+ if (i < n) await sleep(Math.min(60000, 5000 * 2 ** (i - 1)));
79
+ }
80
+ return last;
81
+ }
82
+
83
+ async function remoteSha(cfg, rel) {
84
+ const r = await ssh(cfg, `test -f ${q(remoteBase(cfg) + '/' + rel)} && sha256sum -- ${q(remoteBase(cfg) + '/' + rel)}`);
85
+ if (r.code === 255) throw new Error('remote unreachable: ' + (r.err || '').trim().split('\n').pop());
86
+ if (r.code !== 0) return null; // missing
87
+ return r.out.trim().split(/\s+/)[0] || null;
88
+ }
89
+
90
+ // ---------- index + pins ----------
91
+
92
+ export function loadIndex() {
93
+ return readJson(INDEX_FILE, { version: 1, files: {}, pins: [] });
94
+ }
95
+ function saveIndex(idx) {
96
+ ensureDataDir();
97
+ writeJson(INDEX_FILE, idx);
98
+ }
99
+
100
+ export function setPin(p, pinned) {
101
+ const abs = path.resolve(expandHome(p));
102
+ const idx = loadIndex();
103
+ idx.pins = (idx.pins || []).filter((x) => x !== abs);
104
+ if (pinned) idx.pins.push(abs);
105
+ saveIndex(idx);
106
+ return abs;
107
+ }
108
+
109
+ const isPinned = (abs, pins) => pins.some((pp) => abs === pp || abs.startsWith(pp + path.sep));
110
+
111
+ // ---------- lock: one offload/fetch run at a time ----------
112
+
113
+ // Exclusive create (wx), so two runs can never both win. Only a holder whose pid is
114
+ // provably gone (ESRCH) is cleared, once; a live, EPERM, or unreadable lock blocks.
115
+ export function acquireLock() {
116
+ ensureDataDir();
117
+ for (let attempt = 0; ; attempt++) {
118
+ let fd;
119
+ try { fd = openSync(LOCK_FILE, 'wx', 0o600); } catch (e) {
120
+ if (e.code !== 'EEXIST') throw e;
121
+ let raw = null, pid = null;
122
+ try { raw = readFileSync(LOCK_FILE, 'utf8'); pid = JSON.parse(raw).pid; } catch { /* unreadable */ }
123
+ let dead = false;
124
+ if (Number.isInteger(pid) && pid > 0 && pid !== process.pid) {
125
+ try { process.kill(pid, 0); } catch (k) { dead = k.code === 'ESRCH'; }
126
+ }
127
+ const unchanged = () => { try { return readFileSync(LOCK_FILE, 'utf8') === raw; } catch { return false; } };
128
+ if (attempt > 0 || !dead || !unchanged()) throw new Error(`another offload/fetch run is active (pid ${pid ?? '?'}); inspect ${LOCK_FILE} before removing a stale lock`);
129
+ try { unlinkSync(LOCK_FILE); } catch (u) { if (u.code !== 'ENOENT') throw u; }
130
+ continue;
131
+ }
132
+ try { writeFileSync(fd, JSON.stringify({ pid: process.pid, ts: new Date().toISOString() })); fsyncSync(fd); } finally { closeSync(fd); }
133
+ return;
134
+ }
135
+ }
136
+ export function releaseLock() {
137
+ const cur = readJson(LOCK_FILE);
138
+ if (cur?.pid === process.pid) { try { unlinkSync(LOCK_FILE); } catch { /* gone */ } }
139
+ }
140
+ async function locked(fn) {
141
+ acquireLock();
142
+ try { return await fn(); } finally { releaseLock(); }
143
+ }
144
+
145
+ // ---------- validation ----------
146
+
147
+ function protectedPaths(cfg) {
148
+ return (cfg.protected || []).map((x) => path.resolve(expandHome(x)));
149
+ }
150
+
151
+ // Throws with a human reason if `abs` must not be offloaded. Returns lstat.
152
+ export function validateSource(abs, cfg, pins = []) {
153
+ const st = lstatSync(abs);
154
+ if (st.isSymbolicLink()) throw new Error('is a symlink');
155
+ if (!st.isFile()) throw new Error('not a regular file');
156
+ const real = realpathSync(abs);
157
+ if (!real.startsWith(HOME + path.sep)) throw new Error(`outside ${HOME}`);
158
+ if (abs.endsWith(STUB_EXT)) throw new Error('is already an offload stub');
159
+ if (st.nlink > 1) throw new Error('has hard links — removing it would not free space');
160
+ if (real.startsWith(path.join(HOME, 'Library') + path.sep)) throw new Error('inside ~/Library (app data)');
161
+ if (real.startsWith(DATA_DIR + path.sep)) throw new Error("is cleandrive's own data");
162
+ const segs = real.split(path.sep);
163
+ if (segs.some((s) => NEVER_SEGMENTS.has(s))) throw new Error('inside .git/node_modules/.venv/.Trash');
164
+ if (segs.some((s) => NEVER_SUFFIXES.some((x) => s.endsWith(x)))) throw new Error('inside an app/media library package');
165
+ if (protectedPaths(cfg).some((pp) => real === pp || real.startsWith(pp + path.sep))) throw new Error('user-protected (config.protected)');
166
+ if (isPinned(real, pins)) throw new Error('pinned (keep local)');
167
+ return st;
168
+ }
169
+
170
+ // Fails closed: only a clean "nothing open" (exit 1, no output, no error) counts as free.
171
+ export async function inUse(abs, runner = run) {
172
+ const r = await runner('lsof', ['-t', '--', abs], { timeoutMs: 15000 });
173
+ if (r.code === 1 && !r.out.trim() && !r.err.trim()) return false;
174
+ if (r.code === 0 && r.out.trim()) return true;
175
+ throw new Error('open-file check (lsof) failed — local file kept');
176
+ }
177
+
178
+ // Live re-check right before unlink: policy (protected, pins) re-read from disk, the
179
+ // same inode unchanged, not open, and the content still hashing to what was uploaded.
180
+ export async function freshnessRefusal(abs, before, sha, { runner = run, rehash = true } = {}) {
181
+ let now;
182
+ try { now = validateSource(abs, loadConfig(), loadIndex().pins || []); } catch (e) { return e.message; }
183
+ const same = (a, b) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs && a.nlink === b.nlink;
184
+ if (!same(before, now)) return 'file changed during offload';
185
+ try { if (await inUse(abs, runner)) return 'file was opened during offload'; } catch (e) { return e.message; }
186
+ if (rehash && await sha256File(abs) !== sha) return 'content changed during offload';
187
+ if (!same(before, lstatSync(abs))) return 'file changed during offload';
188
+ return null;
189
+ }
190
+
191
+ // Publish `tmp` at `dest` only if nothing exists there (link is atomic and never
192
+ // overwrites); then drop the temp name. Throws EEXIST-style error otherwise.
193
+ export function placeExclusive(tmp, dest, what) {
194
+ try { linkSync(tmp, dest); } catch (e) {
195
+ if (e.code === 'EEXIST') throw new Error(`${what} already exists — nothing overwritten`);
196
+ throw e;
197
+ }
198
+ unlinkSync(tmp);
199
+ }
200
+
201
+ // Expand dirs to files >= minMB (recursive, pruned like validateSource).
202
+ function expandPaths(inputs, minMB) {
203
+ const out = [];
204
+ const walk = (d) => {
205
+ let ents;
206
+ try { ents = readdirSync(d, { withFileTypes: true }); } catch { return; }
207
+ for (const e of ents) {
208
+ const p = path.join(d, e.name);
209
+ if (e.isDirectory()) {
210
+ if (NEVER_SEGMENTS.has(e.name) || NEVER_SUFFIXES.some((x) => e.name.endsWith(x))) continue;
211
+ walk(p);
212
+ } else if (e.isFile() && !e.name.endsWith(STUB_EXT)) {
213
+ try { if (statSync(p).size >= minMB * 1048576) out.push(p); } catch { /* vanished */ }
214
+ }
215
+ }
216
+ };
217
+ for (const raw of inputs) {
218
+ const abs = path.resolve(expandHome(raw));
219
+ let st;
220
+ try { st = lstatSync(abs); } catch { out.push(abs); continue; } // reported later as missing
221
+ if (st.isDirectory()) walk(abs); else out.push(abs);
222
+ }
223
+ return [...new Set(out)];
224
+ }
225
+
226
+ // ---------- stub ----------
227
+
228
+ export function readStub(stubPath) {
229
+ let j;
230
+ try { j = JSON.parse(readFileSync(stubPath, 'utf8')); } catch { return null; }
231
+ return j && j.cleandrive === 'offload-stub' && /^[0-9a-f]{64}$/.test(j.sha256 || '') ? j : null;
232
+ }
233
+
234
+ export function writeStub(abs, meta, cfg) {
235
+ const base = remoteBase(cfg);
236
+ const stub = {
237
+ cleandrive: 'offload-stub',
238
+ v: 1,
239
+ name: path.basename(abs),
240
+ path: abs,
241
+ size: meta.size,
242
+ sha256: meta.sha256,
243
+ mtimeMs: meta.mtimeMs,
244
+ object: objectRel(meta.sha256),
245
+ remote: { host: cfg.remote.host, user: cfg.remote.user, path: base, uuid: cfg.remote.uuid },
246
+ offloadedAt: new Date().toISOString(),
247
+ howToRestore: `cleandrive fetch ${q(abs + STUB_EXT)} — or by hand: rsync ${remoteDest(cfg)}:${base}/${objectRel(meta.sha256)} ${q(abs)}`,
248
+ };
249
+ const file = abs + STUB_EXT, tmp = `${file}.tmp-${process.pid}`;
250
+ const fd = openSync(tmp, 'w', 0o644);
251
+ try { writeFileSync(fd, JSON.stringify(stub, null, 2) + '\n'); fsyncSync(fd); } finally { closeSync(fd); }
252
+ try { placeExclusive(tmp, file, `${path.basename(file)}`); } catch (e) { try { unlinkSync(tmp); } catch { /* gone */ } throw e; }
253
+ return stub;
254
+ }
255
+
256
+ // ---------- offload ----------
257
+
258
+ async function offloadOne(abs, cfg, idx, { dryRun, onData }) {
259
+ const st = validateSource(abs, cfg, idx.pins || []);
260
+ if (existsSync(abs + STUB_EXT)) throw new Error(`${path.basename(abs)}${STUB_EXT} already exists — resolve it first`);
261
+ if (await inUse(abs)) throw new Error('open in another process (lsof) — close it first');
262
+ onData?.(` hashing ${short(abs)} (${(st.size / 1048576).toFixed(0)} MB)…\n`);
263
+ const sha = await sha256File(abs);
264
+ const rel = objectRel(sha);
265
+ const base = remoteBase(cfg);
266
+
267
+ // Always prove the UUID-pinned drive is mounted first: an unmounted drive
268
+ // leaves an empty mount point on the remote's root fs that must never be used.
269
+ const drive = await checkRemoteDrive(cfg, Math.ceil(st.size / 1024));
270
+ if (!drive.ok) throw new Error(`refusing: ${drive.msg}`);
271
+ const existing = await remoteSha(cfg, rel);
272
+ const dedupe = existing === sha;
273
+ if (existing && !dedupe) onData?.(` ⚠ remote object ${rel} is corrupt (hash ${existing.slice(0, 12)}…) — re-uploading\n`);
274
+ if (dryRun) return { path: abs, sha256: sha, size: st.size, dryRun: true, upload: !dedupe };
275
+
276
+ if (!dedupe) {
277
+ const mk = await ssh(cfg, `mkdir -p ${q(path.posix.dirname(base + '/' + rel))}`);
278
+ if (mk.code !== 0) throw new Error('remote mkdir failed: ' + mk.err.trim());
279
+ const part = `${base}/${rel}.part`;
280
+ onData?.(` ↑ uploading to ${cfg.remote.host}…\n`);
281
+ const up = await withRetry(cfg, 'upload', () => run('rsync', [...rsyncArgs(cfg), abs, `${remoteDest(cfg)}:${part}`]), onData);
282
+ if (up.code !== 0) throw new Error(`upload failed after ${opt(cfg).retries} attempts — local file kept`);
283
+ const got = await remoteSha(cfg, `${rel}.part`);
284
+ if (got !== sha) {
285
+ await ssh(cfg, `rm -f -- ${q(part)}`);
286
+ throw new Error(`remote checksum mismatch (${(got || 'missing').slice(0, 12)}…) — local file kept`);
287
+ }
288
+ const mv = await ssh(cfg, `mv -f -- ${q(part)} ${q(base + '/' + rel)}`);
289
+ if (mv.code !== 0) throw new Error('remote rename failed: ' + mv.err.trim());
290
+ }
291
+
292
+ // The file must not have changed while we hashed/uploaded (cheap check first).
293
+ const pre = await freshnessRefusal(abs, st, sha, { rehash: false });
294
+ if (pre) throw new Error(`${pre} — local file kept`);
295
+
296
+ const stub = writeStub(abs, { size: st.size, sha256: sha, mtimeMs: st.mtimeMs }, cfg);
297
+ const entry = { path: abs, size: st.size, sha256: sha, mtimeMs: st.mtimeMs, object: rel, state: 'offloaded', offloadedAt: stub.offloadedAt };
298
+ const line = Buffer.from(JSON.stringify({ event: 'offload', ...entry, mac: process.env.USER }) + '\n').toString('base64');
299
+ const man = await ssh(cfg, `echo ${line} | base64 -d >> ${q(base + '/manifest.jsonl')}`);
300
+ if (man.code !== 0) onData?.(' ⚠ remote manifest append failed (stub + local index still hold the record)\n');
301
+ // Re-check everything live immediately before the only destructive step.
302
+ const late = await freshnessRefusal(abs, st, sha);
303
+ if (late) { try { unlinkSync(abs + STUB_EXT); } catch { /* keep going: file is kept */ } throw new Error(`${late} — local file kept`); }
304
+ idx.files[abs] = entry;
305
+ saveIndex(idx);
306
+ unlinkSync(abs);
307
+ log({ event: 'offload', path: abs, sha256: sha, kb: Math.round(st.size / 1024), dedupe, ok: true, verified: true });
308
+ await withCatalog((c) => c.record({
309
+ id: sha, type: 'offload', local_path: abs, remote_host: cfg.remote.host,
310
+ remote_path: `${base}/${rel}`, size_bytes: st.size, sha256: sha, state: 'offloaded',
311
+ label: path.basename(abs), created_at: stub.offloadedAt,
312
+ metadata: { mtimeMs: st.mtimeMs, object: rel },
313
+ }));
314
+ return { path: abs, sha256: sha, size: st.size, dedupe, ok: true };
315
+ }
316
+
317
+ export async function offloadPaths(inputs, { dryRun = false, minMB = 50, onData } = {}) {
318
+ const cfg = loadConfig();
319
+ const files = expandPaths(inputs, minMB);
320
+ const run1 = async () => {
321
+ const idx = loadIndex();
322
+ const results = [];
323
+ for (const abs of files) {
324
+ onData?.(`${dryRun ? '[dry-run] ' : '▶ '}offload ${short(abs)}\n`);
325
+ try {
326
+ const r = await offloadOne(abs, cfg, idx, { dryRun, onData });
327
+ onData?.(dryRun
328
+ ? ` would ${r.upload ? 'upload' : 'reuse existing remote copy of'} ${(r.size / 1048576).toFixed(0)} MB\n`
329
+ : ` ✓ offloaded${r.dedupe ? ' (already on remote — dedupe)' : ''}, stub ${path.basename(abs)}${STUB_EXT}\n`);
330
+ results.push({ ...r, ok: true });
331
+ } catch (e) {
332
+ onData?.(` ✗ ${e.message}\n`);
333
+ if (!dryRun) log({ event: 'offload', path: abs, ok: false, error: e.message });
334
+ results.push({ path: abs, ok: false, error: e.message });
335
+ }
336
+ }
337
+ return results;
338
+ };
339
+ return dryRun ? run1() : locked(run1);
340
+ }
341
+
342
+ // ---------- fetch ----------
343
+
344
+ function stubFor(p) {
345
+ const abs = path.resolve(expandHome(p));
346
+ return abs.endsWith(STUB_EXT) ? abs : abs + STUB_EXT;
347
+ }
348
+
349
+ function expandStubs(inputs) {
350
+ const out = [];
351
+ const walk = (d) => {
352
+ let ents;
353
+ try { ents = readdirSync(d, { withFileTypes: true }); } catch { return; }
354
+ for (const e of ents) {
355
+ const p = path.join(d, e.name);
356
+ if (e.isDirectory()) walk(p);
357
+ else if (e.isFile() && e.name.endsWith(STUB_EXT)) out.push(p);
358
+ }
359
+ };
360
+ for (const raw of inputs) {
361
+ const abs = path.resolve(expandHome(raw));
362
+ try { if (lstatSync(abs).isDirectory()) { walk(abs); continue; } } catch { /* not a dir */ }
363
+ out.push(stubFor(abs));
364
+ }
365
+ return [...new Set(out)];
366
+ }
367
+
368
+ async function fetchOne(stubPath, cfg, idx, { dryRun, onData }) {
369
+ const stub = readStub(stubPath);
370
+ if (!stub) throw new Error(`${short(stubPath)} is not a cleandrive stub`);
371
+ const target = stubPath.slice(0, -STUB_EXT.length);
372
+ if (!target.startsWith(HOME + path.sep)) throw new Error(`outside ${HOME}`);
373
+ // The parent must resolve inside $HOME too: a symlinked folder could redirect the write.
374
+ const realParent = realpathSync(path.dirname(target));
375
+ if (!realParent.startsWith(realpathSync(HOME) + path.sep) && realParent !== realpathSync(HOME)) throw new Error(`${short(path.dirname(target))} resolves outside ${HOME}`);
376
+
377
+ if (existsSync(target)) {
378
+ // Crash between "stub written" and "original unlinked", or fetched by hand.
379
+ const h = await sha256File(target);
380
+ if (h !== stub.sha256) throw new Error(`${short(target)} exists with different content — resolve by hand, nothing changed`);
381
+ if (!dryRun) unlinkSync(stubPath);
382
+ return { path: target, ok: true, already: true };
383
+ }
384
+ const free = statfsSync(path.dirname(target));
385
+ const freeBytes = free.bavail * free.bsize;
386
+ if (freeBytes < stub.size + 1073741824) throw new Error(`not enough local space: ${(freeBytes / 1073741824).toFixed(1)} GB free, need ${(stub.size / 1073741824 + 1).toFixed(1)} GB`);
387
+ const drive = await checkRemoteDrive(cfg);
388
+ if (!drive.ok) throw new Error(drive.msg);
389
+ const object = objectRel(stub.sha256); // never stub.object: it would reach the remote shell
390
+ const remoteHash = await remoteSha(cfg, object);
391
+ if (!remoteHash) throw new Error(`remote object ${object} missing — see ${remoteBase(cfg)}/manifest.jsonl`);
392
+ if (remoteHash !== stub.sha256) throw new Error(`remote copy corrupt (hash ${remoteHash.slice(0, 12)}…) — stub kept`);
393
+ if (dryRun) return { path: target, size: stub.size, dryRun: true };
394
+
395
+ const tmp = path.join(path.dirname(target), `.${path.basename(target)}.cleandrive-fetch`);
396
+ onData?.(` ↓ downloading ${(stub.size / 1048576).toFixed(0)} MB…\n`);
397
+ const dl = await withRetry(cfg, 'download', () => run('rsync', [...rsyncArgs(cfg), `${remoteDest(cfg)}:${remoteBase(cfg)}/${object}`, tmp]), onData);
398
+ if (dl.code !== 0) throw new Error(`download failed after ${opt(cfg).retries} attempts — stub kept (partial ${path.basename(tmp)} resumes next time)`);
399
+ const h = await sha256File(tmp);
400
+ if (h !== stub.sha256) {
401
+ unlinkSync(tmp);
402
+ throw new Error('downloaded file checksum mismatch — discarded, stub kept');
403
+ }
404
+ placeExclusive(tmp, target, short(target)); // a file created meanwhile is never overwritten
405
+ if (stub.mtimeMs) { const t = new Date(stub.mtimeMs); utimesSync(target, t, t); }
406
+ unlinkSync(stubPath);
407
+ const prev = idx.files[target] || {};
408
+ idx.files[target] = { ...prev, path: target, size: stub.size, sha256: stub.sha256, object, state: 'local', fetchedAt: new Date().toISOString() };
409
+ saveIndex(idx);
410
+ log({ event: 'fetch', path: target, sha256: stub.sha256, kb: Math.round(stub.size / 1024), ok: true, verified: true });
411
+ await withCatalog((c) => c.updateState(stub.sha256, 'local', { fetchedAt: new Date().toISOString() }));
412
+ return { path: target, size: stub.size, ok: true };
413
+ }
414
+
415
+ export async function fetchPaths(inputs, { dryRun = false, onData } = {}) {
416
+ const cfg = loadConfig();
417
+ const stubs = expandStubs(inputs);
418
+ const run1 = async () => {
419
+ const idx = loadIndex();
420
+ const results = [];
421
+ for (const s of stubs) {
422
+ onData?.(`${dryRun ? '[dry-run] ' : '▶ '}fetch ${short(s.slice(0, -STUB_EXT.length))}\n`);
423
+ try {
424
+ const r = await fetchOne(s, cfg, idx, { dryRun, onData });
425
+ onData?.(r.already ? ' ✓ already local (same content) — stub removed\n' : dryRun ? ' would download, remote copy verified\n' : ' ✓ fetched and verified\n');
426
+ results.push({ ...r, ok: true });
427
+ } catch (e) {
428
+ onData?.(` ✗ ${e.message}\n`);
429
+ if (!dryRun) log({ event: 'fetch', path: s, ok: false, error: e.message });
430
+ results.push({ path: s, ok: false, error: e.message });
431
+ }
432
+ }
433
+ return results;
434
+ };
435
+ return dryRun ? run1() : locked(run1);
436
+ }
437
+
438
+ // ---------- list / verify ----------
439
+
440
+ // Index entries, reconciled with what is actually on disk right now.
441
+ export function listOffloaded() {
442
+ const idx = loadIndex();
443
+ const files = Object.values(idx.files).map((f) => {
444
+ const stub = existsSync(f.path + STUB_EXT);
445
+ const local = existsSync(f.path);
446
+ return { ...f, state: stub && !local ? 'offloaded' : local ? 'local' : 'missing' };
447
+ }).sort((a, b) => b.size - a.size);
448
+ return { files, pins: idx.pins || [] };
449
+ }
450
+
451
+ export async function verifyRemote({ onData } = {}) {
452
+ const cfg = loadConfig();
453
+ const drive = await checkRemoteDrive(cfg);
454
+ if (!drive.ok) throw new Error(drive.msg);
455
+ const { files } = listOffloaded();
456
+ const objs = new Map();
457
+ for (const f of files) if (f.object) objs.set(f.object, f);
458
+ const bad = [];
459
+ for (const [rel, f] of objs) {
460
+ const h = await remoteSha(cfg, rel);
461
+ const ok = h === f.sha256;
462
+ onData?.(`${ok ? '✓' : '✗'} ${short(f.path)}${ok ? '' : h ? ' — CORRUPT on remote' : ' — MISSING on remote'}\n`);
463
+ if (!ok) bad.push({ ...f, remoteSha: h });
464
+ }
465
+ log({ event: 'offload-verify', checked: objs.size, bad: bad.length, ok: bad.length === 0 });
466
+ return { checked: objs.size, bad };
467
+ }
468
+
469
+ // ---------- candidates (read-only strategy) ----------
470
+
471
+ // mtime + Spotlight's "last opened". Not atime: hashing, Quick Look and
472
+ // Spotlight indexing all bump it, so a candidate would never look idle again.
473
+ async function lastUsedMs(p, st) {
474
+ let t = st.mtimeMs;
475
+ const r = await run('mdls', ['-raw', '-name', 'kMDItemLastUsedDate', p]);
476
+ const d = Date.parse(r.out.trim());
477
+ if (Number.isFinite(d)) t = Math.max(t, d);
478
+ return t;
479
+ }
480
+
481
+ export async function findCandidates({ minMB = 200, days = 30, allTypes = false, dupes = true, onData } = {}) {
482
+ const cfg = loadConfig();
483
+ const idx = loadIndex();
484
+ const pins = idx.pins || [];
485
+ const roots = [...DEFAULT_ROOTS, ...(cfg.extraDirs || []), ...(cfg.offload?.roots || [])]
486
+ .map((r) => path.resolve(expandHome(r))).filter(existsSync);
487
+ const found = new Map();
488
+ let unreadable = 0;
489
+ for (const root of roots) {
490
+ onData?.(` searching ${short(root)}…\n`);
491
+ const prune = ['(', '-name', 'Library', '-o', '-name', '.git', '-o', '-name', 'node_modules', '-o', '-name', '.venv', '-o', '-name', '.Trash',
492
+ ...NEVER_SUFFIXES.flatMap((s) => ['-o', '-name', `*${s}`]), ')', '-prune'];
493
+ const r = await run('find', [root, ...prune, '-o', '-type', 'f', '-size', `+${minMB}M`, '-print0']);
494
+ unreadable += (r.err.match(/Operation not permitted|Permission denied/g) || []).length;
495
+ for (const p of r.out.split('\0').filter(Boolean)) found.set(p, true);
496
+ }
497
+ const cutoff = Date.now() - days * 864e5;
498
+ const all = [];
499
+ for (const p of found.keys()) {
500
+ const ext = path.extname(p).slice(1).toLowerCase();
501
+ if (!allTypes && !MEDIA_EXT.has(ext)) continue;
502
+ let st;
503
+ try { st = validateSource(p, cfg, pins); } catch { continue; }
504
+ all.push({ path: p, size: st.size, kb: Math.round(st.size / 1024), lastUsed: await lastUsedMs(p, st), st });
505
+ }
506
+ // duplicates: same size → sha256
507
+ if (dupes) {
508
+ const bySize = new Map();
509
+ for (const c of all) bySize.set(c.size, [...(bySize.get(c.size) || []), c]);
510
+ for (const group of bySize.values()) {
511
+ if (group.length < 2) continue;
512
+ for (const c of group) { onData?.(` hashing possible duplicate ${short(c.path)}…\n`); c.sha256 = await sha256File(c.path); }
513
+ const byHash = new Map();
514
+ for (const c of group) byHash.set(c.sha256, [...(byHash.get(c.sha256) || []), c]);
515
+ for (const same of byHash.values()) {
516
+ if (same.length < 2) continue;
517
+ same.sort((a, b) => b.lastUsed - a.lastUsed);
518
+ for (const c of same.slice(1)) c.duplicateOf = same[0].path;
519
+ }
520
+ }
521
+ }
522
+ const out = all
523
+ .filter((c) => c.duplicateOf || c.lastUsed < cutoff)
524
+ .map(({ st, ...c }) => ({ ...c, idleDays: Math.floor((Date.now() - c.lastUsed) / 864e5) }))
525
+ .sort((a, b) => (!!b.duplicateOf - !!a.duplicateOf) || b.size - a.size);
526
+ const res = { ts: new Date().toISOString(), minMB, days, roots: roots.map(short), unreadable, candidates: out };
527
+ ensureDataDir();
528
+ writeJson(CANDIDATES_FILE, res);
529
+ return res;
530
+ }
531
+
532
+ export function loadCandidates() {
533
+ return readJson(CANDIDATES_FILE);
534
+ }
@@ -0,0 +1,114 @@
1
+ // Evidence is advisory: age never authorizes removal.
2
+ import { readdir, lstat } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { DATA_DIR, readJson, expandHome, run } from './util.js';
5
+ export const GENERATED = new Set(['.git','node_modules','.venv','venv','__pycache__','.pytest_cache','.next','.turbo','target','dist','build','.cache']);
6
+ const MARKERS = new Set(['.git','package.json','pyproject.toml','Cargo.toml','go.mod','pom.xml']);
7
+ export const contains = (parent, child) => child === parent || child.startsWith(parent + path.sep);
8
+ export function projectPins(cfg = {}) {
9
+ return [...(cfg.pins || []), ...(readJson(path.join(DATA_DIR,'offloaded.json'), {}).pins || [])].map(p=>path.resolve(expandHome(p)));
10
+ }
11
+ export function isPinned(p, cfg = {}) { return projectPins(cfg).some(pin=>contains(pin,p) || contains(p,pin)); }
12
+
13
+ export async function discoverProjects(roots, cfg = {}) {
14
+ const found = [];
15
+ const protectedPaths=(cfg.protected || []).map(p=>path.resolve(expandHome(p)));
16
+ const depthLimit=Math.max(1,Math.min(8,Number(cfg.projectDepth)||3));
17
+ async function walk(p, depth) {
18
+ if(protectedPaths.some(pp=>contains(pp,p))) return;
19
+ let entries;
20
+ try { if(!(await lstat(p)).isDirectory()) return; entries=await readdir(p,{withFileTypes:true}); }
21
+ catch { found.push({path:p,kind:'unclassified',incomplete:true}); return; }
22
+ const marked=entries.some(e=>MARKERS.has(e.name));
23
+ const loose=entries.some(e=>!e.isDirectory() && !e.isSymbolicLink() && !e.name.endsWith('.cleandrive-archive.json') && !['.DS_Store'].includes(e.name));
24
+ const children=entries.filter(e=>e.isDirectory() && !GENERATED.has(e.name) && !e.name.startsWith('.'));
25
+ // Marked projects are boundaries; grouping folders retain only residual size.
26
+ if(marked || depth>=depthLimit || !children.length) {
27
+ found.push({path:p,kind:marked?'project':'unclassified',incomplete:protectedPaths.some(pp=>contains(p,pp))}); return;
28
+ }
29
+ const start=found.length;
30
+ for(const e of children) await walk(path.join(p,e.name),depth+1);
31
+ if(loose || entries.some(e=>e.isDirectory() && !children.includes(e))) {
32
+ found.push({path:p,kind:'group',children:found.slice(start).map(x=>x.path).filter(child=>!found.slice(start).some(other=>other.path!==child && contains(other.path,child))),incomplete:true});
33
+ }
34
+ }
35
+ const unique=[...new Set(roots.map(p=>path.resolve(expandHome(p))))].sort((a,b)=>a.length-b.length);
36
+ const covered=[];
37
+ for(const p of unique) { if(covered.some(r=>contains(r,p))) continue; covered.push(p); await walk(p,0); }
38
+ return found;
39
+ }
40
+
41
+ export async function inspectProject(p, cfg = {}, { runner = run, now = Date.now() } = {}) {
42
+ const e={newestSource:null,lastOpened:null,git:null,complete:true,errors:[]};
43
+ let count=0;
44
+ const deadline=Date.now()+(Number(cfg.evidenceTimeoutSec)||15)*1000;
45
+ const protectedPaths=(cfg.protected||[]).map(x=>path.resolve(expandHome(x)));
46
+ async function walk(dir) {
47
+ if(Date.now()>deadline || count>100000) throw new Error('inspection limit reached');
48
+ if(protectedPaths.some(pp=>contains(pp,dir))) throw new Error('protected subtree');
49
+ for(const ent of await readdir(dir,{withFileTypes:true})) {
50
+ count++;
51
+ if(Date.now()>deadline || count>100000) throw new Error('inspection limit reached');
52
+ if(GENERATED.has(ent.name) || ent.name.endsWith('.cleandrive-archive.json') || ent.name==='.DS_Store') continue;
53
+ const f=path.join(dir,ent.name);
54
+ if(ent.isDirectory()) await walk(f);
55
+ else if(ent.isFile()) { const st=await lstat(f); e.newestSource=Math.max(e.newestSource||0,st.mtimeMs); }
56
+ else if(ent.isSymbolicLink()) { e.complete=false; e.errors.push('symlink content not inspected'); }
57
+ }
58
+ }
59
+ try { await walk(p); } catch(err) { e.complete=false; e.errors.push(err.message); }
60
+ const opts={timeoutMs:5000};
61
+ const opened=await runner('mdls',['-raw','-name','kMDItemLastUsedDate',p],opts);
62
+ const t=Date.parse(opened.out.trim());
63
+ if(opened.code===0 && Number.isFinite(t)) e.lastOpened=t;
64
+ e.spotlight=e.lastOpened===null?'unavailable':'available';
65
+ let gitMarker=false;
66
+ try { await lstat(path.join(p,'.git')); gitMarker=true; } catch(err) { if(err.code!=='ENOENT') {e.complete=false;e.errors.push('Git marker unreadable');} }
67
+ if(gitMarker) {
68
+ const status=await runner('git',['--no-optional-locks','-C',p,'status','--porcelain=v1','-z','--untracked-files=normal'],opts);
69
+ const commit=await runner('git',['-C',p,'log','-1','--format=%ct'],opts);
70
+ const timestamp=Number(commit.out.trim())*1000;
71
+ e.git={dirty:status.code===0?status.out.length>0:null,lastCommit:commit.code===0&&timestamp>0?timestamp:null};
72
+ if(status.code!==0 || !e.git.lastCommit) {e.complete=false;e.errors.push('Git inspection incomplete');}
73
+ }
74
+ const latest=Math.max(e.newestSource||0,e.lastOpened||0,e.git?.lastCommit||0);
75
+ e.idleDays=latest?Math.max(0,Math.floor((now-latest)/864e5)):null;
76
+ const stale=Number.isFinite(Number(cfg.staleDays)) && Number(cfg.staleDays)>0?Number(cfg.staleDays):90;
77
+ e.band=isPinned(p,cfg)?'pinned':!e.complete||e.newestSource===null?'unknown':e.git?.dirty?'review':e.idleDays<30?'recent':e.idleDays<stale?'review':'archive-candidate';
78
+ e.suggest=e.band==='archive-candidate'?'archive':'keep';
79
+ e.note=e.band==='pinned'?'keep local (pinned)':e.band==='unknown'?'activity unknown — inspection incomplete':e.git?.dirty?'review — uncommitted or untracked work':`${e.idleDays}d since latest observed activity — ${e.band}`;
80
+ if(e.lastOpened===null) e.note+='; last-opened unavailable';
81
+ return e;
82
+ }
83
+
84
+ // Emit every measured boundary, including small projects. Group rows account
85
+ // only for content not represented by descendants or dependency rows.
86
+ export function projectScanItems(projects, sizes, evidence, dependencies = new Map(), blocked = []) {
87
+ const sizeByPath = new Map(projects.map((entry, i) => [entry.path, sizes[i]]));
88
+ const items = [];
89
+ projects.forEach((entry, i) => {
90
+ const p = entry.path, kb = sizes[i];
91
+ if (!kb) return;
92
+ const activity = { ...evidence[i] };
93
+ if (entry.incomplete || blocked.some(b => b.path === p)) {
94
+ activity.complete = false;
95
+ activity.band = 'unknown';
96
+ activity.suggest = 'keep';
97
+ activity.note = 'activity unknown — inspection incomplete';
98
+ }
99
+ const children = entry.children || [];
100
+ let separatelyListed = children.reduce((sum, child) => sum + (sizeByPath.get(child) || 0), 0);
101
+ for (const [dependency, depKB] of dependencies) {
102
+ if (depKB >= 50 * 1024 && contains(p, dependency)
103
+ && !children.some(child => contains(child, dependency))) separatelyListed += depKB;
104
+ }
105
+ items.push({
106
+ path: p, kb: Math.max(0, kb - separatelyListed), grossKb: kb, kind: entry.kind,
107
+ activity, active: activity.band === 'recent',
108
+ suggest: entry.kind === 'project' ? activity.suggest : 'keep',
109
+ note: (entry.kind === 'group' ? 'grouping folder (remaining content); '
110
+ : entry.kind === 'unclassified' ? 'unclassified folder — manual review; ' : '') + activity.note,
111
+ });
112
+ });
113
+ return items;
114
+ }