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/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  # 🧹 agent-cleandrive
4
4
 
5
+ <img src="media/illustration.jpg" width="420" alt="A small robot sorts the clutter spilling out of a laptop into labelled crates (caches, cables, boxes, containers) while a cart carries a crate along a dashed path to a home server">
6
+
5
7
  ### The disk cleaner your AI agent can't misuse.
6
8
 
7
9
  **Your agent proposes the cleanup, you approve it, and the tool enforces the rules: a project can never be deleted, only archived and verified.**
@@ -11,6 +13,7 @@ verification, or offload big videos iCloud-style. Works with Claude Code, Codex,
11
13
  <sub>Built for, and on, an 8 GB MacBook Air that runs several Claude Code sessions a day.</sub>
12
14
 
13
15
  [![tests](https://github.com/kaiser-data/agent-cleandrive/actions/workflows/test.yml/badge.svg)](https://github.com/kaiser-data/agent-cleandrive/actions/workflows/test.yml)
16
+ [![npm](https://img.shields.io/npm/v/agent-cleandrive?logo=npm)](https://www.npmjs.com/package/agent-cleandrive)
14
17
  ![dependencies](https://img.shields.io/badge/dependencies-0-brightgreen)
15
18
  ![node](https://img.shields.io/badge/node-%E2%89%A520-339933?logo=node.js&logoColor=white)
16
19
  ![platform](https://img.shields.io/badge/macOS-today-000000?logo=apple&logoColor=white) ![linux](https://img.shields.io/badge/Linux-next-lightgrey?logo=linux&logoColor=white)
@@ -84,7 +87,7 @@ manages disk only; it doesn't touch RAM or running processes.
84
87
  |---|---|---|
85
88
  | **Claude Code plugin** | `/plugin install cleandrive --marketplace kaiser-data/agent-cleandrive` | `~/.config/cleandrive/` |
86
89
  | **npm** | `npm i -g agent-cleandrive` → command `cleandrive` (or `npx agent-cleandrive …`) | `~/.config/cleandrive/` |
87
- | **git clone** | `git clone https://github.com/kaiser-data/agent-cleandrive && cd cleandrive && cp config.example.json config.json` | the repo (`config.json`, `data/`) |
90
+ | **git clone** | `git clone https://github.com/kaiser-data/agent-cleandrive && cd agent-cleandrive && cp config.example.json config.json` | the repo (`config.json`, `data/`) |
88
91
 
89
92
  Needs macOS and Node ≥ 20 (Linux support is next on the roadmap). **No dependencies:** pure Node stdlib plus the system's `du`, `rsync`
90
93
  and `ssh`. On first run it writes a default `config.json`. Point `projectRoots` at your
@@ -123,7 +126,7 @@ and **[covered by tests](test/safety.test.mjs)** that run against a fake `$HOME`
123
126
  entries are ignored.
124
127
  - **`rm` is category-gated.** It works only for `pkgcache`, `cache`, `node_modules`, and for
125
128
  `appdata`/`models` after an explicit review. A project can leave only via `archive+rm`.
126
- - **Archive, verify, then delete.** `rsync -aHR` to the remote, then a second `rsync -c` checksum
129
+ - **Archive, verify, then delete.** `rsync -aH` to the remote, then a second `rsync -c` checksum
127
130
  pass. The local copy goes only if that pass reports zero content differences.
128
131
  - **The drive must really be there.** Before every archive or offload, the tool checks over SSH
129
132
  that `remote.path` sits on the expected drive (`remote.uuid`), not on an empty mount point on the
@@ -214,27 +217,30 @@ These shaped the code and the [skill](skills/cleandrive/SKILL.md).
214
217
  | Command | What it does |
215
218
  |---|---|
216
219
  | `scan [--json]` | Rescan, categorize, write `data/latest.json` |
217
- | `state [--json]` | Current scan and plan, with item ids |
220
+ | `state [--json]` | Current scan and plan, with item ids and project activity |
221
+ | `archives [search] [--json]` | Search recorded project archives |
222
+ | `restore <id\|receipt.json> [--dry-run]` | Verify and restore a project to an absent original path |
218
223
  | `serve` | Dashboard at `http://localhost:4499` |
219
224
  | `approve <id…> [--action=rm\|clean\|archive\|archive+rm]` | Approve items |
220
225
  | `skip <id…>` · `review <id…>` | Skip items · mark reviewed (unlocks rm for `appdata`/`models`) |
221
226
  | `execute [--dry-run]` | Run all approved actions |
222
227
  | `remote-test` | SSH reachability, drive mounted, free space |
223
- | `offload-dryrun` | `rsync -n` the approved archive items |
228
+ | `offload-dryrun` | Pre-flight the approved archive items (drive mounted, room) without copying |
224
229
  | `offload-candidates [--min=200] [--days=30]` | Big idle media and duplicates (read-only) |
225
230
  | `offload <file\|dir…> [--dry-run]` | Verified upload, leaves `<name>.cloud` |
226
231
  | `fetch <file\|stub\|dir…> [--dry-run]` | Restore offloaded files, sha256-verified |
227
232
  | `offloaded` · `offload-verify` · `pin <path>` | List · re-hash every remote copy · keep a path local |
233
+ | `catalog [search] \| sync \| stats` | SQLite index of archives and offloads (needs Node ≥ 22.13; everything else runs on Node 20) |
228
234
 
229
235
  ## Remote drive setup
230
236
 
231
237
  1. Attach a drive to any Linux machine you can SSH into: a Raspberry Pi, a Jetson, a NAS, an old
232
238
  laptop. Tailscale makes it reachable from anywhere without opening ports.
233
- 2. Set `remote.host`, `remote.user`, `remote.path` and, ideally, `remote.uuid` (from `findmnt -n -o UUID -T <path>`) in `config.json`, or in the dashboard's remote card.
239
+ 2. Set `remote.host`, `remote.user`, `remote.path` and, ideally, `remote.uuid` (from `findmnt -n -o UUID -T <path>`) in `config.json`, or in the dashboard's remote card. `remote.path` may contain only letters, digits and `._/+@%=,-` (no spaces): it is passed to the remote shell unquoted, which keeps the stock macOS `rsync` working.
234
240
  3. Run `cleandrive remote-test`. It must report the drive as mounted.
235
241
 
236
- Archives keep each item's path relative to your home folder, so the remote mirrors your Mac's
237
- layout and restores are obvious.
242
+ New project archives use unique version directories. Their receipts retain the original Mac path
243
+ and restore instructions; use `cleandrive archives` to find them.
238
244
 
239
245
  ---
240
246
 
@@ -255,7 +261,7 @@ test/ safety-model tests (node:test, fake $HOME)
255
261
  ## Development
256
262
 
257
263
  ```bash
258
- npm test # 15 tests, ~0.3 s, never touches your real home folder
264
+ npm test # 49 tests, ~1 s, never touches your real home folder
259
265
  ```
260
266
 
261
267
  **Roadmap** ([PLAN.md](PLAN.md)): **Linux support** (XDG caches, Docker images, journald, snap revisions) · MCP server for non-CLI agents · item lifecycle and checkbox selection in the dashboard ·
@@ -271,3 +277,82 @@ MIT licensed · built by [Martin Kaiser](https://github.com/kaiser-data) with [C
271
277
  **Clean without fear.**
272
278
 
273
279
  </div>
280
+
281
+ ### Project activity and discoverable archives
282
+
283
+ A scan now discovers projects inside grouping folders, stopping at project markers
284
+ such as `.git`, `package.json`, and `pyproject.toml`. `projectDepth` defaults to 3.
285
+ Loose files remain visible as a grouping folder's remaining content; grouping
286
+ folders themselves cannot be approved for cleanup. Project sizes exclude separately
287
+ listed dependencies, while archive space checks use the full project size.
288
+
289
+ Activity evidence includes meaningful source edits, Git commits, dirty/untracked
290
+ work, and Spotlight last-opened information when available. Generated directories
291
+ such as `node_modules`, `.venv`, `.git`, and build output do not establish activity.
292
+ They are still included in an archive. Missing Spotlight metadata is shown as
293
+ unavailable; failed source/Git inspection yields **unknown**, never inactive.
294
+ Scans inspect at most 100,000 entries per project and default to a 15-second
295
+ inspection budget (`evidenceTimeoutSec`). These are observations, not proof that a
296
+ project is unused.
297
+
298
+ Defaults are **recent (<30 days)**, **review (30–89 days)**, and **archive candidate
299
+ (90+ days)**. An explicit existing `staleDays` overrides the archive threshold.
300
+ Dirty/untracked work and unclassified folders need manual review. `cleandrive pin
301
+ <project>` keeps the project local; unpin explicitly before approving removal.
302
+ Pinning a descendant also prevents removal of its ancestor.
303
+
304
+ Every new project archive has a unique directory on the configured remote:
305
+ `<remote.path>/archives/<id>/payload`. Earlier versions are never overwritten.
306
+ The catalog is stored in `data/archives/` under cleandrive's config/data directory;
307
+ the remote version contains its own `receipt.json`. An archive-and-remove action
308
+ also leaves `<project>.cleandrive-archive.json` beside the former project location.
309
+ Receipts preserve the original path, exact remote location, content hash,
310
+ verification date, and restore instructions.
311
+
312
+ ```bash
313
+ cleandrive archives # list project archives
314
+ cleandrive archives hackathon --json # search for a project
315
+ cleandrive restore <archive-id> --dry-run
316
+ cleandrive restore <archive-id>
317
+ # If the local catalog was lost, use the sibling or remote receipt:
318
+ cleandrive restore /path/project.cleandrive-archive.json
319
+ ```
320
+
321
+ Restore downloads into a temporary sibling, checks the remote contents and receipt
322
+ hash, and publishes only to an absent original path. An existing destination,
323
+ including an empty directory or dangling symlink, is refused. The original parent
324
+ must exist. Failed staging remains available at the path printed in the error.
325
+ Restoring never deletes the remote version. These receipts are explicit recovery
326
+ instructions, not Finder placeholders that download automatically. Old archives
327
+ without receipts remain on the remote but are not inferred into the new catalog.
328
+
329
+ Keep a project quiescent during archive-and-remove: close its editors, development
330
+ servers, and other processes. Open-file checks, source fingerprints, drive identity,
331
+ checksums, and successful receipt writes gate local removal. These checks are not
332
+ an atomic filesystem snapshot. External/absolute symlinks require review and are
333
+ refused; a linked Git worktree cannot be removed because its external metadata is
334
+ not self-contained. Remote storage is expected to be Linux, including `sync -f`
335
+ for flushing receipt and payload writes before local removal.
336
+
337
+ An interrupted process may leave `data/archives.lock`. Check that its recorded PID
338
+ is no longer running and review the archive receipts before removing the stale
339
+ lock. `removal-interrupted` or `removal-failed` means inspect both copies; do not
340
+ assume the remaining local directory is complete.
341
+
342
+ ### Archive storage versus backup
343
+
344
+ **Transfer verified** means the archive matched when copied. **Independent backup:
345
+ unknown** means cleandrive has not verified a second copy on another storage device.
346
+ A second directory on the same remote drive is not an independent backup. The dashboard and
347
+ CLI keep these facts separate; they do not claim that an old archive is currently
348
+ healthy without another verification.
349
+
350
+ Recommended workflow: back up active Mac work with versioned snapshots; copy a
351
+ finished project to the remote drive with `archive`; back that drive up to a separate
352
+ physical disk or offsite destination and test recovery; only then approve local
353
+ removal. Each new `archive+rm` makes another version, so ensure your independent
354
+ backup covers the same contents before removal. This release does not enforce
355
+ that second-copy policy or schedule backups. Keep the catalog, receipts, and
356
+ configuration in your independent backup as well. A reasonable starting retention
357
+ policy is 7 daily, 4 weekly, and 12 monthly snapshots, with monthly integrity checks
358
+ and test restores.
package/bin/cleandrive.js CHANGED
@@ -2,10 +2,11 @@
2
2
  // cleandrive — scan disk, plan cleanup, clean caches, archive to remote over SSH/Tailscale.
3
3
  // This CLI is also the Claude Code connector: every command supports --json where useful.
4
4
  import path from 'node:path';
5
- import { DATA_DIR, readJson, fmtGB, loadConfig } from '../lib/util.js';
5
+ import { listArchives, restoreArchive } from '../lib/archives.js';
6
+ import { DATA_DIR, readJson, fmtGB, loadConfig, loadCatalog } from '../lib/util.js';
6
7
  import { runScan, CATEGORIES } from '../lib/scan.js';
7
8
  import { serve } from '../lib/server.js';
8
- import { loadPlan, setPlanItem, approvedItems, executeItem, testRemote, archive } from '../lib/actions.js';
9
+ import { loadPlan, setPlanItem, approvedItems, executeItem, testRemote, archive, actionRefusal, scanItem } from '../lib/actions.js';
9
10
  import { offloadPaths, fetchPaths, listOffloaded, findCandidates, verifyRemote, setPin } from '../lib/offload.js';
10
11
 
11
12
  const [, , cmd, ...args] = process.argv;
@@ -48,12 +49,36 @@ function printState() {
48
49
  for (const i of items.slice(0, 15)) {
49
50
  const st = plan.items[i.id]?.status || '·';
50
51
  console.log(` [${st.padEnd(8)}] ${i.id} ${fmtGB(i.kb).padStart(8)} ${i.suggest.padEnd(10)} ${i.path.replace(process.env.HOME, '~')}`);
52
+ if (i.activity) console.log(` ${i.note}`);
51
53
  }
52
54
  if (items.length > 15) console.log(` … ${items.length - 15} more`);
53
55
  }
54
56
  }
55
57
 
56
58
  switch (cmd) {
59
+ case 'archives': {
60
+ const records = listArchives(positional().join(' '));
61
+ if (flag('--json')) console.log(JSON.stringify(records, null, 2));
62
+ else {
63
+ console.log(`${records.length} project archive(s); independent backup status is unknown`);
64
+ for (const r of records) {
65
+ console.log(`${r.id} ${r.state} ${fmtGB(r.bytes / 1024)} ${r.originalPath}`);
66
+ console.log(` ${r.remote.host}:${r.remotePath}`);
67
+ console.log(` transfer ${r.verification.status} ${r.verification.checkedAt}; restore: cleandrive restore ${r.id}`);
68
+ }
69
+ }
70
+ break;
71
+ }
72
+ case 'restore': {
73
+ const [ref] = positional();
74
+ if (!ref) { console.error('usage: cleandrive restore <archive-id|receipt.json> [--dry-run]'); process.exitCode = 2; break; }
75
+ try {
76
+ const result = await restoreArchive(ref, { dryRun: flag('--dry-run'), onData: out });
77
+ console.log(result.output);
78
+ } catch (e) { console.error(e.message); process.exitCode = 1; }
79
+ break;
80
+ }
81
+
57
82
  case 'scan': {
58
83
  console.error('scanning…');
59
84
  const scan = await runScan((s) => console.error(' ' + s));
@@ -70,7 +95,12 @@ switch (cmd) {
70
95
  case 'approve': {
71
96
  const ids = args.filter((a) => !a.startsWith('--'));
72
97
  const action = (args.find((a) => a.startsWith('--action=')) || '').split('=')[1];
98
+ const plan = loadPlan();
73
99
  for (const id of ids) {
100
+ const it = scanItem(id);
101
+ if (!it) { console.log(`✗ ${id}: not in the current scan`); process.exitCode = 1; continue; }
102
+ const why = actionRefusal({ ...it, reviewed: plan.items[id]?.reviewed === true }, action || it.suggest);
103
+ if (why) { console.log(`✗ refused ${id} (${it.path}): ${why}`); process.exitCode = 1; continue; }
74
104
  setPlanItem(id, { status: 'approved', ...(action && { action }) });
75
105
  console.log(`approved ${id}${action ? ' → ' + action : ''}`);
76
106
  }
@@ -93,13 +123,20 @@ switch (cmd) {
93
123
  if (!items.length) { console.log('nothing approved'); break; }
94
124
  const dry = flag('--dry-run');
95
125
  for (const item of items) {
96
- console.log(`${dry ? '[dry-run] would' : '▶'} ${item.plannedAction}: ${item.path} (${fmtGB(item.kb)})`);
97
- if (dry) continue;
126
+ const why = actionRefusal(item);
127
+ if (dry) {
128
+ console.log(why ? `[dry-run] ✗ refused ${item.plannedAction}: ${item.path} — ${why}`
129
+ : `[dry-run] would ${item.plannedAction}: ${item.path} (${fmtGB(item.kb)})`);
130
+ continue;
131
+ }
132
+ console.log(`▶ ${item.plannedAction}: ${item.path} (${fmtGB(item.kb)})`);
98
133
  try {
99
134
  const r = await executeItem(item, { onData: (d) => process.stderr.write(d) });
100
135
  console.log(r.ok ? ' ✓ done' : ` ✗ failed: ${r.output.split('\n').pop()}`);
136
+ if (!r.ok) process.exitCode = 1;
101
137
  } catch (e) {
102
138
  console.log(` ✗ refused: ${e.message}`);
139
+ process.exitCode = 1;
103
140
  }
104
141
  }
105
142
  break;
@@ -108,7 +145,7 @@ switch (cmd) {
108
145
  const items = approvedItems().filter((i) => (i.plannedAction || '').startsWith('archive'));
109
146
  for (const item of items) {
110
147
  console.log(`dry-run: ${item.path}`);
111
- const r = await archive(item, { dryRun: true, onData: (d) => process.stderr.write(d) });
148
+ const r = await archive(item, { dryRun: true, removeLocal: item.plannedAction === 'archive+rm', onData: (d) => process.stderr.write(d) });
112
149
  console.log(r.ok ? ' ✓ ok' : ` ✗ ${r.output}`);
113
150
  }
114
151
  break;
@@ -166,18 +203,66 @@ switch (cmd) {
166
203
  process.exit(r.ok ? 0 : 1);
167
204
  break;
168
205
  }
206
+ case 'catalog': {
207
+ // node:sqlite needs Node >= 22.13; the rest of the CLI must keep working without it.
208
+ const C = await loadCatalog();
209
+ if (!C) { console.error(`catalog needs Node >= 22.13 (node:sqlite); this is Node ${process.versions.node}`); process.exit(1); }
210
+ const { all: catalogAll, search: catalogSearch, stats: catalogStats, sync: catalogSync, syncRemote: catalogSyncRemote, closeDb } = C;
211
+ const sub = positional()[0];
212
+ if (sub === 'sync') {
213
+ const local = catalogSync({ onData: out });
214
+ if (flag('--remote')) {
215
+ const remote = await catalogSyncRemote({ onData: out });
216
+ console.log(`sync done: ${local.added + remote.added} added, ${local.updated} updated`);
217
+ } else {
218
+ console.log(`sync done: ${local.added} added, ${local.updated} updated`);
219
+ }
220
+ } else if (sub === 'stats') {
221
+ const s = catalogStats();
222
+ if (flag('--json')) { console.log(JSON.stringify(s, null, 2)); break; }
223
+ console.log(`catalog: ${s.total.n} items, ${fmtGB(s.total.bytes / 1024)} total`);
224
+ console.log(`\nby type:`);
225
+ for (const r of s.byType) console.log(` ${r.type.padEnd(10)} ${String(r.n).padStart(4)} items ${fmtGB(r.bytes / 1024).padStart(8)}`);
226
+ console.log(`\nby state:`);
227
+ for (const r of s.byState) console.log(` ${r.state.padEnd(18)} ${String(r.n).padStart(4)} items ${fmtGB(r.bytes / 1024).padStart(8)}`);
228
+ console.log(`\non remote: ${s.onRemote.n} items, ${fmtGB(s.onRemote.bytes / 1024)}`);
229
+ } else {
230
+ const query = positional().join(' ');
231
+ const items = query ? catalogSearch(query) : catalogAll(
232
+ Object.fromEntries([['type', '--type'], ['state', '--state']].map(
233
+ ([k, f]) => [k, (args.find((a) => a.startsWith(f + '=')) || '').split('=')[1] || '']
234
+ ).filter(([, v]) => v))
235
+ );
236
+ if (flag('--json')) { console.log(JSON.stringify(items, null, 2)); break; }
237
+ if (!items.length) { console.log('catalog empty — run: cleandrive catalog sync'); break; }
238
+ if (flag('--compact')) {
239
+ for (const it of items) console.log(`${it.local_path.replace(process.env.HOME, '~')}\t${fmtGB(it.size_bytes / 1024)}\t${it.state}\t${it.type}`);
240
+ } else {
241
+ console.log(`${items.length} item(s) on the remote drive:\n`);
242
+ for (const it of items) {
243
+ const lp = it.local_path.replace(process.env.HOME, '~');
244
+ console.log(` [${it.type.padEnd(7)}] ${it.state.padEnd(18)} ${fmtGB(it.size_bytes / 1024).padStart(8)} ${lp}`);
245
+ console.log(` ${it.remote_host}:${it.remote_path}`);
246
+ }
247
+ }
248
+ }
249
+ closeDb();
250
+ break;
251
+ }
169
252
  default:
170
253
  console.log(`cleandrive — disk cleanup planner & executor
171
254
 
172
255
  usage:
173
256
  cleandrive scan [--json] scan disk, categorize, write data/latest.json
257
+ cleandrive archives [search] [--json] search verified project archive records
258
+ cleandrive restore <id|receipt.json> [--dry-run] restore a project without overwriting
174
259
  cleandrive state [--json] show latest scan + plan status
175
260
  cleandrive serve start dashboard on http://localhost:${loadConfig().port || 4499}
176
261
  cleandrive approve <id…> [--action=rm|clean|archive|archive+rm]
177
262
  cleandrive skip <id…>
178
263
  cleandrive review <id…> mark reviewed (unlocks rm for appdata/models)
179
264
  cleandrive execute [--dry-run] run all approved actions
180
- cleandrive offload-dryrun rsync -n approved archive items to remote
265
+ cleandrive offload-dryrun pre-flight approved archive items (drive, room)
181
266
  cleandrive remote-test check SSH reachability of configured remote
182
267
 
183
268
  offload (iCloud-style switch to the remote drive, see docs/offload-strategy.md):
@@ -186,5 +271,10 @@ offload (iCloud-style switch to the remote drive, see docs/offload-strategy.md):
186
271
  cleandrive offloaded [--json] what is offloaded / back local
187
272
  cleandrive offload-candidates [--min=200] [--days=30] [--all-types] [--no-dupes] [--json]
188
273
  cleandrive offload-verify re-hash remote copies (scrub)
189
- cleandrive pin|unpin <path…> keep local / never propose`);
274
+ cleandrive pin|unpin <path…> keep local / never propose
275
+
276
+ catalog (SQLite index of everything on the remote drive; Node >= 22.13):
277
+ cleandrive catalog [search] [--type=offload|archive] [--state=…] [--json]
278
+ cleandrive catalog sync [--remote] rebuild from local JSON + optionally pull remote manifest
279
+ cleandrive catalog stats [--json] summary: items by type, state, total size`);
190
280
  }
@@ -1,6 +1,8 @@
1
1
  {
2
2
  "port": 4499,
3
- "staleDays": 60,
3
+ "staleDays": 90,
4
+ "projectDepth": 3,
5
+ "evidenceTimeoutSec": 15,
4
6
  "minCacheMB": 100,
5
7
  "minAppDataMB": 500,
6
8
  "projectRoots": [
package/lib/actions.js CHANGED
@@ -1,5 +1,8 @@
1
- import { appendFileSync, existsSync } from 'node:fs';
1
+ import { appendFileSync, existsSync, lstatSync } from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { archiveProject } from './archives.js';
4
+ import { isPinned, contains } from './projects.js';
5
+ import { PKG_CACHES, APPDATA_ROOTS } from './scan.js';
3
6
  import {
4
7
  HOME, DATA_DIR, loadConfig, readJson, writeJson, run, runShell, ensureDataDir,
5
8
  } from './util.js';
@@ -55,10 +58,14 @@ function latestScan() {
55
58
 
56
59
  // A path is only actionable if it came out of the scan (allowlist by construction),
57
60
  // lives under $HOME, and is not a protected root.
58
- function validateTarget(item) {
59
- const p = path.resolve(item.path);
61
+ export function validateTarget(item) {
62
+ const p = path.resolve(item.path.replace(/^~(?=$|\/)/, HOME));
60
63
  if (!p.startsWith(HOME + path.sep)) throw new Error(`refusing: ${p} is outside ${HOME}`);
61
64
  if (p.includes('..')) throw new Error('refusing: path traversal');
65
+ for (let cursor = p; cursor !== path.dirname(cursor); cursor = path.dirname(cursor)) {
66
+ try { if (lstatSync(cursor).isSymbolicLink()) throw new Error('refusing: symlink target or ancestor'); }
67
+ catch (e) { if (e.code !== 'ENOENT') throw e; }
68
+ }
62
69
  if (DENY.includes(p)) throw new Error(`refusing: ${p} is a protected directory`);
63
70
  const cfg = loadConfig();
64
71
  const protectedPaths = (cfg.protected || []).map((x) => path.resolve(x.replace(/^~/, HOME)));
@@ -66,19 +73,13 @@ function validateTarget(item) {
66
73
  // from the protected lock (subpaths of them are NOT — only the listed dir).
67
74
  const extraCaches = new Set((cfg.extraCaches || []).map((x) => path.resolve(x.replace(/^~/, HOME))));
68
75
  for (const pp of protectedPaths) {
69
- if ((p === pp || p.startsWith(pp + path.sep)) && !extraCaches.has(p)) {
76
+ if ((contains(pp, p) || contains(p, pp)) && !extraCaches.has(p)) {
70
77
  throw new Error(`refusing: ${p} is user-protected (config.protected)`);
71
78
  }
72
79
  }
73
80
  return p;
74
81
  }
75
82
 
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
83
  // Extra ssh flags from config.remote (custom identity file / non-22 port).
83
84
  // sshKey is expanded from ~ and validated to exist so a typo fails loudly.
84
85
  export function sshOpts(cfg) {
@@ -93,12 +94,6 @@ export function sshOpts(cfg) {
93
94
  return opts;
94
95
  }
95
96
 
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
97
  // The archive path must live on the real archive drive, not on an empty mount
103
98
  // point of the remote's system disk (drive unplugged / not mounted). With
104
99
  // remote.uuid set, the filesystem holding remote.path must have that UUID;
@@ -114,6 +109,7 @@ export async function checkRemoteDrive(cfg, needKB = 0) {
114
109
  const [fsUuid, target, avail] = r.out.trim().split(/\s+/);
115
110
  if (r.code !== 0 || !target) return { ok: false, reachable: true, mounted: false, msg: `archive path ${rpath} not found — is the archive drive mounted?` };
116
111
  const freeKB = Math.floor(Number(avail) / 1024);
112
+ if (!Number.isFinite(freeKB) || freeKB < 0) return { ok: false, reachable: true, mounted: false, msg: 'archive free space could not be verified' };
117
113
  const mounted = uuid ? fsUuid === uuid : target !== '/';
118
114
  if (!mounted) {
119
115
  return { ok: false, reachable: true, mounted, freeKB, msg: `archive drive not mounted: ${rpath} is on ${target} (uuid ${fsUuid || '?'})${uuid ? `, expected uuid ${uuid}` : ''}` };
@@ -131,39 +127,98 @@ export async function testRemote() {
131
127
  try { return await checkRemoteDrive(cfg); } catch (e) { return { ok: false, reachable: false, mounted: false, msg: e.message }; }
132
128
  }
133
129
 
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`) };
130
+ // Project archives use versioned destinations and durable recovery receipts.
131
+ export async function archive(item, options = {}) {
132
+ const remote = loadConfig().remote;
133
+ if (!remote?.host || !remote?.path) throw new Error('remote not configured');
134
+ return archiveProject(item, options);
135
+ }
136
+
137
+ const EXECUTABLE = new Set(['clean', 'rm', 'archive', 'archive+rm']);
138
+
139
+ // latest.json is a plain file anyone with shell access can edit, so its category
140
+ // and cleanCmd are not trusted: re-derive both from the path, using the same
141
+ // source lists the scan uses. A row relabelled to a deletable category (or with
142
+ // a rewritten cleanCmd) is refused instead of executed.
143
+ const exp = (p) => path.resolve(p.replace(/^~(?=$|\/)/, HOME));
144
+ // Remote paths reach the remote shell (rsync without -s, ssh commands), so remote.path is
145
+ // limited to shell-inert characters: no quoting is ever needed, and every rsync works
146
+ // (stock macOS openrsync has no -s/--protect-args; rsync >=3.2.4 escapes args itself).
147
+ export const SAFE_REMOTE_PATH = /^\/[A-Za-z0-9._\/+@%=,-]*$/;
148
+ export function remotePathRefusal(p) {
149
+ if (typeof p !== 'string' || !SAFE_REMOTE_PATH.test(p) || p.split('/').includes('..'))
150
+ return `remote.path must be an absolute path of letters, digits and ._/+@%=,- only (got ${JSON.stringify(p)})`;
151
+ return null;
152
+ }
153
+
154
+ export function provenanceRefusal(item, cfg = loadConfig()) {
155
+ const p = exp(item.path);
156
+ const parent = path.dirname(p);
157
+ switch (item.category) {
158
+ case 'pkgcache': {
159
+ const known = PKG_CACHES.find((c) => exp(c.p) === p);
160
+ if (!known) return 'not a known package cache path';
161
+ if ((item.cleanCmd || null) !== known.cmd) return 'clean command does not match the scan definition';
162
+ return null;
163
+ }
164
+ case 'cache': {
165
+ const extra = (cfg.extraCaches || []).map(exp);
166
+ if (extra.includes(p) || parent === exp('~/.cache') || parent === exp('~/Library/Caches')) return null;
167
+ return 'not under a known cache directory';
168
+ }
169
+ case 'node_modules':
170
+ return path.basename(p) === 'node_modules' ? null : 'not a node_modules directory';
171
+ case 'appdata':
172
+ return APPDATA_ROOTS.map(exp).includes(parent) ? null : 'not under a known app-data directory';
173
+ case 'models':
174
+ return p === exp('~/.ollama') ? null : 'not a known model store';
175
+ case 'projects':
176
+ case 'apps':
177
+ return null; // projects are archive-only (verified before removal); apps are never executable
178
+ default:
179
+ return `unknown category '${item.category}'`;
180
+ }
181
+ }
182
+
183
+ // Why this item/action would be refused, or null if it is allowed. One source of
184
+ // truth for approve, execute --dry-run and execute, so a preview never promises
185
+ // something the executor will refuse.
186
+ export function actionRefusal(item, action = item.plannedAction || item.suggest) {
187
+ try { validateTarget(item); } catch (e) { return e.message.replace(/^refusing: /, ''); }
188
+ if (item.kind === 'group') return 'grouping folder: select individual projects';
189
+ const forged = provenanceRefusal(item);
190
+ if (forged) return `scan entry does not match its category: ${forged}`;
191
+ if ((action === 'archive' || action === 'archive+rm') && item.category !== 'projects') {
192
+ return `category '${item.category}' cannot be archived (only projects)`;
193
+ }
194
+ if ((action === 'rm' || action === 'clean' || action === 'archive+rm') && isPinned(item.path, loadConfig())) return 'pinned to keep local';
195
+ if (!EXECUTABLE.has(action)) return `'${action}' is not an executable action (review items are manual)`;
196
+ if (action === 'clean' && !item.cleanCmd) return 'no clean command for this item — use rm';
197
+ if (action === 'rm') {
198
+ const reviewUnlocked = REVIEW_RM_UNLOCK.has(item.category) && item.reviewed === true;
199
+ if (!RM_ALLOWED.has(item.category) && !reviewUnlocked) {
200
+ const hint = REVIEW_RM_UNLOCK.has(item.category) ? ' (mark it reviewed first)'
201
+ : item.category === 'projects' ? ' (projects can only be archived: use archive or archive+rm)' : '';
202
+ return `category '${item.category}' is not deletable${hint}`;
203
+ }
204
+ }
205
+ return null;
206
+ }
207
+
208
+ export function scanItem(id) {
209
+ return latestScan()?.items.find((it) => it.id === id) || null;
162
210
  }
163
211
 
164
212
  export async function executeItem(item, { onData = () => {} } = {}) {
165
213
  const p = validateTarget(item);
166
214
  const action = item.plannedAction || item.suggest;
215
+ if (item.kind === 'group') throw new Error('refusing: grouping folder; select individual projects');
216
+ const forged = provenanceRefusal(item);
217
+ if (forged) throw new Error(`refusing: scan entry does not match its category: ${forged}`);
218
+ if ((action === 'archive' || action === 'archive+rm') && item.category !== 'projects') {
219
+ throw new Error(`refusing: category '${item.category}' cannot be archived (only projects)`);
220
+ }
221
+ if (isPinned(p, loadConfig()) && ['rm', 'clean', 'archive+rm'].includes(action)) throw new Error('refusing: pinned to keep local');
167
222
  log({ event: 'start', id: item.id, path: p, action });
168
223
 
169
224
  let result;
@@ -180,22 +235,15 @@ export async function executeItem(item, { onData = () => {} } = {}) {
180
235
  const r = await run('rm', ['-rf', p], { onData });
181
236
  result = { ok: r.code === 0, output: r.err || 'removed' };
182
237
  } else if (action === 'archive' || action === 'archive+rm') {
183
- const a = await archive(item, { onData });
238
+ const a = await archive(item, { onData, removeLocal: action === 'archive+rm' });
184
239
  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
240
  } else {
195
241
  result = { ok: false, output: `no executable action for '${action}' (review items are manual)` };
196
242
  }
197
243
 
198
- log({ event: 'done', id: item.id, path: p, action, ok: result.ok, verified: result.verified });
244
+ // Failures carry their reason in the audit log; plan.json lastOutput is overwritten on retry.
245
+ log({ event: 'done', id: item.id, path: p, action, ok: result.ok, verified: result.verified,
246
+ ...(result.ok ? {} : { error: String(result.output || '').trim().split('\n').pop().slice(0, 300) }) });
199
247
  setPlanItem(item.id, { status: result.ok ? 'done' : 'failed', lastOutput: result.output.slice(-2000) });
200
248
  return result;
201
249
  }