dsh-disk-cleaner 1.2.0 → 1.4.0

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
@@ -5,7 +5,7 @@
5
5
  <!-- badges -->
6
6
  | | |
7
7
  | --- | --- |
8
- | **version** | `1.2.0` |
8
+ | **version** | `1.4.0` |
9
9
  | **DSH** | `0.2.1-rc.5`(开发与实测版本;用到 `plugins.bundle.config`、`settings.section`) |
10
10
  | **license** | [MIT](LICENSE) |
11
11
  | **Node** | `>= 22`(仅运行冒烟测试需要) |
@@ -16,7 +16,7 @@
16
16
 
17
17
  **dsh-disk-cleaner** is a disk-space plugin for [DeepSeek Harness](https://github.com/deepseek-ai) (DSH). It does two different jobs, and keeps them apart on purpose:
18
18
 
19
- 1. **Clean** — nineteen known-safe locations (temp folders, package manager stores, browser caches, crash dumps, the Recycle Bin, leftover update installers, per-app caches and logs, superseded plugin versions and applied update packages). Only these are ever deleted.
19
+ 1. **Clean** — twenty-eight known-safe locations (temp folders, package manager stores, browser caches, crash dumps, the Recycle Bin, leftover update installers, per-app caches and logs, superseded plugin versions and applied update packages). Only these are ever deleted.
20
20
  2. **Assess** — everything the plugin will *not* delete (installed programs, the WSL virtual disk, the Windows component store, chat-app data, your own folders). Measured and listed, never removed.
21
21
 
22
22
  The assessment ends with a **plan**: the same numbers ordered by what it costs you to act, with the exact Windows command for the steps the plugin cannot perform itself.
@@ -27,9 +27,9 @@ Both the panel and the agent reach the *same* operations: the cleaning logic liv
27
27
 
28
28
  | Feature | Description |
29
29
  | --- | --- |
30
- | Scan | Measures all nineteen targets concurrently and shows what each occupies |
30
+ | Scan | Measures all twenty-eight targets concurrently and shows what each occupies |
31
31
  | Per-drive filter | Chip row of mounted volumes; scanning or cleaning can be limited to one drive, and rows with nothing on that drive disappear |
32
- | Risk labels | Every target is `safe` or `caution`, with a one-line reason (`in-use` / `rebuild` / `elevation` / `pending-update` / `rollback` / `superseded`) and a permanent legend, so "caution" never means "unspecified" |
32
+ | Risk labels | Every target is `safe` or `caution`, with a one-line reason (`in-use` / `rebuild` / `elevation` / `pending-update` / `rollback` / `superseded` / `history` / `duplicate` / `database-backup`) and a permanent legend, so "caution" never means "unspecified" |
33
33
  | Aged deletion | `temp` and `windows-temp` only remove files older than one day; files a running program still holds are skipped |
34
34
  | Space assessment | Walks the disk read-only and groups the result into Windows / installed software / your own files, plus the ten largest app-data folders. Any row opens its folder in Explorer — click, right click, or Enter |
35
35
  | Honest re-run | Re-running the assessment re-measures; a plain call still answers from the ten-minute cache |
@@ -65,6 +65,15 @@ Every path is built from this table — a caller selects an **id**, never a path
65
65
  | `app-temp` | scratch folders apps keep inside their own `%APPDATA%` folder instead of `%TEMP%`: `WorkDaddy\client-tmp`, `PersonalCenter\Temp` | aged, 2 days | caution | the owning app may be running and holding files |
66
66
  | `plugin-old-versions` | every version but the newest of each family in the WPS plugin pool `kingsoft\wps\addons\pool\win-i386` | purge | caution | the manager loads the newest; the rest are rollback copies |
67
67
  | `update-packages` | update packages already applied: FTNN `.spd` patches whose build number is below the newest `Program Files\FTNN\app\[version]`, and `WorkDaddy\update` installers below the installed version | purge | caution | decided by version comparison, not by age |
68
+ | `session-backups` | `modify_backup` folders under `%USERPROFILE%\.workbuddy\workspace\sessions\*` — a whole-file snapshot of edits per agent session | purge | caution | the session itself lives beside the snapshot and does not read it back |
69
+ | `agent-logs` | date-named log folders under `%USERPROFILE%\.workbuddy\logs` and `\.workbuddy-ai\logs` | aged, 3 days | safe | nothing reads an old log back |
70
+ | `toolchain-snapshots` | duplicate snapshots under `%USERPROFILE%\.dsh\dsh-ops\bash-ipc`: folders whose `.ops-ipc.json` carries the same `patchedSha256` collapse to the newest | purge | caution | a folder without that metadata is never touched |
71
+ | `editor-server-bundles` | every bundle but the newest under `%USERPROFILE%\vscode-remote-wsl\stable` | purge | caution | the editor re-downloads the one it needs |
72
+ | `database-backups` | `zotero.sqlite*.bak` under `%USERPROFILE%\Zotero` | purge | caution | the live `zotero.sqlite` sits beside the copies |
73
+ | `editor-builds` | complete build trees under `%LOCALAPPDATA%\Programs\Microsoft VS Code` that `bin\code.cmd` does not name, plus `old_*` files whose original still sits beside them | purge | caution | no launcher, a launcher naming a missing build, or a lone build means nothing is dropped |
74
+ | `agent-app-caches` | `Cache` / `Code Cache` / `GPUCache` under `%USERPROFILE%\.workbuddy\app` and `\.workbuddy-ai\app` | purge | caution | the sibling `cache` folder holds spilled conversation text and is never a target |
75
+ | `rewind-snapshots` | `session-*` folders under `%USERPROFILE%\.dsh\rewind-snapshots` | aged, 30 days | caution | a recent session stays restorable |
76
+ | `rotated-logs` | `*.old.log` and `*.log.N` files in the `logs` folders of the agent apps | aged, 3 days | safe | nothing reads a rotated file back |
68
77
 
69
78
  `aged` targets skip anything modified within the retention window; `purge` targets remove every entry. Both keep the target directory itself and leave locked entries alone, counting them as skipped.
70
79
 
@@ -139,6 +148,11 @@ These are enforced in `lib/catalog.js` and must not be relaxed:
139
148
  - Symlinks and junctions met during a walk are skipped, never followed or deleted.
140
149
  - Locked or denied entries are counted as skipped and the walk continues.
141
150
  - The target directory itself is kept; only its contents go.
151
+ - Rules that pick "the newest of a group" fail closed: a family with only one member, a folder
152
+ whose metadata file is missing or whose hash is not a string, and a `vscode-remote-wsl\stable`
153
+ that holds a single bundle all resolve to *nothing to delete*. The newest member is never returned.
154
+ - `editor-builds` drops a build only when `bin\code.cmd` exists and names a different build that is also on disk; `old_x` goes only while `x` is still beside it.
155
+ - `database-backups` matches `.sqlite*.bak` by name only; the live `zotero.sqlite` is never a candidate.
142
156
  - The directory Windows refuses to let an unelevated process write (`SoftwareDistribution\Download`) is labelled `elevation` and excluded from "reclaimable now". `C:\Windows\Temp` is **not** one of them on a default ACL: it grants `BUILTIN\Users` create and delete, so only EBUSY on a live file stops a delete there, which the age limit covers.
143
157
 
144
158
  ### Install
@@ -175,7 +189,7 @@ The bundle's own `cordis.patch.yml` inserts the plugin row; no profile patch edi
175
189
  ### Development
176
190
 
177
191
  ```bash
178
- node smoke.mjs # 67 assertions, zero dependencies
192
+ node smoke.mjs # 68 assertions, zero dependencies
179
193
  node --check lib/client.js # and lib/index.js, lib/catalog.js, lib/audit.js, lib/plan.js
180
194
  ```
181
195
 
@@ -199,6 +213,9 @@ What the smoke test deliberately does **not** cover: anything that walks a real
199
213
  | Dry run deletes nothing | `confirm` omitted, byte counts unchanged |
200
214
  | Drive filter rejects unmounted and malformed volumes | `C:extra`, `Z:`, `abc` → 400 |
201
215
  | Plan excludes elevation bytes from `reclaimNow` | Live audit against this machine |
216
+ | "Keep only the newest of a group" fails closed | Throwaway fixture tree: a same-hash duplicate collapses to the newest, a folder with no metadata is left alone, a different hash is kept, the live database survives (9/9) |
217
+ | Old editor builds need a launcher that proves which one runs | Throwaway fixture tree: a build the launcher does not name goes, no launcher deletes nothing, a launcher naming a missing build deletes nothing, a lone build stays, `old_x` goes only while `x` exists (7/7) |
218
+ | A dry run reports what a real run frees | The 30-day rewind window reports 263 KB not 283 MB, and scan matches the dry run |
202
219
  | Visual layout | Checked by hand in the running Web UI. No browser automation here, so this one is a human check, not a test. |
203
220
 
204
221
  ### Implementation notes
@@ -223,16 +240,16 @@ What the smoke test deliberately does **not** cover: anything that walks a real
223
240
  ```
224
241
  ├─ package.json dsh.bundle.patch + dsh.client { platform: "web" }
225
242
  ├─ cordis.patch.yml - insert: id: dsh-disk-cleaner
226
- ├─ lib/index.js (405) Host: HTTP route + disk_cleaner tool, same run() for both; reveal
227
- ├─ lib/catalog.js (688) The 19 targets, measurePath / purgePath / resolveTargets / drives
243
+ ├─ lib/index.js (411) Host: HTTP route + disk_cleaner tool, same run() for both; reveal
244
+ ├─ lib/catalog.js (969) The 28 targets, measurePath / purgePath / resolveTargets / drives
228
245
  ├─ lib/audit.js (365) Read-only assessment, 10-minute cache, areaPaths, exposes no deletion
229
246
  ├─ lib/plan.js (150) Pure: measurements → ordered steps
230
- ├─ lib/client.js (1355) Client half: slots, panel, preferences, zh/en dictionaries, CSS
247
+ ├─ lib/client.js (1379) Client half: slots, panel, preferences, zh/en dictionaries, CSS
231
248
  ├─ locale/{en,zh}.json Display metadata (meta.title / meta.description)
232
249
  ├─ icon.svg Plugin icon
233
250
  ├─ README.md This file
234
251
  ├─ LICENSE MIT
235
- └─ smoke.mjs 67 assertions, zero dependencies
252
+ └─ smoke.mjs 68 assertions, zero dependencies
236
253
  ```
237
254
 
238
255
  Client-half slots: `sidebar.panellist` (order 50, disposed in settings-only mode), `main` (keyed by the package name), `settings.section` (order 30, disposed in sidebar-only mode), `plugins.bundle.config` (keyed by the package name).
@@ -244,7 +261,7 @@ Client-half slots: `sidebar.panellist` (order 50, disposed in settings-only mode
244
261
 
245
262
  **dsh-disk-cleaner** 是 [DeepSeek Harness](https://github.com/deepseek-ai)(DSH)的磁盘空间插件。它做两件不同的事,并且刻意分开:
246
263
 
247
- 1. **清理** —— 十九个已知安全的位置(临时目录、包管理器存储、浏览器缓存、崩溃转储、回收站、更新安装包残留、各应用的缓存与日志、被淘汰的插件版本与已应用的更新包)。只有这些会被删除。
264
+ 1. **清理** —— 二十八个已知安全的位置(临时目录、包管理器存储、浏览器缓存、崩溃转储、回收站、更新安装包残留、各应用的缓存与日志、被淘汰的插件版本与已应用的更新包)。只有这些会被删除。
248
265
  2. **评估** —— 所有本插件**不会**删的东西(已装程序、WSL 虚拟磁盘、Windows 组件库、聊天软件数据、你自己的文件夹)。只测量、只列出,绝不删除。
249
266
 
250
267
  评估的最后是一份**处理方案**:同一批数字按「你要付出多少代价」排序,本插件做不到的步骤附上确切的 Windows 命令。
@@ -255,9 +272,9 @@ Client-half slots: `sidebar.panellist` (order 50, disposed in settings-only mode
255
272
 
256
273
  | 功能 | 说明 |
257
274
  | --- | --- |
258
- | 扫描 | 并发测量全部十九个目标,显示各自占用 |
275
+ | 扫描 | 并发测量全部二十八个目标,显示各自占用 |
259
276
  | 按盘过滤 | 已挂载卷的胶囊按钮;扫描与清理都可限定单盘,该盘上为空的项会隐藏 |
260
- | 风险标注 | 每个目标都标 `安全` 或 `注意`,并给一行理由(`in-use` / `rebuild` / `elevation` / `pending-update` / `rollback` / `superseded`),图例常驻,所以「注意」永远不是「说不清」 |
277
+ | 风险标注 | 每个目标都标 `安全` 或 `注意`,并给一行理由(`in-use` / `rebuild` / `elevation` / `pending-update` / `rollback` / `superseded` / `history` / `duplicate` / `database-backup`),图例常驻,所以「注意」永远不是「说不清」 |
261
278
  | 保留期删除 | `temp` 与 `windows-temp` 只删一天前的文件;被运行中程序占住的自动跳过 |
262
279
  | 空间评估 | 只读遍历磁盘,按 Windows 自身 / 已装软件 / 你自己的文件 分组,另列占用最大的十个应用数据目录。每一行都能打开所在目录——单击、右键或回车 |
263
280
  | 重新评估真的重测 | 「重新评估」会重新测量;普通调用仍然走十分钟缓存 |
@@ -293,6 +310,15 @@ Client-half slots: `sidebar.panellist` (order 50, disposed in settings-only mode
293
310
  | `app-temp` | 应用自己放在 `%APPDATA%` 里的临时目录(不走 `%TEMP%`):`WorkDaddy\client-tmp`、`PersonalCenter\Temp` | 保留期 2 天 | 注意 | 应用可能正在运行并占用其中的文件 |
294
311
  | `plugin-old-versions` | WPS 插件池 `kingsoft\wps\addons\pool\win-i386` 里,每个插件族除最高版本以外的全部版本 | 全清 | 注意 | 管理器加载最高版本,其余是回滚副本 |
295
312
  | `update-packages` | 已应用的更新包:FTNN 的 `.spd` 补丁(build 号低于 `Program Files\FTNN\app\[版本]` 中最新者),以及 `WorkDaddy\update` 里低于已装版本的安装包 | 全清 | 注意 | 按版本号比较判断,不按时间 |
313
+ | `session-backups` | `%USERPROFILE%\.workbuddy\workspace\sessions\*` 下的 `modify_backup` 目录——每个 agent 会话的整文件修改快照 | 全清 | 注意 | 会话本体在快照旁边,不会读回这些文件 |
314
+ | `agent-logs` | `%USERPROFILE%\.workbuddy\logs` 与 `\.workbuddy-ai\logs` 下按日期命名的日志目录 | 保留期 3 天 | 安全 | 旧日志不会被读回 |
315
+ | `toolchain-snapshots` | `%USERPROFILE%\.dsh\dsh-ops\bash-ipc` 下重复的快照:`.ops-ipc.json` 里 `patchedSha256` 相同的目录只留最新一份 | 全清 | 注意 | 没有该元数据的目录永不触碰 |
316
+ | `editor-server-bundles` | `%USERPROFILE%\vscode-remote-wsl\stable` 下除最新以外的服务包 | 全清 | 注意 | 编辑器需要时会重新下载 |
317
+ | `database-backups` | `%USERPROFILE%\Zotero` 下的 `zotero.sqlite*.bak` | 全清 | 注意 | 正在用的 `zotero.sqlite` 就在副本旁边 |
318
+ | `editor-builds` | `%LOCALAPPDATA%\Programs\Microsoft VS Code` 下 `bin\code.cmd` 未指向的完整构建目录,以及原件仍在旁边的 `old_*` 文件 | 全清 | 注意 | 没有启动器、启动器指向的构建不在磁盘上、或只有一份构建时,一律不删 |
319
+ | `agent-app-caches` | `%USERPROFILE%\.workbuddy\app` 与 `\.workbuddy-ai\app` 下的 `Cache` / `Code Cache` / `GPUCache` | 全清 | 注意 | 同级的 `cache` 目录存的是对话溢写内容,从不作为目标 |
320
+ | `rewind-snapshots` | `%USERPROFILE%\.dsh\rewind-snapshots` 下的 `session-*` 目录 | 保留期 30 天 | 注意 | 最近的会话仍然可以回滚 |
321
+ | `rotated-logs` | 各 agent 应用 `logs` 目录下的 `*.old.log` 与 `*.log.N` 文件 | 保留期 3 天 | 安全 | 轮转掉的日志不会被读回 |
296
322
 
297
323
  保留期方式会跳过保留期内修改过的文件;全清方式清掉全部条目。两者都保留目标目录本身,并把锁定或无权限的条目跳过计数。
298
324
 
@@ -308,8 +334,8 @@ Client-half slots: `sidebar.panellist` (order 50, disposed in settings-only mode
308
334
  | `reclaim-caution` | 注意目标共 ≥200 MB(不含需提权的) | 是,一个按钮 |
309
335
  | `wsl-compact` | WSL 映像 ≥1 GB | 否 —— `wsl --shutdown` + `diskpart` 的 `compact vdisk` |
310
336
  | `winsxs-cleanup` | WinSxS ≥1 GB | 否 —— `Dism.exe /Online /Cleanup-Image /StartComponentCleanup` |
311
- | `elevation-clean` | 需提权目标 ≥200 MB | 否 —— 以管理员身份运行本插件 |
312
337
  | `hibernate-off` | `system-files` ≥200 MB | 否 —— `powercfg.exe /hibernate off` |
338
+ | `elevation-clean` | 需提权目标 ≥200 MB | 否 —— 以管理员身份运行本插件 |
313
339
  | `app-review` | 单个应用数据目录 ≥1 GB,取前 3 个且未被其它步骤覆盖 | 否 —— 走卸载,绝不删目录 |
314
340
  | `move-folder` | 个人文件夹 ≥2 GB,且另有盘有空间 | 否 —— 属性 → 位置 |
315
341
  | `pressure` | 系统盘可用 < 12% | 否 —— 作为上述步骤的背景 |
@@ -367,6 +393,10 @@ Client-half slots: `sidebar.panellist` (order 50, disposed in settings-only mode
367
393
  - 遍历时遇到符号链接与 junction 一律跳过,不跟随也不删除。
368
394
  - 锁定或无权限的条目计为跳过,遍历继续。
369
395
  - 保留目标目录本身,只清内容。
396
+ - 「只留最新一份」这类规则一律选保守的一侧:族内只有一个成员、元数据文件缺失或哈希不是字符串、
397
+ `vscode-remote-wsl\stable` 下只有一个服务包,结果都是*没有可删项*。最新那一份永远不会被返回。
398
+ - `editor-builds` 只有在 `bin\code.cmd` 存在且指向另一份确实在磁盘上的构建时才删;`old_x` 也只有在 `x` 仍在旁边时才删。
399
+ - `database-backups` 只按名字匹配 `.sqlite*.bak`,正在用的 `zotero.sqlite` 永不成为候选。
370
400
  - 那个拒绝普通权限写入的 Windows 目录标为 `elevation`,并排除在「现在能回收」之外。
371
401
 
372
402
  ### 安装
@@ -407,7 +437,7 @@ git clone https://github.com/stallenlu/dsh-disk-cleaner
407
437
  ### 开发
408
438
 
409
439
  ```bash
410
- node smoke.mjs # 67 条断言,零依赖
440
+ node smoke.mjs # 68 条断言,零依赖
411
441
  node --check lib/client.js # 以及 lib/index.js、lib/catalog.js、lib/audit.js、lib/plan.js
412
442
  ```
413
443
 
@@ -431,6 +461,9 @@ node --check lib/client.js # 以及 lib/index.js、lib/catalog.js、li
431
461
  | 试运行不删任何东西 | 不传 `confirm`,字节数不变 |
432
462
  | 盘过滤拒绝未挂载与畸形卷名 | `C:extra`、`Z:`、`abc` → 400 |
433
463
  | 方案不把提权目标的字节算进「现在能回收」 | 在本机跑真实 audit |
464
+ | 「只留最新一份」一律选保守一侧 | 一次性 fixture 目录:同哈希的重复项收敛到最新、无元数据的目录不动、不同哈希保留、正在用的数据库完好(9/9) |
465
+ | 旧版编辑器构建要有启动器作证才删 | 一次性 fixture 目录:启动器未指向的构建会删、没有启动器一律不删、启动器指向的构建不在磁盘上也不删、只有一份构建时不删、`old_x` 只在 `x` 仍在时删(7/7) |
466
+ | 预演报告的字节数等于真删能释放的字节数 | 30 天的回滚窗口报 263 KB 而不是 283 MB,且扫描结果与预演一致 |
434
467
  | 视觉排版 | 在运行中的 Web UI 里手工确认过。本环境没有浏览器自动化,所以这条是人眼检查,不是测试。 |
435
468
 
436
469
  ### 实现要点
@@ -455,16 +488,16 @@ node --check lib/client.js # 以及 lib/index.js、lib/catalog.js、li
455
488
  ```
456
489
  ├─ package.json dsh.bundle.patch + dsh.client { platform: "web" }
457
490
  ├─ cordis.patch.yml - insert: id: dsh-disk-cleaner
458
- ├─ lib/index.js (405) Host:HTTP 路由 + disk_cleaner 工具,共用同一个 run(),含 reveal
459
- ├─ lib/catalog.js (688) 19 个目标,measurePath / purgePath / resolveTargets / drives
491
+ ├─ lib/index.js (411) Host:HTTP 路由 + disk_cleaner 工具,共用同一个 run(),含 reveal
492
+ ├─ lib/catalog.js (969) 28 个目标,measurePath / purgePath / resolveTargets / drives
460
493
  ├─ lib/audit.js (365) 只读评估,10 分钟缓存,带 areaPaths,不暴露任何删除
461
494
  ├─ lib/plan.js (150) 纯函数:测量结果 → 有序步骤
462
- ├─ lib/client.js (1355) Client 半面:slot、面板、偏好、zh/en 字典、CSS
495
+ ├─ lib/client.js (1379) Client 半面:slot、面板、偏好、zh/en 字典、CSS
463
496
  ├─ locale/{en,zh}.json 展示元数据(meta.title / meta.description)
464
497
  ├─ icon.svg 插件图标
465
498
  ├─ README.md 本文件
466
499
  ├─ LICENSE MIT
467
- └─ smoke.mjs 67 条断言,零依赖
500
+ └─ smoke.mjs 68 条断言,零依赖
468
501
  ```
469
502
 
470
503
  Client 半面注册的 slot:`sidebar.panellist`(order 50,仅设置页模式下拆除)、`main`(以包名为 key)、`settings.section`(order 30,仅侧边栏模式下拆除)、`plugins.bundle.config`(以包名为 key)。
package/lib/catalog.js CHANGED
@@ -274,14 +274,209 @@ const supersededUpdatePackages = () => [
274
274
  ...pooledOldVersions(path.join(env('APPDATA') ?? '', 'WorkDaddy', 'update'), /^(.+)-([0-9][0-9._]*)(\.[A-Za-z0-9]+)?$/),
275
275
  ];
276
276
 
277
+ /** The user profile, which roots every target built from a dot-directory in the home folder. */
278
+ const home = () => env('USERPROFILE') ?? '';
279
+
280
+ /**
281
+ * Per-session backup dumps an editor's agent keeps beside a workspace, such as WorkBuddy's
282
+ * `sessions/<id>/modify_backup`. Each file is a whole-file snapshot ten-odd days old; the
283
+ * session's live state is elsewhere in the same folder, so the dumps are pure history.
284
+ */
285
+ const sessionBackups = () => {
286
+ const sessions = path.join(home(), '.workbuddy', 'workspace', 'sessions');
287
+ const out = [];
288
+ for (const entry of listDir(sessions)) {
289
+ if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
290
+ const backup = path.join(sessions, entry.name, 'modify_backup');
291
+ if (isDir(backup)) out.push(backup);
292
+ }
293
+ return out;
294
+ };
295
+
296
+ /** `2026-11-04` and `20261104` both name one day; anything else is not a log archive. */
297
+ const LOG_DAY = /^(\d{4})-?(\d{2})-?(\d{2})$/;
298
+
299
+ /**
300
+ * Day-named log archives an app writes and never prunes. The age limit on the target does
301
+ * the pruning per file, so this only has to name the folders that look like a date.
302
+ */
303
+ const datedLogDirs = (roots) => {
304
+ const out = [];
305
+ for (const root of roots) {
306
+ for (const entry of listDir(root)) {
307
+ if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
308
+ if (LOG_DAY.exec(entry.name) === null) continue;
309
+ out.push(path.join(root, entry.name));
310
+ }
311
+ }
312
+ return out;
313
+ };
314
+
315
+ /**
316
+ * Sibling directories that repeat each other, decided by the content hash the owner writes
317
+ * into its own metadata file. A snapshot keeper leaves the previous extraction behind after
318
+ * an upgrade; two of them here were byte-identical. The newest stays, and a sibling with no
319
+ * metadata proves nothing, so it is never touched.
320
+ */
321
+ const repeatedSiblings = (parent, metaName, key) => {
322
+ if (!isDir(parent)) return [];
323
+ const groups = new Map();
324
+ for (const entry of listDir(parent)) {
325
+ if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
326
+ const abs = path.join(parent, entry.name);
327
+ let stamp;
328
+ try {
329
+ stamp = JSON.parse(fs.readFileSync(path.join(abs, metaName), 'utf8'))[key];
330
+ } catch {
331
+ continue;
332
+ }
333
+ if (typeof stamp !== 'string' || stamp === '') continue;
334
+ if (!groups.has(stamp)) groups.set(stamp, []);
335
+ let mtimeMs = 0;
336
+ try {
337
+ mtimeMs = fs.statSync(abs).mtimeMs;
338
+ } catch {
339
+ /* unreadable sorts last, so a broken copy is the one dropped */
340
+ }
341
+ groups.get(stamp).push({ abs, mtimeMs });
342
+ }
343
+ const out = [];
344
+ for (const list of groups.values()) {
345
+ if (list.length < 2) continue;
346
+ list.sort((a, b) => b.mtimeMs - a.mtimeMs);
347
+ for (const older of list.slice(1)) out.push(older.abs);
348
+ }
349
+ return out;
350
+ };
351
+
352
+ /** Every child directory but the most recently written one; a lone child is left alone. */
353
+ const keepNewestChild = (parent) => {
354
+ if (!isDir(parent)) return [];
355
+ const stamped = listDir(parent)
356
+ .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink())
357
+ .map((entry) => {
358
+ const abs = path.join(parent, entry.name);
359
+ let mtimeMs = 0;
360
+ try {
361
+ mtimeMs = fs.statSync(abs).mtimeMs;
362
+ } catch {
363
+ /* unreadable sorts last */
364
+ }
365
+ return { abs, mtimeMs };
366
+ })
367
+ .sort((a, b) => b.mtimeMs - a.mtimeMs);
368
+ if (stamped.length < 2) return [];
369
+ return stamped.slice(1).map((item) => item.abs);
370
+ };
371
+
372
+ /**
373
+ * An editor that ships a whole runtime per commit leaves the previous one behind after every
374
+ * update: VS Code kept two complete 764 MB trees plus `old_Code.exe`. Unlike a version holder,
375
+ * the tree names are commit hashes, so the newest mtime proves nothing — the launcher does.
376
+ * `bin\code.cmd` names the live hash, and a build is only dropped when that launcher exists,
377
+ * parses, and points at a different build that is also present. No launcher, no deletion.
378
+ *
379
+ * The renamed `old_*` copies are dead weight only while the file they duplicate still sits
380
+ * beside them; a lone `old_x` may be the only copy left, so it stays.
381
+ */
382
+ const vscodeSuperseded = () => {
383
+ const appDir = path.join(env('LOCALAPPDATA') ?? '', 'Programs', 'Microsoft VS Code');
384
+ if (!isDir(appDir)) return [];
385
+ const out = [];
386
+ let live = '';
387
+ try {
388
+ const launcher = fs.readFileSync(path.join(appDir, 'bin', 'code.cmd'), 'utf8');
389
+ const match = /[\\/]([0-9a-f]{10,})[\\/]/.exec(launcher);
390
+ if (match !== null) live = match[1];
391
+ } catch {
392
+ /* no launcher means no evidence about which build runs, so nothing is dropped */
393
+ }
394
+ if (live !== '') {
395
+ const builds = listDir(appDir)
396
+ .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink())
397
+ .map((entry) => entry.name)
398
+ .filter((name) => /^[0-9a-f]{10,}$/.test(name));
399
+ if (builds.length >= 2 && builds.includes(live)) {
400
+ for (const name of builds) if (name !== live) out.push(path.join(appDir, name));
401
+ }
402
+ }
403
+ for (const dir of [appDir, path.join(appDir, 'bin')]) {
404
+ for (const entry of listDir(dir)) {
405
+ if (!entry.isFile() || entry.isSymbolicLink()) continue;
406
+ const match = /^old_(.+)$/.exec(entry.name);
407
+ if (match === null) continue;
408
+ if (!isFile(path.join(dir, match[1]))) continue;
409
+ out.push(path.join(dir, entry.name));
410
+ }
411
+ }
412
+ return out;
413
+ };
414
+
415
+ /**
416
+ * The Chromium caches an Electron-based agent app writes under its own app folder. The root
417
+ * is spelled out per app because the sibling `cache` next to it (`~/.workbuddy/cache`) holds
418
+ * spilled conversation text rather than anything regenerable — it stays.
419
+ */
420
+ const agentAppCaches = () => {
421
+ const out = [];
422
+ for (const name of ['.workbuddy', '.workbuddy-ai']) {
423
+ const app = path.join(home(), name, 'app');
424
+ out.push(...subdirs(path.join(app, 'session'), ['Cache', 'Code Cache', 'GPUCache', 'DawnCache', 'ShaderCache']));
425
+ out.push(...subdirs(app, ['cache', 'CodeCache']));
426
+ }
427
+ return out;
428
+ };
429
+
430
+ /**
431
+ * Rewind snapshots this harness writes one folder per session, never pruning. The folders are
432
+ * named by session id, so age is the only signal; the target's 30-day floor keeps a recent
433
+ * session restorable.
434
+ */
435
+ const rewindSnapshots = () => {
436
+ const root = path.join(home(), '.dsh', 'rewind-snapshots');
437
+ return listDir(root)
438
+ .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink())
439
+ .map((entry) => path.join(root, entry.name));
440
+ };
441
+
442
+ /**
443
+ * A log file rotated out of the way — `daemon.old.log`, `main.log.1` — as opposed to the
444
+ * day-named folders the `agent-logs` target covers. Nothing reads a rotated file at runtime.
445
+ */
446
+ const rotatedLogs = () => {
447
+ const out = [];
448
+ for (const name of ['.workbuddy', '.workbuddy-ai', '.qoder', '.zcode', '.codebuddy']) {
449
+ const logs = path.join(home(), name, 'logs');
450
+ for (const entry of listDir(logs)) {
451
+ if (!entry.isFile() || entry.isSymbolicLink()) continue;
452
+ if (!/\.(old\.log|log\.[0-9]+)$/i.test(entry.name)) continue;
453
+ out.push(path.join(logs, entry.name));
454
+ }
455
+ }
456
+ return out;
457
+ };
458
+
459
+ /** The one-generation database copies Zotero writes beside the library it is using. */
460
+ const zoteroBackups = () => {
461
+ const data = path.join(home(), 'Zotero');
462
+ return listDir(data)
463
+ .filter((entry) => entry.isFile() && !entry.isSymbolicLink())
464
+ .filter((entry) => /\.sqlite[0-9.]*\.bak$/i.test(entry.name))
465
+ .map((entry) => path.join(data, entry.name));
466
+ };
467
+
277
468
  /**
278
469
  * `purge` targets drop every entry under the path. `aged` targets keep anything modified
279
470
  * within `minAgeDays`, because those files may belong to a process that is still running.
280
471
  *
281
472
  * `note` says why a target carries the `caution` risk, in one stable code the UI
282
473
  * translates: 'in-use' (a running program may hold these files), 'rebuild' (the owner
283
- * regenerates them, so the first use afterwards is slower), or 'elevation' (Windows
284
- * refuses an unelevated delete). Safe targets have none.
474
+ * regenerates them, so the first use afterwards is slower), 'elevation' (Windows
475
+ * refuses an unelevated delete), 'pending-update' (a download that may not be applied
476
+ * yet), 'rollback' (an older version kept beside the live one), 'superseded' (an update
477
+ * package the installed version already contains), 'history' (a snapshot nothing reads
478
+ * back), 'duplicate' (a byte-identical copy of a live directory) or 'database-backup' (a
479
+ * copy of a database file made before an upgrade). Safe targets have none.
285
480
  */
286
481
  const CATALOG = [
287
482
  {
@@ -437,6 +632,79 @@ const CATALOG = [
437
632
  roots: ['APPDATA'],
438
633
  paths: () => supersededUpdatePackages(),
439
634
  },
635
+ {
636
+ id: 'session-backups',
637
+ kind: 'purge',
638
+ risk: 'caution',
639
+ note: 'history',
640
+ roots: ['USERPROFILE'],
641
+ paths: () => sessionBackups(),
642
+ },
643
+ {
644
+ id: 'agent-logs',
645
+ kind: 'aged',
646
+ minAgeDays: 3,
647
+ risk: 'safe',
648
+ roots: ['USERPROFILE'],
649
+ paths: () => datedLogDirs([path.join(home(), '.workbuddy', 'logs'), path.join(home(), '.workbuddy-ai', 'logs')]),
650
+ },
651
+ {
652
+ id: 'toolchain-snapshots',
653
+ kind: 'purge',
654
+ risk: 'caution',
655
+ note: 'duplicate',
656
+ roots: ['USERPROFILE'],
657
+ paths: () => repeatedSiblings(path.join(home(), '.dsh', 'dsh-ops', 'bash-ipc'), '.ops-ipc.json', 'patchedSha256'),
658
+ },
659
+ {
660
+ id: 'editor-server-bundles',
661
+ kind: 'purge',
662
+ risk: 'caution',
663
+ note: 'superseded',
664
+ roots: ['USERPROFILE'],
665
+ paths: () => keepNewestChild(path.join(home(), 'vscode-remote-wsl', 'stable')),
666
+ },
667
+ {
668
+ id: 'database-backups',
669
+ kind: 'purge',
670
+ risk: 'caution',
671
+ note: 'database-backup',
672
+ roots: ['USERPROFILE'],
673
+ paths: () => zoteroBackups(),
674
+ },
675
+ {
676
+ id: 'editor-builds',
677
+ kind: 'purge',
678
+ risk: 'caution',
679
+ note: 'superseded',
680
+ roots: ['LOCALAPPDATA'],
681
+ paths: () => vscodeSuperseded(),
682
+ },
683
+ {
684
+ id: 'agent-app-caches',
685
+ kind: 'purge',
686
+ risk: 'caution',
687
+ note: 'rebuild',
688
+ roots: ['USERPROFILE'],
689
+ paths: () => agentAppCaches(),
690
+ },
691
+ {
692
+ id: 'rewind-snapshots',
693
+ kind: 'aged',
694
+ minAgeDays: 30,
695
+ risk: 'caution',
696
+ note: 'history',
697
+ roots: ['USERPROFILE'],
698
+ paths: () => rewindSnapshots(),
699
+ },
700
+ {
701
+ id: 'rotated-logs',
702
+ kind: 'aged',
703
+ minAgeDays: 3,
704
+ risk: 'safe',
705
+ roots: ['USERPROFILE'],
706
+ paths: () => rotatedLogs(),
707
+ },
440
708
  ];
441
709
 
442
710
  const byId = new Map(CATALOG.map((entry) => [entry.id, entry]));
@@ -506,10 +774,16 @@ export function resolveTargets(only, drive) {
506
774
  });
507
775
  }
508
776
 
509
- export async function measurePath(abs) {
777
+ /**
778
+ * Total the files under `abs`. With a `cutoff`, only files older than it count, so a dry run
779
+ * reports what a real run would actually delete instead of the whole folder.
780
+ */
781
+ export async function measurePath(abs, cutoff) {
510
782
  if (isFile(abs)) {
511
783
  try {
512
- return { bytes: fs.statSync(abs).size, files: 1 };
784
+ const stat = fs.statSync(abs);
785
+ if (cutoff !== undefined && stat.mtimeMs > cutoff) return { bytes: 0, files: 0 };
786
+ return { bytes: stat.size, files: 1 };
513
787
  } catch {
514
788
  return { bytes: 0, files: 0 };
515
789
  }
@@ -536,7 +810,9 @@ export async function measurePath(abs) {
536
810
  }
537
811
  if (!entry.isFile()) continue;
538
812
  try {
539
- bytes += (await fsp.stat(path.join(dir, entry.name))).size;
813
+ const stat = await fsp.stat(path.join(dir, entry.name));
814
+ if (cutoff !== undefined && stat.mtimeMs > cutoff) continue;
815
+ bytes += stat.size;
540
816
  files += 1;
541
817
  } catch {
542
818
  /* a file that vanished or is locked contributes nothing */
@@ -549,15 +825,20 @@ export async function measurePath(abs) {
549
825
  return { bytes, files };
550
826
  }
551
827
 
552
- /** Measure every resolved target concurrently, keeping the host event loop free. */
828
+ /**
829
+ * Measure every resolved target concurrently, keeping the host event loop free. Each target's
830
+ * own age limit is applied, so the numbers answer "what would a clean free right now" rather
831
+ * than "how much is in the folder" — the two differ for every `aged` target.
832
+ */
553
833
  export async function scan(only, drive) {
554
834
  const targets = resolveTargets(only, drive);
555
835
  const measured = await Promise.all(
556
836
  targets.map(async (target) => {
837
+ const cutoff = target.minAgeDays > 0 ? Date.now() - target.minAgeDays * DAY : undefined;
557
838
  let bytes = 0;
558
839
  let files = 0;
559
840
  for (const abs of target.paths) {
560
- const size = await measurePath(abs);
841
+ const size = await measurePath(abs, cutoff);
561
842
  bytes += size.bytes;
562
843
  files += size.files;
563
844
  }
@@ -628,7 +909,7 @@ export async function clean(ids, options = {}) {
628
909
  let bytes = 0;
629
910
  let files = 0;
630
911
  for (const abs of target.paths) {
631
- const size = await measurePath(abs);
912
+ const size = await measurePath(abs, cutoff);
632
913
  bytes += size.bytes;
633
914
  files += size.files;
634
915
  }
package/lib/client.js CHANGED
@@ -41,6 +41,9 @@ window.__ModuleLoader__.load({
41
41
  'why_pending-update': '只清 {n} 天前的下载,避免删掉还没装的更新',
42
42
  why_rollback: '每个插件/程序只留版本号最高的一份,其余是回滚副本',
43
43
  why_superseded: '版本号不高于已装版本的更新包,装着的那份已经生效',
44
+ why_history: '每个会话的整文件备份,删了不影响会话本身',
45
+ why_duplicate: '内容完全相同的重复副本,保留最新那份',
46
+ 'why_database-backup': '升级前的数据库副本,正在用的数据库还在旁边',
44
47
  pathCount: '{n} 处',
45
48
  driveLabel: '清理范围',
46
49
  allDrives: '全部磁盘',
@@ -66,6 +69,15 @@ window.__ModuleLoader__.load({
66
69
  'target_app-temp': '各应用临时目录',
67
70
  'target_plugin-old-versions': '插件旧版本',
68
71
  'target_update-packages': '已应用的更新包',
72
+ 'target_session-backups': '会话备份快照',
73
+ 'target_agent-logs': '按天的日志归档',
74
+ 'target_toolchain-snapshots': '重复的工具链快照',
75
+ 'target_editor-server-bundles': '多余的编辑器服务包',
76
+ 'target_database-backups': '数据库备份副本',
77
+ 'target_editor-builds': '编辑器的旧版构建',
78
+ 'target_agent-app-caches': 'AI 应用的浏览器缓存',
79
+ 'target_rewind-snapshots': '过期的回滚快照',
80
+ 'target_rotated-logs': '轮转掉的日志',
69
81
  auditTitle: '空间评估(本插件不会删除)',
70
82
  auditHint: '统计缓存之外真正占空间的东西:已装软件、WSL 虚拟磁盘、Windows 组件库,以及你自己的文件。这些一律不由本插件删除,只列出供你判断。',
71
83
  auditRun: '开始评估',
@@ -185,6 +197,9 @@ window.__ModuleLoader__.load({
185
197
  'why_pending-update': 'only downloads older than {n} day(s), so a pending update survives',
186
198
  why_rollback: 'only the highest version of each family stays; the rest are rollback copies',
187
199
  why_superseded: 'the update package version is not above what is installed, so it is already applied',
200
+ why_history: 'a whole-file backup per session; removing it does not touch the session',
201
+ why_duplicate: 'an identical copy; the newest one is kept',
202
+ 'why_database-backup': 'a copy made before an upgrade; the live database is beside it',
188
203
  pathCount: '{n} location(s)',
189
204
  driveLabel: 'Limit to',
190
205
  allDrives: 'All drives',
@@ -210,6 +225,15 @@ window.__ModuleLoader__.load({
210
225
  'target_app-temp': 'App scratch folders',
211
226
  'target_plugin-old-versions': 'Old plugin versions',
212
227
  'target_update-packages': 'Applied update packages',
228
+ 'target_session-backups': 'Session backup snapshots',
229
+ 'target_agent-logs': 'Dated log archives',
230
+ 'target_toolchain-snapshots': 'Duplicate toolchain snapshots',
231
+ 'target_editor-server-bundles': 'Extra editor server bundles',
232
+ 'target_database-backups': 'Database backup copies',
233
+ 'target_editor-builds': 'Old editor builds',
234
+ 'target_agent-app-caches': 'Browser caches of the AI apps',
235
+ 'target_rewind-snapshots': 'Expired rewind snapshots',
236
+ 'target_rotated-logs': 'Rotated-out log files',
213
237
  auditTitle: 'Space assessment (this plugin deletes none of it)',
214
238
  auditHint: 'What actually takes up room outside caches: installed programs, WSL disk images, the Windows component store, and your own files. None of it is removed here; it is listed so you can decide.',
215
239
  auditRun: 'Run assessment',
package/lib/index.js CHANGED
@@ -197,6 +197,10 @@ const NOTE_MEANING = {
197
197
  elevation: 'Windows refuses an unelevated delete here; run the plugin elevated to reach these bytes',
198
198
  rollback: 'an older version the app keeps for rollback; what it runs now is the newest of that family',
199
199
  superseded: 'an update package whose version is at or below what is already installed',
200
+ 'pending-update': 'a downloaded update inside the age limit, so it may not be applied yet',
201
+ history: 'a backup snapshot of file edits that nothing reads back; the live state sits beside it',
202
+ duplicate: 'a byte-identical copy of a directory that is still present',
203
+ 'database-backup': 'a copy of a database file taken before an upgrade; the live database is beside it',
200
204
  };
201
205
 
202
206
  const formatBytes = (bytes) => {
@@ -274,7 +278,11 @@ export function apply(ctx) {
274
278
  description:
275
279
  'Inspect and reclaim disk space on this Windows machine from known-safe cache locations only: ' +
276
280
  'temp directories, package manager caches (npm, pnpm, pip, uv), crash dumps, browser and editor ' +
277
- 'caches, and the Windows internet cache. Call with action "overview" to list drives and target ids, ' +
281
+ 'caches, the Windows internet cache, per-app caches, logs and scratch folders under %APPDATA%, ' +
282
+ 'superseded plugin versions and applied update packages, the backup snapshots, dated logs, ' +
283
+ 'rotated-out log files, duplicate toolchain copies and database backups under the user profile, ' +
284
+ 'editor builds their launcher no longer names, and the Chromium caches of the agent apps. ' +
285
+ 'Call with action "overview" to list drives and target ids, ' +
278
286
  '"scan" to measure them, and "clean" to delete. clean without confirm: true is a dry run that only ' +
279
287
  'reports what it would free, so the user can approve the amount before anything is removed. ' +
280
288
  'Action "audit" instead assesses the space that CANNOT be cleaned automatically — installed programs, ' +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-disk-cleaner",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "type": "module",
5
5
  "description": "Disk Cleaner for DSH: scan known-safe cache locations, see what they occupy, and reclaim the space from a panel or from the agent.",
6
6
  "keywords": [
package/smoke.mjs CHANGED
@@ -262,13 +262,19 @@ check('tool description warns audit is read-only', /read-only: it never removes
262
262
  check('every effect is labelled', applied.every((label) => typeof label === 'string' && label.startsWith('dsh-disk-cleaner:')));
263
263
 
264
264
  const ids = [...catalog.matchAll(/^\s{4}id: '([a-z-]+)',$/gm)].map((m) => m[1]);
265
- check('catalog has the documented 19 targets', ids.length === 19, `got ${ids.length}`);
265
+ check('catalog has the documented 28 targets', ids.length === 28, `got ${ids.length}`);
266
266
  check('every catalog id has a client label', ids.every((id) => zhKeys.includes(`target_${id}`) && enKeys.includes(`target_${id}`)));
267
- check('every note code has an explanation', ['why_safe', 'why_in-use', 'why_rebuild', 'why_elevation', 'why_pending-update', 'why_rollback', 'why_superseded'].every((k) => zhKeys.includes(k) && enKeys.includes(k)));
267
+ check('every note code has an explanation', ['why_safe', 'why_in-use', 'why_rebuild', 'why_elevation', 'why_pending-update', 'why_rollback', 'why_superseded', 'why_history', 'why_duplicate', 'why_database-backup'].every((k) => zhKeys.includes(k) && enKeys.includes(k)));
268
268
  const areaIds = [...auditSrc.matchAll(/^\s{6}id: '([a-z-]+)',$/gm)].map((m) => m[1]);
269
269
  check('every assessment area has a translated label and reason', areaIds.length > 0 && areaIds.every((id) => zhKeys.includes(`area_${id}`) && zhKeys.includes(`area_${id}_why`) && enKeys.includes(`area_${id}`) && enKeys.includes(`area_${id}_why`)), `areas: ${areaIds.join(',')}`);
270
270
  check('a reveal request names an area, never a path', index.includes("action === 'reveal'") && auditSrc.includes('export function areaPaths') && !/revealPath[\s\S]{0,200}payload\.path/.test(index));
271
271
  check('no caller may pass a raw path', !/parameters[\s\S]{0,400}paths/.test(index) && catalog.includes('Callers select catalog ids'));
272
+ check(
273
+ 'a dry run reports what a real run would delete, not the folder size',
274
+ catalog.includes('export async function measurePath(abs, cutoff)') &&
275
+ (catalog.match(/await measurePath\(abs, cutoff\)/g) ?? []).length === 2,
276
+ `${(catalog.match(/await measurePath\(abs, cutoff\)/g) ?? []).length} cutoff-aware call sites`,
277
+ );
272
278
 
273
279
  const codes = [...new Set([...plan.matchAll(/code: '([a-z-]+)'/g)].map((m) => m[1]))];
274
280
  check('plan emits the documented 9 step codes', codes.length === 9, `got ${codes.length}`);