agent-cleandrive 0.0.0-stage β 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +272 -2
- package/bin/cleandrive.js +190 -0
- package/config.example.json +33 -0
- package/docs/offload-strategy.md +132 -0
- package/lib/actions.js +215 -0
- package/lib/offload.js +472 -0
- package/lib/scan.js +253 -0
- package/lib/server.js +208 -0
- package/lib/util.js +118 -0
- package/package.json +60 -4
- package/ui/index.html +489 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Martin Kaiser
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,273 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="center">
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
# π§Ή agent-cleandrive
|
|
4
|
+
|
|
5
|
+
### The disk cleaner your AI agent can't misuse.
|
|
6
|
+
|
|
7
|
+
**Your agent proposes the cleanup, you approve it, and the tool enforces the rules: a project can never be deleted, only archived and verified.**
|
|
8
|
+
Scan β sort by risk β approve β clean caches, archive projects to your own drive with checksum
|
|
9
|
+
verification, or offload big videos iCloud-style. Works with Claude Code, Codex, Cursor, or no agent at all.
|
|
10
|
+
|
|
11
|
+
<sub>Built for, and on, an 8 GB MacBook Air that runs several Claude Code sessions a day.</sub>
|
|
12
|
+
|
|
13
|
+
[](https://github.com/kaiser-data/agent-cleandrive/actions/workflows/test.yml)
|
|
14
|
+

|
|
15
|
+

|
|
16
|
+
 
|
|
17
|
+

|
|
18
|
+

|
|
19
|
+
|
|
20
|
+
<br>
|
|
21
|
+
|
|
22
|
+

|
|
23
|
+
|
|
24
|
+
</div>
|
|
25
|
+
|
|
26
|
+
> **Try it in 60 seconds** (read-only until you approve something):
|
|
27
|
+
> ```bash
|
|
28
|
+
> npx agent-cleandrive scan # ~1β3 min, nothing is changed
|
|
29
|
+
> npx agent-cleandrive serve # dashboard β http://localhost:4499
|
|
30
|
+
> ```
|
|
31
|
+
> Or in Claude Code: `/plugin install cleandrive --marketplace kaiser-data/agent-cleandrive`, then ask *"my disk is full, what can I clean?"*
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## Why this exists
|
|
36
|
+
|
|
37
|
+
Mac disk cleaners fall into two camps. **Dumb** ones blindly wipe `~/Library/Caches` and hope.
|
|
38
|
+
**Dangerous** ones offer "free up 200 GB" in one click and take last week's project with it.
|
|
39
|
+
|
|
40
|
+
agent-cleandrive starts from one hard rule: **nothing is deleted unless it can be regenerated, or has
|
|
41
|
+
been verified on another disk first.** Caches can go, because apps rebuild them. Projects can only
|
|
42
|
+
leave the machine by being copied to your drive and checksum-verified before the local copy is
|
|
43
|
+
removed. Paths you never want touched, such as your Claude Code history, are **hard-locked** and
|
|
44
|
+
refused even when someone forges the action.
|
|
45
|
+
|
|
46
|
+
| Without it | With agent-cleandrive |
|
|
47
|
+
|---|---|
|
|
48
|
+
| "Free up 40 GB?" β and you don't know what's in it | Every item has a category, a risk level and a reason |
|
|
49
|
+
| Deleting a project is one `rm -rf` away | Projects can't be `rm`-ed at all, only archived and verified |
|
|
50
|
+
| Old videos are either on the Mac or gone | `offload` leaves a `.cloud` placeholder; `fetch` restores it byte-for-byte |
|
|
51
|
+
| `df` says 56% full while macOS says the disk is full | Real APFS capacity: `used / (used + available)` |
|
|
52
|
+
| The disk fills up again and you don't know why | Field-tested list of where the space actually goes ([below](#field-notes-where-the-space-actually-went)) |
|
|
53
|
+
|
|
54
|
+
### Built on an 8 GB Mac
|
|
55
|
+
|
|
56
|
+
I'm [Martin Kaiser](https://github.com/kaiser-data). I do agent-heavy development, with several Claude
|
|
57
|
+
Code sessions, MCP servers, a browser and a local model, on a **base M2 MacBook Air: 8 GB RAM,
|
|
58
|
+
228 GB disk**. That's a deliberate choice. Small hardware forces lean habits, and lean habits make
|
|
59
|
+
agent work cheaper wherever it runs.
|
|
60
|
+
|
|
61
|
+
The catch is that on a small Mac, **memory and disk are one problem.** With 8 GB, macOS swaps hard;
|
|
62
|
+
on a normal workday swap sits around **7.9 of 8 GB**, and those swap files live in the same APFS
|
|
63
|
+
container as your files. Each `npm install` or `uv sync` an agent runs adds gigabytes of
|
|
64
|
+
dependencies. So the disk fills from two sides, and when free space runs out, swap has nowhere to
|
|
65
|
+
grow and the whole machine stalls.
|
|
66
|
+
|
|
67
|
+
agent-cleandrive is how I keep that machine usable without buying a bigger one. It makes the disk side
|
|
68
|
+
predictable: dependency churn gets cleaned often and safely, finished projects move to a drive
|
|
69
|
+
on my tailnet, and big videos become placeholders. Free space stays free, so swap has room. It
|
|
70
|
+
manages disk only; it doesn't touch RAM or running processes.
|
|
71
|
+
|
|
72
|
+
<table>
|
|
73
|
+
<tr>
|
|
74
|
+
<td width="50%" valign="top"><b>Light</b><br><img src="media/dashboard-light.png" alt="Dashboard in light mode: capacity bar, category breakdown, item table with approve buttons"></td>
|
|
75
|
+
<td width="50%" valign="top"><b>Dark</b><br><img src="media/dashboard-dark.png" alt="Dashboard in dark mode"></td>
|
|
76
|
+
</tr>
|
|
77
|
+
</table>
|
|
78
|
+
|
|
79
|
+
---
|
|
80
|
+
|
|
81
|
+
## Install
|
|
82
|
+
|
|
83
|
+
| Way | Command | Config & data live in |
|
|
84
|
+
|---|---|---|
|
|
85
|
+
| **Claude Code plugin** | `/plugin install cleandrive --marketplace kaiser-data/agent-cleandrive` | `~/.config/cleandrive/` |
|
|
86
|
+
| **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/`) |
|
|
88
|
+
|
|
89
|
+
Needs macOS and Node β₯ 20 (Linux support is next on the roadmap). **No dependencies:** pure Node stdlib plus the system's `du`, `rsync`
|
|
90
|
+
and `ssh`. On first run it writes a default `config.json`. Point `projectRoots` at your
|
|
91
|
+
code folders and, if you want archiving, set `remote`.
|
|
92
|
+
|
|
93
|
+
---
|
|
94
|
+
|
|
95
|
+
## How it works
|
|
96
|
+
|
|
97
|
+
1. **Scan.** `cleandrive scan` sizes caches, package caches, `node_modules`, projects, app data,
|
|
98
|
+
apps (with last-used date) and models, then writes `data/latest.json`.
|
|
99
|
+
2. **Plan.** Each item gets a category, which fixes what is allowed. You approve items in the
|
|
100
|
+
dashboard or with `cleandrive approve <id>`.
|
|
101
|
+
3. **Preview.** `cleandrive execute --dry-run` shows exactly what will happen.
|
|
102
|
+
4. **Execute.** In the dashboard you type `FREE`; in the CLI you run `cleandrive execute`. Every
|
|
103
|
+
step is logged to `data/actions.log`.
|
|
104
|
+
|
|
105
|
+
| Category | Risk | What it allows | Example |
|
|
106
|
+
|---|---|---|---|
|
|
107
|
+
| `pkgcache` | low | official clean (npm/uv/brew/pnpm/bun), or rm | *`~/.npm` β 935 MB* |
|
|
108
|
+
| `cache` | low | rm, the app rebuilds it | *`~/Library/Caches/com.spotify.client`* |
|
|
109
|
+
| `node_modules` | low | rm, reinstall per project | *`~/code/old-app/node_modules`* |
|
|
110
|
+
| `projects` | medium | archive / archive+rm / keep, **never a bare rm** | *a repo untouched for 60+ days* |
|
|
111
|
+
| `appdata` | review | rm only after you mark it reviewed | *`~/Library/Application Support/Slack`* |
|
|
112
|
+
| `models` | review | rm after review, or via the owning tool | *`~/.ollama`* |
|
|
113
|
+
| `apps` | manual | never deleted, shown with size and last-used date | *an 800 MB app unopened for 5 months* |
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
## The safety model
|
|
118
|
+
|
|
119
|
+
This is the reason the tool exists. Every rule is enforced in the executor, not just in the UI,
|
|
120
|
+
and **[covered by tests](test/safety.test.mjs)** that run against a fake `$HOME`.
|
|
121
|
+
|
|
122
|
+
- **Allowlist by construction.** Only paths that came out of the scan are actionable; forged plan
|
|
123
|
+
entries are ignored.
|
|
124
|
+
- **`rm` is category-gated.** It works only for `pkgcache`, `cache`, `node_modules`, and for
|
|
125
|
+
`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
|
|
127
|
+
pass. The local copy goes only if that pass reports zero content differences.
|
|
128
|
+
- **The drive must really be there.** Before every archive or offload, the tool checks over SSH
|
|
129
|
+
that `remote.path` sits on the expected drive (`remote.uuid`), not on an empty mount point on the
|
|
130
|
+
remote's system disk, and that there is room for the item + 5%.
|
|
131
|
+
- **Protected paths are hard-locked.** `config.protected` entries are flagged π, forced to `keep`,
|
|
132
|
+
and refused at execution. The default protects `~/.claude`, `~/.claude-mem` and the Claude
|
|
133
|
+
desktop app's data. `config.extraCaches` can carve out exact regenerable subpaths, and only those.
|
|
134
|
+
- **Protected roots.** `~`, `~/Documents`, `~/Desktop`, `~/Downloads`, `~/Pictures`, `~/Library`
|
|
135
|
+
are refused as direct targets, whatever the plan says.
|
|
136
|
+
- **Local only.** The dashboard binds to `127.0.0.1`. There is no cloud, no account and no telemetry.
|
|
137
|
+
|
|
138
|
+
---
|
|
139
|
+
|
|
140
|
+
## Offload: iCloud-style, to your own drive
|
|
141
|
+
|
|
142
|
+
Big idle files, mostly videos, move to your remote drive. A small `<name>.cloud` placeholder stays
|
|
143
|
+
on the Mac, and `fetch` brings the file back byte-for-byte. Nothing runs in the background, on
|
|
144
|
+
either machine.
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
cleandrive offload-candidates # read-only: big idle media, duplicates first
|
|
148
|
+
cleandrive offload ~/Movies/talk.mov --dry-run
|
|
149
|
+
cleandrive offload ~/Movies/talk.mov # β talk.mov.cloud (1 KB)
|
|
150
|
+
cleandrive fetch ~/Movies/talk.mov.cloud # β talk.mov, sha256-verified
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
The local file is unlinked only after the **remote sha256 equals the local hash** and the file is
|
|
154
|
+
**unchanged since hashing**. Symlinks, hard links, open files (`lsof`), `~/Library`, `.git`,
|
|
155
|
+
`node_modules`, photo and media libraries, protected paths and pins are refused. Storage is
|
|
156
|
+
content-addressed, so duplicates are stored once and re-offloading a fetched file uploads nothing.
|
|
157
|
+
The design is in [`docs/offload-strategy.md`](docs/offload-strategy.md).
|
|
158
|
+
|
|
159
|
+
---
|
|
160
|
+
|
|
161
|
+
## Any agent can drive it
|
|
162
|
+
|
|
163
|
+
The CLI speaks `--json` and the state is plain files, so any coding agent can run the whole loop.
|
|
164
|
+
The safety gates live in the executor, not in the prompt: **an agent that misreads the plan still
|
|
165
|
+
cannot delete a project or a protected path.**
|
|
166
|
+
|
|
167
|
+
- **Claude Code:** install the plugin. Its [skill](skills/cleandrive/SKILL.md) teaches the workflow: read the scan, propose a plan grouped by risk, act only on the items you confirm.
|
|
168
|
+
- **Codex, Cursor, Gemini CLI, others:** paste this into the agent's instructions (`AGENTS.md`, rules file):
|
|
169
|
+
|
|
170
|
+
> To free disk space, use the `cleandrive` CLI. Run `cleandrive state --json`, propose a plan grouped by category with sizes, and wait for my confirmation of specific items. Then `cleandrive approve <ids>`, show `cleandrive execute --dry-run`, and run `cleandrive execute` only after I say yes. Never delete files by hand that cleandrive refuses.
|
|
171
|
+
|
|
172
|
+
```bash
|
|
173
|
+
cleandrive state --json # items: {id, path, kb, category, suggest, note}
|
|
174
|
+
cleandrive approve <idβ¦> --action=archive+rm
|
|
175
|
+
cleandrive execute --dry-run # Claude shows you this first
|
|
176
|
+
cleandrive execute # only after you say yes
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
> *"Here are 33 GB of package caches and 14 GB of `node_modules`, all regenerable. Clean them?
|
|
180
|
+
> And 3 projects untouched since spring, 21 GB. Archive and verify them to your drive first?"*
|
|
181
|
+
|
|
182
|
+
agent-cleandrive was itself built in Claude Code sessions. That is why protecting agent history is a
|
|
183
|
+
default: **the tool knows what it must never delete.**
|
|
184
|
+
|
|
185
|
+
---
|
|
186
|
+
|
|
187
|
+
## Field notes: where the space actually went
|
|
188
|
+
|
|
189
|
+
Lessons from running agent-cleandrive on an 8 GB / 228 GB MacBook Air under daily agent workloads,
|
|
190
|
+
which kept hitting 98% full (SeptβNov 2026).
|
|
191
|
+
These shaped the code and the [skill](skills/cleandrive/SKILL.md).
|
|
192
|
+
|
|
193
|
+
| What we saw | What it taught us |
|
|
194
|
+
|---|---|
|
|
195
|
+
| `df` reported 56% while macOS said the disk was full | APFS volumes share one container. Real capacity is `used / (used + available)`. |
|
|
196
|
+
| A scan ran for over an hour at 0% CPU | `du` blocks forever on other apps' privacy-protected containers. Every `du` now has a timeout, and unreadable paths are listed in `scan.blocked`. |
|
|
197
|
+
| Swap stood at 7.9 of 8 GB on a normal workday | On an 8 GB Mac, swap is part of disk usage. Keep several GB free, or the machine stalls before the disk is technically full. |
|
|
198
|
+
| Roughly 100 GB of "used" space never appeared in any scan | macOS privacy (TCC) hides Downloads, Documents, Desktop, Mail and Trash from the terminal. Grant **Full Disk Access** or the numbers stay low. |
|
|
199
|
+
| 36 GB came back within five days of a cleanup | Most likely not a leak but dependency churn: `node_modules`, `.venv` and package caches regrow with every install. Clean them often; they are low-risk. |
|
|
200
|
+
| Aerial wallpaper videos regrew to 5.9 GB in two days | Switching the wallpaper is not enough. The **screen saver and lock screen** also download Aerials. |
|
|
201
|
+
| A Claude Code plugin cache held 17 old versions, most ~800 MB each (9.6 GB) | Tool and plugin caches keep old versions side by side. Keep the active one (check its manifest); the rest is dead weight. |
|
|
202
|
+
| "Archive OK", but the files landed on the remote's boot disk | The USB drive wasn't mounted, so the mount point was just an empty folder. Archives now check the drive's UUID first. |
|
|
203
|
+
| The USB drive didn't mount after a reboot | `x-systemd.device-timeout=10` in fstab is too short for a spinning HDD. Use 90 s. |
|
|
204
|
+
| SSH to the Tailscale short name timed out | The `100.x` IP worked. Use the IP as `remote.host` if the name is flaky. |
|
|
205
|
+
| `rsync --info=progress2` failed on the Mac | macOS ships openrsync ("2.6.9 compatible"). Use portable flags only. |
|
|
206
|
+
| Checksum verification flagged unchanged files | ext4 can't represent macOS symlink permissions. Ignore metadata-only diffs; still fail on any content, size or missing-file change. |
|
|
207
|
+
| A cache `rm` failed halfway | The browser was still running. Quit the app first, then re-approve the item. |
|
|
208
|
+
| `approve $IDS` recorded a single bogus id | zsh doesn't word-split `$IDS`. Pass ids as `$(cat ids.txt)`. |
|
|
209
|
+
|
|
210
|
+
---
|
|
211
|
+
|
|
212
|
+
## CLI reference
|
|
213
|
+
|
|
214
|
+
| Command | What it does |
|
|
215
|
+
|---|---|
|
|
216
|
+
| `scan [--json]` | Rescan, categorize, write `data/latest.json` |
|
|
217
|
+
| `state [--json]` | Current scan and plan, with item ids |
|
|
218
|
+
| `serve` | Dashboard at `http://localhost:4499` |
|
|
219
|
+
| `approve <idβ¦> [--action=rm\|clean\|archive\|archive+rm]` | Approve items |
|
|
220
|
+
| `skip <idβ¦>` Β· `review <idβ¦>` | Skip items Β· mark reviewed (unlocks rm for `appdata`/`models`) |
|
|
221
|
+
| `execute [--dry-run]` | Run all approved actions |
|
|
222
|
+
| `remote-test` | SSH reachability, drive mounted, free space |
|
|
223
|
+
| `offload-dryrun` | `rsync -n` the approved archive items |
|
|
224
|
+
| `offload-candidates [--min=200] [--days=30]` | Big idle media and duplicates (read-only) |
|
|
225
|
+
| `offload <file\|dirβ¦> [--dry-run]` | Verified upload, leaves `<name>.cloud` |
|
|
226
|
+
| `fetch <file\|stub\|dirβ¦> [--dry-run]` | Restore offloaded files, sha256-verified |
|
|
227
|
+
| `offloaded` Β· `offload-verify` Β· `pin <path>` | List Β· re-hash every remote copy Β· keep a path local |
|
|
228
|
+
|
|
229
|
+
## Remote drive setup
|
|
230
|
+
|
|
231
|
+
1. Attach a drive to any Linux machine you can SSH into: a Raspberry Pi, a Jetson, a NAS, an old
|
|
232
|
+
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.
|
|
234
|
+
3. Run `cleandrive remote-test`. It must report the drive as mounted.
|
|
235
|
+
|
|
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.
|
|
238
|
+
|
|
239
|
+
---
|
|
240
|
+
|
|
241
|
+
## Architecture
|
|
242
|
+
|
|
243
|
+
```
|
|
244
|
+
bin/cleandrive.js CLI + agent connector (every command scriptable, --json where useful)
|
|
245
|
+
lib/scan.js scanner: categories, sizes, staleness, app last-used, blocked paths
|
|
246
|
+
lib/actions.js executor: validation gates, rm/clean/archive, checksum verify, audit log
|
|
247
|
+
lib/offload.js offload/fetch: content-addressed remote store, .cloud stubs, scrub
|
|
248
|
+
lib/server.js zero-dependency HTTP API + static host, 127.0.0.1 only
|
|
249
|
+
lib/util.js process runner with timeouts, atomic JSON writes, config resolution
|
|
250
|
+
ui/index.html single-file dashboard (colorblind-safe palette, light/dark)
|
|
251
|
+
skills/cleandrive/ Claude Code skill shipped with the plugin
|
|
252
|
+
test/ safety-model tests (node:test, fake $HOME)
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
## Development
|
|
256
|
+
|
|
257
|
+
```bash
|
|
258
|
+
npm test # 15 tests, ~0.3 s, never touches your real home folder
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
**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 Β·
|
|
262
|
+
"free up X GB" goal mode Β· known space-hog catalog Β· coverage bar (what the scan can't see) Β·
|
|
263
|
+
recursive project discovery and stale subfolders Β· scan speed.
|
|
264
|
+
|
|
265
|
+
---
|
|
266
|
+
|
|
267
|
+
<div align="center">
|
|
268
|
+
|
|
269
|
+
MIT licensed Β· built by [Martin Kaiser](https://github.com/kaiser-data) with [Claude Code](https://claude.com/claude-code), on 8 GB of RAM
|
|
270
|
+
|
|
271
|
+
**Clean without fear.**
|
|
272
|
+
|
|
273
|
+
</div>
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// cleandrive β scan disk, plan cleanup, clean caches, archive to remote over SSH/Tailscale.
|
|
3
|
+
// This CLI is also the Claude Code connector: every command supports --json where useful.
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { DATA_DIR, readJson, fmtGB, loadConfig } from '../lib/util.js';
|
|
6
|
+
import { runScan, CATEGORIES } from '../lib/scan.js';
|
|
7
|
+
import { serve } from '../lib/server.js';
|
|
8
|
+
import { loadPlan, setPlanItem, approvedItems, executeItem, testRemote, archive } from '../lib/actions.js';
|
|
9
|
+
import { offloadPaths, fetchPaths, listOffloaded, findCandidates, verifyRemote, setPin } from '../lib/offload.js';
|
|
10
|
+
|
|
11
|
+
const [, , cmd, ...args] = process.argv;
|
|
12
|
+
const flag = (f) => args.includes(f);
|
|
13
|
+
const num = (name, dflt) => { const a = args.find((x) => x.startsWith(`--${name}=`)); return a ? Number(a.split('=')[1]) : dflt; };
|
|
14
|
+
const positional = () => args.filter((a) => !a.startsWith('--'));
|
|
15
|
+
const out = (d) => process.stderr.write(d);
|
|
16
|
+
|
|
17
|
+
function latest() {
|
|
18
|
+
const scan = readJson(path.join(DATA_DIR, 'latest.json'));
|
|
19
|
+
if (!scan) {
|
|
20
|
+
console.error('no scan yet β run: cleandrive scan');
|
|
21
|
+
process.exit(1);
|
|
22
|
+
}
|
|
23
|
+
return scan;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function printState() {
|
|
27
|
+
const scan = latest();
|
|
28
|
+
const plan = loadPlan();
|
|
29
|
+
if (flag('--json')) {
|
|
30
|
+
console.log(JSON.stringify({ scan, plan }, null, 2));
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
const d = scan.disk;
|
|
34
|
+
console.log(`scan: ${scan.ts}`);
|
|
35
|
+
console.log(`disk: ${fmtGB(d.usedKB)} used of ${fmtGB(d.sizeKB)} (${d.pct}%), ${fmtGB(d.availKB)} free\n`);
|
|
36
|
+
if (scan.blocked?.length) {
|
|
37
|
+
const timedOut = scan.blocked.filter((b) => /timed out/.test(b.reason));
|
|
38
|
+
const partial = scan.blocked.length - timedOut.length;
|
|
39
|
+
for (const b of timedOut) console.log(`β not measured: ${b.path.replace(process.env.HOME, '~')} β ${b.reason}`);
|
|
40
|
+
if (partial) console.log(`βΉ ${partial} folder(s) partly unreadable (macOS privacy). Sizes may be low; grant your terminal Full Disk Access for full numbers.`);
|
|
41
|
+
console.log('');
|
|
42
|
+
}
|
|
43
|
+
for (const [key, meta] of Object.entries(CATEGORIES)) {
|
|
44
|
+
const items = scan.items.filter((i) => i.category === key);
|
|
45
|
+
if (!items.length) continue;
|
|
46
|
+
const total = items.reduce((s, i) => s + i.kb, 0);
|
|
47
|
+
console.log(`## ${meta.label} β ${fmtGB(total)} (risk: ${meta.risk})`);
|
|
48
|
+
for (const i of items.slice(0, 15)) {
|
|
49
|
+
const st = plan.items[i.id]?.status || 'Β·';
|
|
50
|
+
console.log(` [${st.padEnd(8)}] ${i.id} ${fmtGB(i.kb).padStart(8)} ${i.suggest.padEnd(10)} ${i.path.replace(process.env.HOME, '~')}`);
|
|
51
|
+
}
|
|
52
|
+
if (items.length > 15) console.log(` β¦ ${items.length - 15} more`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
switch (cmd) {
|
|
57
|
+
case 'scan': {
|
|
58
|
+
console.error('scanningβ¦');
|
|
59
|
+
const scan = await runScan((s) => console.error(' ' + s));
|
|
60
|
+
if (flag('--json')) console.log(JSON.stringify(scan, null, 2));
|
|
61
|
+
else console.log(`done: ${scan.items.length} items, disk at ${scan.disk.pct}%`);
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
case 'state':
|
|
65
|
+
printState();
|
|
66
|
+
break;
|
|
67
|
+
case 'serve':
|
|
68
|
+
serve();
|
|
69
|
+
break;
|
|
70
|
+
case 'approve': {
|
|
71
|
+
const ids = args.filter((a) => !a.startsWith('--'));
|
|
72
|
+
const action = (args.find((a) => a.startsWith('--action=')) || '').split('=')[1];
|
|
73
|
+
for (const id of ids) {
|
|
74
|
+
setPlanItem(id, { status: 'approved', ...(action && { action }) });
|
|
75
|
+
console.log(`approved ${id}${action ? ' β ' + action : ''}`);
|
|
76
|
+
}
|
|
77
|
+
break;
|
|
78
|
+
}
|
|
79
|
+
case 'skip':
|
|
80
|
+
for (const id of args.filter((a) => !a.startsWith('--'))) {
|
|
81
|
+
setPlanItem(id, { status: 'skipped' });
|
|
82
|
+
console.log(`skipped ${id}`);
|
|
83
|
+
}
|
|
84
|
+
break;
|
|
85
|
+
case 'review':
|
|
86
|
+
for (const id of args.filter((a) => !a.startsWith('--'))) {
|
|
87
|
+
setPlanItem(id, { status: 'reviewed', reviewed: true });
|
|
88
|
+
console.log(`reviewed ${id}`);
|
|
89
|
+
}
|
|
90
|
+
break;
|
|
91
|
+
case 'execute': {
|
|
92
|
+
const items = approvedItems();
|
|
93
|
+
if (!items.length) { console.log('nothing approved'); break; }
|
|
94
|
+
const dry = flag('--dry-run');
|
|
95
|
+
for (const item of items) {
|
|
96
|
+
console.log(`${dry ? '[dry-run] would' : 'βΆ'} ${item.plannedAction}: ${item.path} (${fmtGB(item.kb)})`);
|
|
97
|
+
if (dry) continue;
|
|
98
|
+
try {
|
|
99
|
+
const r = await executeItem(item, { onData: (d) => process.stderr.write(d) });
|
|
100
|
+
console.log(r.ok ? ' β done' : ` β failed: ${r.output.split('\n').pop()}`);
|
|
101
|
+
} catch (e) {
|
|
102
|
+
console.log(` β refused: ${e.message}`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
break;
|
|
106
|
+
}
|
|
107
|
+
case 'offload-dryrun': {
|
|
108
|
+
const items = approvedItems().filter((i) => (i.plannedAction || '').startsWith('archive'));
|
|
109
|
+
for (const item of items) {
|
|
110
|
+
console.log(`dry-run: ${item.path}`);
|
|
111
|
+
const r = await archive(item, { dryRun: true, onData: (d) => process.stderr.write(d) });
|
|
112
|
+
console.log(r.ok ? ' β ok' : ` β ${r.output}`);
|
|
113
|
+
}
|
|
114
|
+
break;
|
|
115
|
+
}
|
|
116
|
+
case 'offload': {
|
|
117
|
+
const ps = positional();
|
|
118
|
+
if (!ps.length) { console.error('usage: cleandrive offload <file|dirβ¦> [--dry-run] [--min=MB]'); process.exit(2); }
|
|
119
|
+
const r = await offloadPaths(ps, { dryRun: flag('--dry-run'), minMB: num('min', 50), onData: out });
|
|
120
|
+
const ok = r.filter((x) => x.ok);
|
|
121
|
+
console.log(`${flag('--dry-run') ? 'dry-run: ' : ''}${ok.length}/${r.length} ok, ${fmtGB(ok.reduce((s, x) => s + (x.size || 0), 0) / 1024)}`);
|
|
122
|
+
process.exit(r.every((x) => x.ok) ? 0 : 1);
|
|
123
|
+
break;
|
|
124
|
+
}
|
|
125
|
+
case 'fetch': {
|
|
126
|
+
const ps = positional();
|
|
127
|
+
if (!ps.length) { console.error('usage: cleandrive fetch <file|file.cloud|dirβ¦> [--dry-run]'); process.exit(2); }
|
|
128
|
+
const r = await fetchPaths(ps, { dryRun: flag('--dry-run'), onData: out });
|
|
129
|
+
console.log(`${flag('--dry-run') ? 'dry-run: ' : ''}${r.filter((x) => x.ok).length}/${r.length} ok`);
|
|
130
|
+
process.exit(r.every((x) => x.ok) ? 0 : 1);
|
|
131
|
+
break;
|
|
132
|
+
}
|
|
133
|
+
case 'offloaded': {
|
|
134
|
+
const l = listOffloaded();
|
|
135
|
+
if (flag('--json')) { console.log(JSON.stringify(l, null, 2)); break; }
|
|
136
|
+
const off = l.files.filter((f) => f.state === 'offloaded');
|
|
137
|
+
console.log(`offloaded: ${off.length} files, ${fmtGB(off.reduce((s, f) => s + f.size, 0) / 1024)} on the remote`);
|
|
138
|
+
for (const f of l.files) console.log(` [${f.state.padEnd(9)}] ${fmtGB(f.size / 1024).padStart(8)} ${f.path.replace(process.env.HOME, '~')}`);
|
|
139
|
+
if (l.pins.length) console.log(`pinned (keep local): ${l.pins.map((p) => p.replace(process.env.HOME, '~')).join(', ')}`);
|
|
140
|
+
break;
|
|
141
|
+
}
|
|
142
|
+
case 'offload-candidates': {
|
|
143
|
+
const r = await findCandidates({ minMB: num('min', 200), days: num('days', 30), allTypes: flag('--all-types'), dupes: !flag('--no-dupes'), onData: out });
|
|
144
|
+
if (flag('--json')) { console.log(JSON.stringify(r, null, 2)); break; }
|
|
145
|
+
const tot = r.candidates.reduce((s, c) => s + c.kb, 0);
|
|
146
|
+
console.log(`${r.candidates.length} candidates, ${fmtGB(tot)} (β₯${r.minMB} MB, idle β₯${r.days}d)`);
|
|
147
|
+
for (const c of r.candidates.slice(0, 40)) {
|
|
148
|
+
console.log(` ${fmtGB(c.kb).padStart(8)} ${String(c.idleDays).padStart(4)}d ${c.path.replace(process.env.HOME, '~')}${c.duplicateOf ? ` β§ duplicate of ${c.duplicateOf.replace(process.env.HOME, '~')}` : ''}`);
|
|
149
|
+
}
|
|
150
|
+
if (r.unreadable) console.log(`β ${r.unreadable} paths not readable (macOS privacy / Full Disk Access)`);
|
|
151
|
+
break;
|
|
152
|
+
}
|
|
153
|
+
case 'offload-verify': {
|
|
154
|
+
const r = await verifyRemote({ onData: out });
|
|
155
|
+
console.log(r.bad.length ? `β ${r.bad.length} of ${r.checked} remote copies bad` : `β all ${r.checked} remote copies verified`);
|
|
156
|
+
process.exit(r.bad.length ? 1 : 0);
|
|
157
|
+
break;
|
|
158
|
+
}
|
|
159
|
+
case 'pin':
|
|
160
|
+
case 'unpin':
|
|
161
|
+
for (const p of positional()) console.log(`${cmd === 'pin' ? 'pinned' : 'unpinned'} ${setPin(p, cmd === 'pin')}`);
|
|
162
|
+
break;
|
|
163
|
+
case 'remote-test': {
|
|
164
|
+
const r = await testRemote();
|
|
165
|
+
console.log((r.ok ? 'β ' : 'β ') + r.msg);
|
|
166
|
+
process.exit(r.ok ? 0 : 1);
|
|
167
|
+
break;
|
|
168
|
+
}
|
|
169
|
+
default:
|
|
170
|
+
console.log(`cleandrive β disk cleanup planner & executor
|
|
171
|
+
|
|
172
|
+
usage:
|
|
173
|
+
cleandrive scan [--json] scan disk, categorize, write data/latest.json
|
|
174
|
+
cleandrive state [--json] show latest scan + plan status
|
|
175
|
+
cleandrive serve start dashboard on http://localhost:${loadConfig().port || 4499}
|
|
176
|
+
cleandrive approve <idβ¦> [--action=rm|clean|archive|archive+rm]
|
|
177
|
+
cleandrive skip <idβ¦>
|
|
178
|
+
cleandrive review <idβ¦> mark reviewed (unlocks rm for appdata/models)
|
|
179
|
+
cleandrive execute [--dry-run] run all approved actions
|
|
180
|
+
cleandrive offload-dryrun rsync -n approved archive items to remote
|
|
181
|
+
cleandrive remote-test check SSH reachability of configured remote
|
|
182
|
+
|
|
183
|
+
offload (iCloud-style switch to the remote drive, see docs/offload-strategy.md):
|
|
184
|
+
cleandrive offload <file|dirβ¦> [--dry-run] [--min=MB] verified upload, leaves <name>.cloud
|
|
185
|
+
cleandrive fetch <file|stub|dirβ¦> [--dry-run] verified download, removes the stub
|
|
186
|
+
cleandrive offloaded [--json] what is offloaded / back local
|
|
187
|
+
cleandrive offload-candidates [--min=200] [--days=30] [--all-types] [--no-dupes] [--json]
|
|
188
|
+
cleandrive offload-verify re-hash remote copies (scrub)
|
|
189
|
+
cleandrive pin|unpin <pathβ¦> keep local / never propose`);
|
|
190
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"port": 4499,
|
|
3
|
+
"staleDays": 60,
|
|
4
|
+
"minCacheMB": 100,
|
|
5
|
+
"minAppDataMB": 500,
|
|
6
|
+
"projectRoots": [
|
|
7
|
+
"~/code",
|
|
8
|
+
"~/projects"
|
|
9
|
+
],
|
|
10
|
+
"extraDirs": [
|
|
11
|
+
"~/work",
|
|
12
|
+
"~/experiments"
|
|
13
|
+
],
|
|
14
|
+
"protected": [
|
|
15
|
+
"~/Library/Application Support/Claude",
|
|
16
|
+
"~/.claude",
|
|
17
|
+
"~/.claude-mem"
|
|
18
|
+
],
|
|
19
|
+
"extraCaches": [
|
|
20
|
+
"~/Library/Application Support/Claude/vm_bundles",
|
|
21
|
+
"~/Library/Application Support/Claude/Cache",
|
|
22
|
+
"~/Library/Application Support/Claude/Code Cache"
|
|
23
|
+
],
|
|
24
|
+
"remote": {
|
|
25
|
+
"enabled": false,
|
|
26
|
+
"host": "",
|
|
27
|
+
"user": "",
|
|
28
|
+
"path": "/mnt/external/mac-archive",
|
|
29
|
+
"sshKey": "",
|
|
30
|
+
"sshPort": 22,
|
|
31
|
+
"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."
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -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`.
|