agent-cleandrive 0.2.2 → 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 CHANGED
@@ -6,13 +6,13 @@
6
6
  import { createHash } from 'node:crypto';
7
7
  import {
8
8
  createReadStream, lstatSync, statSync, realpathSync, readdirSync, readFileSync, existsSync,
9
- unlinkSync, renameSync, utimesSync, statfsSync,
9
+ unlinkSync, renameSync, utimesSync, statfsSync, openSync, writeFileSync, fsyncSync, closeSync, linkSync,
10
10
  } from 'node:fs';
11
11
  import path from 'node:path';
12
12
  import {
13
- HOME, DATA_DIR, loadConfig, readJson, writeJson, writeFileAtomic, run, ensureDataDir, expandHome,
13
+ HOME, DATA_DIR, loadConfig, readJson, writeJson, writeFileAtomic, run, ensureDataDir, expandHome, withCatalog,
14
14
  } from './util.js';
15
- import { checkRemoteDrive, sshOpts, log } from './actions.js';
15
+ import { checkRemoteDrive, sshOpts, log, remotePathRefusal } from './actions.js';
16
16
 
17
17
  export const STUB_EXT = '.cloud';
18
18
  const INDEX_FILE = path.join(DATA_DIR, 'offloaded.json');
@@ -47,6 +47,8 @@ export function sha256File(p) {
47
47
  function remoteBase(cfg) {
48
48
  const rpath = cfg.remote?.path;
49
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);
50
52
  return rpath.replace(/\/$/, '') + '/offload';
51
53
  }
52
54
  const objectRel = (sha) => `objects/${sha.slice(0, 2)}/${sha}`;
@@ -58,7 +60,10 @@ function ssh(cfg, cmd) {
58
60
  return run('ssh', [...sshBase(cfg), remoteDest(cfg), cmd]);
59
61
  }
60
62
 
61
- function rsyncArgs(cfg) {
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) {
62
67
  return ['--partial', `--timeout=${opt(cfg).timeoutSec}`, '-e', ['ssh', ...sshBase(cfg)].join(' ')];
63
68
  }
64
69
 
@@ -105,17 +110,30 @@ const isPinned = (abs, pins) => pins.some((pp) => abs === pp || abs.startsWith(p
105
110
 
106
111
  // ---------- lock: one offload/fetch run at a time ----------
107
112
 
108
- function acquireLock() {
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() {
109
116
  ensureDataDir();
110
- const cur = readJson(LOCK_FILE);
111
- if (cur?.pid && cur.pid !== process.pid) {
112
- let alive = true;
113
- try { process.kill(cur.pid, 0); } catch { alive = false; }
114
- if (alive) throw new Error(`another offload/fetch run is active (pid ${cur.pid})`);
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;
115
134
  }
116
- writeJson(LOCK_FILE, { pid: process.pid, ts: new Date().toISOString() });
117
135
  }
118
- function releaseLock() {
136
+ export function releaseLock() {
119
137
  const cur = readJson(LOCK_FILE);
120
138
  if (cur?.pid === process.pid) { try { unlinkSync(LOCK_FILE); } catch { /* gone */ } }
121
139
  }
@@ -149,9 +167,35 @@ export function validateSource(abs, cfg, pins = []) {
149
167
  return st;
150
168
  }
151
169
 
152
- async function inUse(abs) {
153
- const r = await run('lsof', ['-t', '--', abs]);
154
- return r.code === 0 && r.out.trim().length > 0;
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);
155
199
  }
156
200
 
157
201
  // Expand dirs to files >= minMB (recursive, pruned like validateSource).
@@ -187,7 +231,7 @@ export function readStub(stubPath) {
187
231
  return j && j.cleandrive === 'offload-stub' && /^[0-9a-f]{64}$/.test(j.sha256 || '') ? j : null;
188
232
  }
189
233
 
190
- function writeStub(abs, meta, cfg) {
234
+ export function writeStub(abs, meta, cfg) {
191
235
  const base = remoteBase(cfg);
192
236
  const stub = {
193
237
  cleandrive: 'offload-stub',
@@ -202,7 +246,10 @@ function writeStub(abs, meta, cfg) {
202
246
  offloadedAt: new Date().toISOString(),
203
247
  howToRestore: `cleandrive fetch ${q(abs + STUB_EXT)} — or by hand: rsync ${remoteDest(cfg)}:${base}/${objectRel(meta.sha256)} ${q(abs)}`,
204
248
  };
205
- writeFileAtomic(abs + STUB_EXT, JSON.stringify(stub, null, 2) + '\n');
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; }
206
253
  return stub;
207
254
  }
208
255
 
@@ -210,6 +257,7 @@ function writeStub(abs, meta, cfg) {
210
257
 
211
258
  async function offloadOne(abs, cfg, idx, { dryRun, onData }) {
212
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`);
213
261
  if (await inUse(abs)) throw new Error('open in another process (lsof) — close it first');
214
262
  onData?.(` hashing ${short(abs)} (${(st.size / 1048576).toFixed(0)} MB)…\n`);
215
263
  const sha = await sha256File(abs);
@@ -241,19 +289,28 @@ async function offloadOne(abs, cfg, idx, { dryRun, onData }) {
241
289
  if (mv.code !== 0) throw new Error('remote rename failed: ' + mv.err.trim());
242
290
  }
243
291
 
244
- // The file must not have changed while we hashed/uploaded.
245
- const now = lstatSync(abs);
246
- if (now.size !== st.size || now.mtimeMs !== st.mtimeMs) throw new Error('file changed during offload — local file kept');
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`);
247
295
 
248
296
  const stub = writeStub(abs, { size: st.size, sha256: sha, mtimeMs: st.mtimeMs }, cfg);
249
297
  const entry = { path: abs, size: st.size, sha256: sha, mtimeMs: st.mtimeMs, object: rel, state: 'offloaded', offloadedAt: stub.offloadedAt };
250
298
  const line = Buffer.from(JSON.stringify({ event: 'offload', ...entry, mac: process.env.USER }) + '\n').toString('base64');
251
299
  const man = await ssh(cfg, `echo ${line} | base64 -d >> ${q(base + '/manifest.jsonl')}`);
252
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`); }
253
304
  idx.files[abs] = entry;
254
305
  saveIndex(idx);
255
306
  unlinkSync(abs);
256
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
+ }));
257
314
  return { path: abs, sha256: sha, size: st.size, dedupe, ok: true };
258
315
  }
259
316
 
@@ -313,6 +370,9 @@ async function fetchOne(stubPath, cfg, idx, { dryRun, onData }) {
313
370
  if (!stub) throw new Error(`${short(stubPath)} is not a cleandrive stub`);
314
371
  const target = stubPath.slice(0, -STUB_EXT.length);
315
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}`);
316
376
 
317
377
  if (existsSync(target)) {
318
378
  // Crash between "stub written" and "original unlinked", or fetched by hand.
@@ -326,27 +386,29 @@ async function fetchOne(stubPath, cfg, idx, { dryRun, onData }) {
326
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`);
327
387
  const drive = await checkRemoteDrive(cfg);
328
388
  if (!drive.ok) throw new Error(drive.msg);
329
- const remoteHash = await remoteSha(cfg, stub.object);
330
- if (!remoteHash) throw new Error(`remote object ${stub.object} missing — see ${remoteBase(cfg)}/manifest.jsonl`);
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`);
331
392
  if (remoteHash !== stub.sha256) throw new Error(`remote copy corrupt (hash ${remoteHash.slice(0, 12)}…) — stub kept`);
332
393
  if (dryRun) return { path: target, size: stub.size, dryRun: true };
333
394
 
334
395
  const tmp = path.join(path.dirname(target), `.${path.basename(target)}.cleandrive-fetch`);
335
396
  onData?.(` ↓ downloading ${(stub.size / 1048576).toFixed(0)} MB…\n`);
336
- const dl = await withRetry(cfg, 'download', () => run('rsync', [...rsyncArgs(cfg), `${remoteDest(cfg)}:${remoteBase(cfg)}/${stub.object}`, tmp]), onData);
397
+ const dl = await withRetry(cfg, 'download', () => run('rsync', [...rsyncArgs(cfg), `${remoteDest(cfg)}:${remoteBase(cfg)}/${object}`, tmp]), onData);
337
398
  if (dl.code !== 0) throw new Error(`download failed after ${opt(cfg).retries} attempts — stub kept (partial ${path.basename(tmp)} resumes next time)`);
338
399
  const h = await sha256File(tmp);
339
400
  if (h !== stub.sha256) {
340
401
  unlinkSync(tmp);
341
402
  throw new Error('downloaded file checksum mismatch — discarded, stub kept');
342
403
  }
343
- renameSync(tmp, target);
404
+ placeExclusive(tmp, target, short(target)); // a file created meanwhile is never overwritten
344
405
  if (stub.mtimeMs) { const t = new Date(stub.mtimeMs); utimesSync(target, t, t); }
345
406
  unlinkSync(stubPath);
346
407
  const prev = idx.files[target] || {};
347
- idx.files[target] = { ...prev, path: target, size: stub.size, sha256: stub.sha256, object: stub.object, state: 'local', fetchedAt: new Date().toISOString() };
408
+ idx.files[target] = { ...prev, path: target, size: stub.size, sha256: stub.sha256, object, state: 'local', fetchedAt: new Date().toISOString() };
348
409
  saveIndex(idx);
349
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() }));
350
412
  return { path: target, size: stub.size, ok: true };
351
413
  }
352
414
 
@@ -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
+ }
package/lib/scan.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { existsSync, readdirSync, statSync } from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { discoverProjects, inspectProject, projectScanItems } from './projects.js';
3
4
  import {
4
5
  HOME, DATA_DIR, expandHome, loadConfig, idFor, ensureDataDir, writeJson, run, pool,
5
6
  } from './util.js';
@@ -15,10 +16,10 @@ export const CATEGORIES = {
15
16
  models: { label: 'AI models', risk: 'review', desc: 'Local model weights. Remove via the owning tool (e.g. ollama rm).' },
16
17
  };
17
18
 
18
- const APP_ROOTS = ['/Applications', '~/Applications'];
19
+ export const APP_ROOTS = ['/Applications', '~/Applications'];
19
20
 
20
21
  // Package caches that have a proper clean command
21
- const PKG_CACHES = [
22
+ export const PKG_CACHES = [
22
23
  { p: '~/.cache/uv', cmd: 'uv cache clean', label: 'uv package cache' },
23
24
  { p: '~/.npm', cmd: 'npm cache clean --force', label: 'npm cache' },
24
25
  { p: '~/Library/Caches/Homebrew', cmd: 'brew cleanup -s --prune=all', label: 'Homebrew downloads' },
@@ -27,7 +28,7 @@ const PKG_CACHES = [
27
28
  { p: '~/.pub-cache', cmd: null, label: 'dart pub cache' },
28
29
  ];
29
30
 
30
- const APPDATA_ROOTS = [
31
+ export const APPDATA_ROOTS = [
31
32
  '~/Library/Application Support',
32
33
  '~/Library/Group Containers',
33
34
  '~/Library/Containers',
@@ -61,12 +62,6 @@ async function dfData() {
61
62
  return { sizeKB, usedKB, availKB, pct: Math.round((usedKB / sizeKB) * 100) };
62
63
  }
63
64
 
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
65
  function safeStatMtime(p) {
71
66
  try { return statSync(p).mtimeMs; } catch { return 0; }
72
67
  }
@@ -84,7 +79,7 @@ function listDirs(root) {
84
79
  export async function runScan(onProgress = () => {}) {
85
80
  ensureDataDir();
86
81
  const cfg = loadConfig();
87
- const staleDays = cfg.staleDays ?? 60;
82
+ const staleDays = cfg.staleDays ?? 90;
88
83
  blocked = [];
89
84
  duTimeoutMs = (cfg.duTimeoutSec ?? 60) * 1000;
90
85
  const minCacheKB = (cfg.minCacheMB ?? 100) * 1024;
@@ -142,27 +137,15 @@ export async function runScan(onProgress = () => {}) {
142
137
  if (kb >= 50 * 1024) add(p, 'node_modules', { kb, suggest: 'rm', note: 'reinstall with the project\'s package manager' });
143
138
  }
144
139
 
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
- });
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
+ }
166
149
 
167
150
  // 5. Large app data (review only)
168
151
  onProgress('scanning app data');
@@ -191,7 +174,7 @@ export async function runScan(onProgress = () => {}) {
191
174
  // the bundle's Info.plist / executable (survives when Spotlight has no usage record).
192
175
  const r = await run('mdls', ['-raw', '-name', 'kMDItemLastUsedDate', p]);
193
176
  const v = r.out.trim();
194
- if (v && v !== '(null)') return v;
177
+ if (v && Number.isFinite(Date.parse(v))) return v;
195
178
  const a = await run('stat', ['-f', '%a', path.join(p, 'Contents', 'Info.plist')]);
196
179
  const secs = parseInt(a.out.trim(), 10);
197
180
  return Number.isFinite(secs) ? new Date(secs * 1000).toISOString() : null;
package/lib/server.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import http from 'node:http';
2
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
3
+ import { listArchives } from './archives.js';
2
4
  import { readFileSync, existsSync } from 'node:fs';
3
5
  import path from 'node:path';
4
6
  import { ROOT, DATA_DIR, loadConfig, saveConfig, readJson, fmtGB, run } from './util.js';
5
7
  import { runScan } from './scan.js';
6
- import { loadPlan, setPlanItem, setPlanItems, approvedItems, executeItem, testRemote, archive, log } from './actions.js';
8
+ import { loadPlan, setPlanItem, setPlanItems, approvedItems, executeItem, testRemote, archive, log, actionRefusal, scanItem } from './actions.js';
7
9
  import { offloadPaths, fetchPaths, listOffloaded, findCandidates, loadCandidates, setPin } from './offload.js';
8
10
 
9
11
  const state = {
@@ -30,6 +32,17 @@ async function dfNow() {
30
32
  return { sizeKB, usedKB, availKB, pct: Math.round((usedKB / sizeKB) * 100) };
31
33
  }
32
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
+
33
46
  async function handleApi(req, res, url, body) {
34
47
  const send = (code, obj) => {
35
48
  res.writeHead(code, { 'Content-Type': 'application/json' });
@@ -40,6 +53,7 @@ async function handleApi(req, res, url, body) {
40
53
  const scan = readJson(path.join(DATA_DIR, 'latest.json'));
41
54
  return send(200, {
42
55
  scan,
56
+ archives: listArchives(),
43
57
  plan: loadPlan(),
44
58
  config: loadConfig(),
45
59
  disk: await dfNow(),
@@ -64,6 +78,8 @@ async function handleApi(req, res, url, body) {
64
78
  if (req.method === 'POST' && url.pathname === '/api/plan') {
65
79
  const { id, status, action, reviewed } = body || {};
66
80
  if (!id) return send(400, { error: 'id required' });
81
+ const why = approvalRefusal(id, status, action);
82
+ if (why) return send(409, { error: why });
67
83
  return send(200, setPlanItem(id, {
68
84
  ...(status && { status }),
69
85
  ...(action && { action }),
@@ -74,7 +90,9 @@ async function handleApi(req, res, url, body) {
74
90
  if (req.method === 'POST' && url.pathname === '/api/plan/bulk') {
75
91
  const changes = Array.isArray(body?.changes) ? body.changes : [];
76
92
  if (!changes.length) return send(400, { error: 'changes required' });
77
- return send(200, setPlanItems(changes));
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 });
78
96
  }
79
97
 
80
98
  if (req.method === 'POST' && url.pathname === '/api/execute') {
@@ -123,7 +141,7 @@ async function handleApi(req, res, url, body) {
123
141
  for (const item of items) {
124
142
  pushLog(`▶ dry-run archive: ${item.path}`);
125
143
  try {
126
- const r = await archive(item, { dryRun: true, onData: pushLog });
144
+ const r = await archive(item, { dryRun: true, removeLocal: item.plannedAction === 'archive+rm', onData: pushLog });
127
145
  pushLog(r.ok ? '✓ dry-run ok' : `✗ ${r.output.split('\n').pop()}`);
128
146
  } catch (e) { pushLog(`✗ ${e.message}`); }
129
147
  }
@@ -175,10 +193,38 @@ async function handleApi(req, res, url, body) {
175
193
  send(404, { error: 'not found' });
176
194
  }
177
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
+
178
218
  export function serve() {
179
219
  const cfg = loadConfig();
180
220
  const port = cfg.port || 4499;
221
+ const token = randomBytes(24).toString('hex');
181
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
+ }
182
228
  const url = new URL(req.url, `http://127.0.0.1:${port}`);
183
229
  if (url.pathname.startsWith('/api/')) {
184
230
  let raw = '';
@@ -195,8 +241,15 @@ export function serve() {
195
241
  }
196
242
  const ui = path.join(ROOT, 'ui', 'index.html');
197
243
  if (url.pathname === '/' && existsSync(ui)) {
198
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
199
- return res.end(readFileSync(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);
200
253
  }
201
254
  res.writeHead(404);
202
255
  res.end('not found');
package/lib/util.js CHANGED
@@ -93,6 +93,22 @@ export function run(cmd, args = [], opts = {}) {
93
93
  });
94
94
  }
95
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
+
96
112
  // Run through a login zsh so PATH includes homebrew/uv/etc.
97
113
  export function runShell(cmdline, opts = {}) {
98
114
  return run('zsh', ['-lc', cmdline], opts);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-cleandrive",
3
- "version": "0.2.2",
3
+ "version": "0.3.2",
4
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
5
  "type": "module",
6
6
  "bin": {