agent-cleandrive 0.0.0-stage → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +357 -2
- package/bin/cleandrive.js +280 -0
- package/config.example.json +35 -0
- package/docs/offload-strategy.md +132 -0
- package/lib/actions.js +263 -0
- package/lib/archives.js +242 -0
- package/lib/catalog.js +222 -0
- package/lib/offload.js +534 -0
- package/lib/projects.js +114 -0
- package/lib/scan.js +236 -0
- package/lib/server.js +261 -0
- package/lib/util.js +134 -0
- package/package.json +60 -4
- package/ui/index.html +521 -0
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
{
|
|
2
|
+
"port": 4499,
|
|
3
|
+
"staleDays": 90,
|
|
4
|
+
"projectDepth": 3,
|
|
5
|
+
"evidenceTimeoutSec": 15,
|
|
6
|
+
"minCacheMB": 100,
|
|
7
|
+
"minAppDataMB": 500,
|
|
8
|
+
"projectRoots": [
|
|
9
|
+
"~/code",
|
|
10
|
+
"~/projects"
|
|
11
|
+
],
|
|
12
|
+
"extraDirs": [
|
|
13
|
+
"~/work",
|
|
14
|
+
"~/experiments"
|
|
15
|
+
],
|
|
16
|
+
"protected": [
|
|
17
|
+
"~/Library/Application Support/Claude",
|
|
18
|
+
"~/.claude",
|
|
19
|
+
"~/.claude-mem"
|
|
20
|
+
],
|
|
21
|
+
"extraCaches": [
|
|
22
|
+
"~/Library/Application Support/Claude/vm_bundles",
|
|
23
|
+
"~/Library/Application Support/Claude/Cache",
|
|
24
|
+
"~/Library/Application Support/Claude/Code Cache"
|
|
25
|
+
],
|
|
26
|
+
"remote": {
|
|
27
|
+
"enabled": false,
|
|
28
|
+
"host": "",
|
|
29
|
+
"user": "",
|
|
30
|
+
"path": "/mnt/external/mac-archive",
|
|
31
|
+
"sshKey": "",
|
|
32
|
+
"sshPort": 22,
|
|
33
|
+
"note": "host = Tailscale device name. sshKey/sshPort optional: leave sshKey blank to use the SSH agent; set sshPort only if the remote is not on 22."
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# Offload / fetch: an iCloud-style switch to your own drive
|
|
2
|
+
|
|
3
|
+
Status: v1 implemented (`lib/offload.js`), 2026-11-04. The reference setup is a
|
|
4
|
+
7.3 TB USB HDD on an NVIDIA Jetson reached over Tailscale; any Linux box with
|
|
5
|
+
SSH and a mounted drive works.
|
|
6
|
+
|
|
7
|
+
## Goal
|
|
8
|
+
|
|
9
|
+
Big, rarely used files (mostly videos) live on the remote drive. On the Mac each one leaves a small placeholder, `<name>.cloud`.
|
|
10
|
+
`fetch` brings the file back byte-for-byte. You can switch a file between
|
|
11
|
+
**local** and **offloaded** as often as you like, and switching back is cheap
|
|
12
|
+
because the remote copy stays.
|
|
13
|
+
|
|
14
|
+
## Hard requirements
|
|
15
|
+
|
|
16
|
+
1. **No always-on process** on the Mac or the remote. That rules out Nextcloud,
|
|
17
|
+
an rclone mount, launchd/systemd units and file watchers. All work happens
|
|
18
|
+
inside one `cleandrive` command over on-demand SSH and rsync.
|
|
19
|
+
2. **Reliability over speed.** A file is never lost, even if Wi-Fi drops,
|
|
20
|
+
Tailscale hangs, the HDD is unplugged, the Mac sleeps or a command is killed
|
|
21
|
+
halfway.
|
|
22
|
+
3. Zero npm dependencies. Reuse `checkRemoteDrive()`, the SSH options and the
|
|
23
|
+
audit log.
|
|
24
|
+
|
|
25
|
+
## The switch: three states per file
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
offload (verified) fetch (verified)
|
|
29
|
+
LOCAL ───────────────────────► OFFLOADED ───────────────────► LOCAL
|
|
30
|
+
file.mp4 file.mp4.cloud (stub) file.mp4
|
|
31
|
+
+ remote object + remote object kept
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
- **local**: a normal file. If it was offloaded before, the remote copy still
|
|
35
|
+
exists, so offloading it again only re-verifies and uploads nothing.
|
|
36
|
+
- **offloaded**: only the stub is on the Mac. The stub is self-describing JSON
|
|
37
|
+
(name, size, sha256, mtime, remote host/path/object), so a fetch works even
|
|
38
|
+
if `data/` is lost.
|
|
39
|
+
- **pinned**: `cleandrive pin <path>`. Never proposed as a candidate.
|
|
40
|
+
|
|
41
|
+
## Which files switch: candidate strategy
|
|
42
|
+
|
|
43
|
+
`cleandrive offload-candidates` (read-only) proposes files. Nothing is moved
|
|
44
|
+
automatically. The user picks.
|
|
45
|
+
|
|
46
|
+
| rule | default | why |
|
|
47
|
+
|---|---|---|
|
|
48
|
+
| size | ≥ 200 MB (`--min=MB`) | small files free little and cost a round-trip |
|
|
49
|
+
| idle | not modified **and** not opened for ≥ 30 days (`--days=N`) | don't offload what is in use |
|
|
50
|
+
| type | video, audio masters, disk images, archives (`--all-types` lifts this) | data that is opaque and big |
|
|
51
|
+
| roots | `~/Movies ~/Documents ~/Desktop ~/Downloads ~/Pictures` + `config.extraDirs` + `config.offload.roots` | where media piles up |
|
|
52
|
+
| never | `~/Library`, `*.photoslibrary`, `.git`, `node_modules`, protected paths, pins, hard links, open files | app data, libraries, things another process owns |
|
|
53
|
+
| duplicates | same size → sha256 → flagged `duplicate of …` | dupes go first; the remote stores the content once |
|
|
54
|
+
|
|
55
|
+
Order: duplicates first, then the largest idle files.
|
|
56
|
+
**When to switch:** when `brief.mjs` shows < 20 GB free, the skill offers
|
|
57
|
+
candidates next to the SAFE caches. Nothing runs on a timer.
|
|
58
|
+
|
|
59
|
+
## Reliability design
|
|
60
|
+
|
|
61
|
+
**Content-addressed remote store.** The object lives at
|
|
62
|
+
`<remote.path>/offload/objects/<aa>/<sha256>`. Identical files are stored
|
|
63
|
+
once. An object is never overwritten and never deleted by offload or fetch.
|
|
64
|
+
|
|
65
|
+
**Offload of one file, in strict order:**
|
|
66
|
+
|
|
67
|
+
1. Validate. The path is a regular file under `$HOME`, not a symlink, has
|
|
68
|
+
nlink = 1, isn't under `~/Library`, protected paths, pins or `.git`, isn't a
|
|
69
|
+
stub, and isn't open in any process (`lsof`).
|
|
70
|
+
2. Hash locally (sha256, streamed). Record size and mtime.
|
|
71
|
+
3. `checkRemoteDrive(size)`. The UUID-pinned drive must be mounted with room
|
|
72
|
+
for size + 5%. If not, refuse.
|
|
73
|
+
4. If the object already exists, re-hash it on the remote. If it matches, this
|
|
74
|
+
is a dedupe and nothing is uploaded.
|
|
75
|
+
5. Otherwise `rsync --partial --timeout=120` to `objects/aa/<sha>.part`. On any
|
|
76
|
+
failure, retry with backoff (default 5 attempts). `--partial` resumes the
|
|
77
|
+
transfer.
|
|
78
|
+
6. Remote `sha256sum <sha>.part` must equal the local hash, then `mv` to the
|
|
79
|
+
final name (atomic on the same filesystem).
|
|
80
|
+
7. Re-stat the local file. If size or mtime changed since step 2, **abort and
|
|
81
|
+
keep the file**.
|
|
82
|
+
8. Write the stub atomically (tmp + fsync + rename). Append to the remote
|
|
83
|
+
`offload/manifest.jsonl` (the second copy of the index). Update
|
|
84
|
+
`data/offloaded.json` (atomic).
|
|
85
|
+
9. Only now unlink the original. If a crash happens between steps 8 and 9,
|
|
86
|
+
both the stub and the original exist. That is harmless: fetch sees the
|
|
87
|
+
original matches and only removes the stub.
|
|
88
|
+
|
|
89
|
+
**Fetch of one stub:**
|
|
90
|
+
|
|
91
|
+
1. Read the stub. If the original path already exists with the same hash,
|
|
92
|
+
just remove the stub.
|
|
93
|
+
2. Check local free space (size + 1 GB margin) and the remote drive.
|
|
94
|
+
3. `rsync --partial` the object into `.<name>.cleandrive-fetch` next to the
|
|
95
|
+
stub, with retries.
|
|
96
|
+
4. The local sha256 must equal the stub's hash, or delete the temp file and
|
|
97
|
+
fail. Then rename to the original name, restore the mtime, and remove the
|
|
98
|
+
stub.
|
|
99
|
+
5. The remote object stays, so a later re-offload is instant.
|
|
100
|
+
|
|
101
|
+
**Concurrency:** `data/offload.lock` (pid) means only one offload or fetch run
|
|
102
|
+
at a time. A stale lock (dead pid) is taken over.
|
|
103
|
+
|
|
104
|
+
**Scrub:** `cleandrive offload-verify` re-hashes every remote object for
|
|
105
|
+
offloaded files on the remote and reports any mismatch. Run it occasionally,
|
|
106
|
+
since the remote has no daemon that would notice bit rot.
|
|
107
|
+
|
|
108
|
+
## Interfaces
|
|
109
|
+
|
|
110
|
+
```
|
|
111
|
+
cleandrive offload <file|dir…> [--dry-run] [--min=MB] dir → files ≥ min (default 50 MB)
|
|
112
|
+
cleandrive fetch <file|file.cloud…> [--dry-run]
|
|
113
|
+
cleandrive offloaded [--json] index: what is offloaded / back local
|
|
114
|
+
cleandrive offload-candidates [--min=200] [--days=30] [--all-types] [--json]
|
|
115
|
+
cleandrive offload-verify scrub remote copies
|
|
116
|
+
cleandrive pin <path…> | unpin <path…>
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
The dashboard has an **Offload** card with candidates (Offload button), the
|
|
120
|
+
offloaded files (Fetch button) and a "Find candidates" run. Both actions ask
|
|
121
|
+
for confirmation and stream into the live log.
|
|
122
|
+
|
|
123
|
+
## Known limits / follow-ups
|
|
124
|
+
|
|
125
|
+
- No Finder double-click on `.cloud` yet. Run `cleandrive fetch <stub>`. A
|
|
126
|
+
Quick Action is a possible follow-up.
|
|
127
|
+
- Remote objects of files that were fetched and later deleted locally stay on
|
|
128
|
+
the remote. A `offload gc` command is a follow-up (by design: nothing on the
|
|
129
|
+
remote is ever deleted automatically).
|
|
130
|
+
- USB drives on the remote may fail to auto-mount at boot if the fstab entry has
|
|
131
|
+
a short `x-systemd.device-timeout` (10 s is too short for a spinning HDD).
|
|
132
|
+
Raise it to 90 s and `sudo systemctl daemon-reload`.
|
package/lib/actions.js
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, lstatSync } from 'node:fs';
|
|
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';
|
|
6
|
+
import {
|
|
7
|
+
HOME, DATA_DIR, loadConfig, readJson, writeJson, run, runShell, ensureDataDir,
|
|
8
|
+
} from './util.js';
|
|
9
|
+
|
|
10
|
+
const PLAN_FILE = path.join(DATA_DIR, 'plan.json');
|
|
11
|
+
const LOG_FILE = path.join(DATA_DIR, 'actions.log');
|
|
12
|
+
|
|
13
|
+
// Categories whose items may be deleted directly (regenerable data only).
|
|
14
|
+
const RM_ALLOWED = new Set(['pkgcache', 'cache', 'node_modules']);
|
|
15
|
+
// Review-only categories where rm unlocks only after an explicit human review
|
|
16
|
+
// (plan.reviewed === true). Apps stay manual: outside $HOME, often root-owned.
|
|
17
|
+
const REVIEW_RM_UNLOCK = new Set(['appdata', 'models']);
|
|
18
|
+
// Never touch these paths or anything above them, whatever the plan says.
|
|
19
|
+
const DENY = ['~', '~/Documents', '~/Desktop', '~/Downloads', '~/Pictures', '~/Library']
|
|
20
|
+
.map((p) => (p === '~' ? HOME : path.join(HOME, p.slice(2))));
|
|
21
|
+
|
|
22
|
+
export function loadPlan() {
|
|
23
|
+
return readJson(PLAN_FILE, { items: {} });
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function savePlan(plan) {
|
|
27
|
+
ensureDataDir();
|
|
28
|
+
writeJson(PLAN_FILE, plan);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function setPlanItem(id, patch) {
|
|
32
|
+
const plan = loadPlan();
|
|
33
|
+
plan.items[id] = { ...(plan.items[id] || {}), ...patch, updated: new Date().toISOString() };
|
|
34
|
+
savePlan(plan);
|
|
35
|
+
return plan.items[id];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Apply many plan changes in one read/write (dashboard one-click presets).
|
|
39
|
+
export function setPlanItems(changes) {
|
|
40
|
+
const plan = loadPlan();
|
|
41
|
+
const updated = new Date().toISOString();
|
|
42
|
+
for (const { id, ...patch } of changes) {
|
|
43
|
+
if (!id) continue;
|
|
44
|
+
plan.items[id] = { ...(plan.items[id] || {}), ...patch, updated };
|
|
45
|
+
}
|
|
46
|
+
savePlan(plan);
|
|
47
|
+
return plan;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function log(entry) {
|
|
51
|
+
ensureDataDir();
|
|
52
|
+
appendFileSync(LOG_FILE, JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function latestScan() {
|
|
56
|
+
return readJson(path.join(DATA_DIR, 'latest.json'));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// A path is only actionable if it came out of the scan (allowlist by construction),
|
|
60
|
+
// lives under $HOME, and is not a protected root.
|
|
61
|
+
export function validateTarget(item) {
|
|
62
|
+
const p = path.resolve(item.path.replace(/^~(?=$|\/)/, HOME));
|
|
63
|
+
if (!p.startsWith(HOME + path.sep)) throw new Error(`refusing: ${p} is outside ${HOME}`);
|
|
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
|
+
}
|
|
69
|
+
if (DENY.includes(p)) throw new Error(`refusing: ${p} is a protected directory`);
|
|
70
|
+
const cfg = loadConfig();
|
|
71
|
+
const protectedPaths = (cfg.protected || []).map((x) => path.resolve(x.replace(/^~/, HOME)));
|
|
72
|
+
// Exact config.extraCaches entries are user-declared regenerable and exempt
|
|
73
|
+
// from the protected lock (subpaths of them are NOT — only the listed dir).
|
|
74
|
+
const extraCaches = new Set((cfg.extraCaches || []).map((x) => path.resolve(x.replace(/^~/, HOME))));
|
|
75
|
+
for (const pp of protectedPaths) {
|
|
76
|
+
if ((contains(pp, p) || contains(p, pp)) && !extraCaches.has(p)) {
|
|
77
|
+
throw new Error(`refusing: ${p} is user-protected (config.protected)`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return p;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Extra ssh flags from config.remote (custom identity file / non-22 port).
|
|
84
|
+
// sshKey is expanded from ~ and validated to exist so a typo fails loudly.
|
|
85
|
+
export function sshOpts(cfg) {
|
|
86
|
+
const { sshKey, sshPort } = cfg.remote || {};
|
|
87
|
+
const opts = [];
|
|
88
|
+
if (sshPort && Number(sshPort) !== 22) opts.push('-p', String(Number(sshPort)));
|
|
89
|
+
if (sshKey) {
|
|
90
|
+
const keyPath = path.resolve(sshKey.replace(/^~/, HOME));
|
|
91
|
+
if (!existsSync(keyPath)) throw new Error(`remote.sshKey not found: ${keyPath}`);
|
|
92
|
+
opts.push('-i', keyPath);
|
|
93
|
+
}
|
|
94
|
+
return opts;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// The archive path must live on the real archive drive, not on an empty mount
|
|
98
|
+
// point of the remote's system disk (drive unplugged / not mounted). With
|
|
99
|
+
// remote.uuid set, the filesystem holding remote.path must have that UUID;
|
|
100
|
+
// without it, it must at least not be the remote's root filesystem.
|
|
101
|
+
// needKB (+5% margin) is checked against the drive's free space.
|
|
102
|
+
export async function checkRemoteDrive(cfg, needKB = 0) {
|
|
103
|
+
const { host, user, path: rpath, uuid } = cfg.remote || {};
|
|
104
|
+
const dest = `${user ? user + '@' : ''}${host}`;
|
|
105
|
+
const base = ['-o', 'ConnectTimeout=5', '-o', 'BatchMode=yes', ...sshOpts(cfg)];
|
|
106
|
+
const q = `'${rpath.replace(/'/g, `'\\''`)}'`;
|
|
107
|
+
const r = await run('ssh', [...base, dest, `findmnt -n -b -o UUID,TARGET,AVAIL -T ${q}`]);
|
|
108
|
+
if (r.code === 255) return { ok: false, reachable: false, mounted: false, msg: (r.err || 'unreachable').trim().split('\n').pop() };
|
|
109
|
+
const [fsUuid, target, avail] = r.out.trim().split(/\s+/);
|
|
110
|
+
if (r.code !== 0 || !target) return { ok: false, reachable: true, mounted: false, msg: `archive path ${rpath} not found — is the archive drive mounted?` };
|
|
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' };
|
|
113
|
+
const mounted = uuid ? fsUuid === uuid : target !== '/';
|
|
114
|
+
if (!mounted) {
|
|
115
|
+
return { ok: false, reachable: true, mounted, freeKB, msg: `archive drive not mounted: ${rpath} is on ${target} (uuid ${fsUuid || '?'})${uuid ? `, expected uuid ${uuid}` : ''}` };
|
|
116
|
+
}
|
|
117
|
+
if (needKB && freeKB < needKB * 1.05) {
|
|
118
|
+
return { ok: false, reachable: true, mounted, freeKB, msg: `not enough space on archive drive: ${Math.round(freeKB / 1024)} MB free, need ~${Math.round(needKB * 1.05 / 1024)} MB` };
|
|
119
|
+
}
|
|
120
|
+
return { ok: true, reachable: true, mounted, freeKB, msg: `archive drive mounted at ${target} — ${(freeKB / 1048576).toFixed(0)} GB free` };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export async function testRemote() {
|
|
124
|
+
const cfg = loadConfig();
|
|
125
|
+
const { host, path: rpath } = cfg.remote || {};
|
|
126
|
+
if (!host || !rpath) return { ok: false, reachable: false, mounted: false, msg: 'remote not configured (set remote.host and remote.path in config.json)' };
|
|
127
|
+
try { return await checkRemoteDrive(cfg); } catch (e) { return { ok: false, reachable: false, mounted: false, msg: e.message }; }
|
|
128
|
+
}
|
|
129
|
+
|
|
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;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export async function executeItem(item, { onData = () => {} } = {}) {
|
|
213
|
+
const p = validateTarget(item);
|
|
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');
|
|
222
|
+
log({ event: 'start', id: item.id, path: p, action });
|
|
223
|
+
|
|
224
|
+
let result;
|
|
225
|
+
if (action === 'clean' && item.cleanCmd) {
|
|
226
|
+
result = await runShell(item.cleanCmd, { onData });
|
|
227
|
+
// Some caches keep residue after the official clean (e.g. npm _cacache logs) — that's fine.
|
|
228
|
+
result = { ok: result.code === 0, output: (result.out + result.err).slice(-4000) };
|
|
229
|
+
} else if (action === 'rm') {
|
|
230
|
+
const reviewUnlocked = REVIEW_RM_UNLOCK.has(item.category) && item.reviewed === true;
|
|
231
|
+
if (!RM_ALLOWED.has(item.category) && !reviewUnlocked) {
|
|
232
|
+
const hint = REVIEW_RM_UNLOCK.has(item.category) ? ' (mark it reviewed first)' : '';
|
|
233
|
+
throw new Error(`refusing rm: category '${item.category}' is not deletable${hint}`);
|
|
234
|
+
}
|
|
235
|
+
const r = await run('rm', ['-rf', p], { onData });
|
|
236
|
+
result = { ok: r.code === 0, output: r.err || 'removed' };
|
|
237
|
+
} else if (action === 'archive' || action === 'archive+rm') {
|
|
238
|
+
const a = await archive(item, { onData, removeLocal: action === 'archive+rm' });
|
|
239
|
+
result = { ok: a.ok, verified: a.verified, output: a.output.slice(-4000) };
|
|
240
|
+
} else {
|
|
241
|
+
result = { ok: false, output: `no executable action for '${action}' (review items are manual)` };
|
|
242
|
+
}
|
|
243
|
+
|
|
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) }) });
|
|
247
|
+
setPlanItem(item.id, { status: result.ok ? 'done' : 'failed', lastOutput: result.output.slice(-2000) });
|
|
248
|
+
return result;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// Merge scan + plan into actionable approved items
|
|
252
|
+
export function approvedItems() {
|
|
253
|
+
const scan = latestScan();
|
|
254
|
+
const plan = loadPlan();
|
|
255
|
+
if (!scan) return [];
|
|
256
|
+
return scan.items
|
|
257
|
+
.filter((it) => plan.items[it.id]?.status === 'approved')
|
|
258
|
+
.map((it) => ({
|
|
259
|
+
...it,
|
|
260
|
+
plannedAction: plan.items[it.id].action || it.suggest,
|
|
261
|
+
reviewed: plan.items[it.id].reviewed === true,
|
|
262
|
+
}));
|
|
263
|
+
}
|