The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(disk-cleanup): never rmtree protected top-level dirs; never track kanban/
teknium133f3d96b996d
diff --git a/plugins/disk-cleanup/README.md b/plugins/disk-cleanup/README.mdindex f3506da045d..d9410f2eb81 100644--- a/plugins/disk-cleanup/README.md+++ b/plugins/disk-cleanup/README.md@@ -47,8 +47,12 @@ Deletion rules (same as the original PR):- `$HERMES_HOME/logs/`, `memories/`, `sessions/`, `skills/`, `plugins/`,and config files are never tracked- User project trees (`workspace/`, `projects/`, `plans/`, `home/`, `patches/`,- `skins/`, `themes/`, `contributors/`, `profiles/`, `backups/`) are never- tracked or swept, even for files named `test_*`/`tmp_*`+ `skins/`, `themes/`, `contributors/`, `profiles/`, `backups/`) and `kanban/`+ (task attachments/workspaces) are never tracked or swept, even for files+ named `test_*`/`tmp_*`+- A tracked *directory* under a protected top level (e.g. `cache/`, which holds+ terminal snapshots) is never removed; only its files age out. Stale entries+ are logged as `SKIPPED` and dropped- Backup/restore is scoped to `tracked.json` — the plugin never touchesagent logs- Atomic writes: `.tmp` → backup → renamediff --git a/plugins/disk-cleanup/disk_cleanup.py b/plugins/disk-cleanup/disk_cleanup.pyindex 6ce42192823..96aa93df069 100755--- a/plugins/disk-cleanup/disk_cleanup.py+++ b/plugins/disk-cleanup/disk_cleanup.py@@ -87,7 +87,9 @@ _EMPTY_DIR_PROTECTED_TOP_LEVEL = frozenset({"hermes-agent", "backups", "profiles", ".worktrees","patches", "projects", "skins", "themes", "contributors",# Per-profile user trees bootstrapped by ``profiles.py::_PROFILE_DIRS`` (#112859).- "workspace", "plans", "home"})+ "workspace", "plans", "home",+ # Kanban owns its own lifecycle (workspaces GC'd at terminal state, attachments live with the task).+ "kanban"})_EMPTY_DIR_SWEEP_PRUNE_DIRS = frozenset({".git", "node_modules", "venv", ".venv", "site-packages", "__pycache__"})@@ -103,7 +105,21 @@ _NEVER_TRACK_TOP_LEVEL = frozenset({# named test_* or tmp_* (#75403, also #32164, #37721). ``workspace``, ``plans`` and ``home`` are the# per-profile user trees bootstrapped by ``profiles.py::_PROFILE_DIRS`` (#112859)."patches", "projects", "skins", "themes", "contributors",- "profiles", "backups", "optional-skills", "workspace", "plans", "home"})+ "profiles", "backups", "optional-skills", "workspace", "plans", "home",+ # Kanban task attachments/workspaces have their own lifecycle; test_* staging files there are+ # not disposable (#114552).+ "kanban"})+++def _is_protected_dir(p: Path) -> bool:+ """A tracked DIRECTORY that is HERMES_HOME itself or lives under a protected top-level tree+ (``cache/terminal`` holds terminal snapshots) is never rmtree'd; only its files age out."""+ if not p.is_dir():+ return False+ with contextlib.suppress(ValueError, OSError):+ rel = p.resolve().relative_to(get_hermes_home())+ return not rel.parts or rel.parts[0] in _EMPTY_DIR_PROTECTED_TOP_LEVEL+ return False@functools.lru_cache(maxsize=8) # keyed by home: a multiplexed process serves several profilesdef _protected_cron_paths(home: Path) -> frozenset:@@ -215,8 +231,8 @@ def dry_run() -> Tuple[List[Dict], List[Dict]]:auto, prompt = [], []for item, p, age in _live_items(load_tracked(), datetime.now(timezone.utc)):cat = item["category"]- # Stale cron-output entries are skipped by quick(); omit them here too.- if cat == "cron-output" and guess_category(p) != "cron-output":+ # Stale cron-output entries and protected dirs are skipped by quick(); omit them here too.+ if (cat == "cron-output" and guess_category(p) != "cron-output") or _is_protected_dir(p):continueif _is_auto_delete(cat, age):auto.append(item)@@ -240,6 +256,9 @@ def quick() -> Dict[str, Any]:if _is_protected_cron_path(p):_log(f"SKIP protected cron path: {p}")continue+ if _is_protected_dir(p):+ _log(f"SKIPPED: {p} (protected top-level dir)")+ continueif not _is_auto_delete(cat, age):new_tracked.append(item)continue@@ -324,7 +343,7 @@ def guess_category(path: Path) -> Optional[str]:with contextlib.suppress(ValueError): # not under HERMES_HOME (/tmp/hermes-*) — name rules onlyrel = path.resolve().relative_to(get_hermes_home())top = rel.parts[0] if rel.parts else ""- if top in _NEVER_TRACK_TOP_LEVEL:+ if top in _NEVER_TRACK_TOP_LEVEL or _is_protected_dir(path):return Noneif top in ("cron", "cronjobs"):# Only the disposable ``output/`` subtree; control-plane state (jobs.json,diff --git a/tests/plugins/test_disk_cleanup_plugin.py b/tests/plugins/test_disk_cleanup_plugin.pyindex f46da30815c..c84067894d5 100644--- a/tests/plugins/test_disk_cleanup_plugin.py+++ b/tests/plugins/test_disk_cleanup_plugin.py@@ -15,6 +15,7 @@ Covers the bundled plugin at ``plugins/disk-cleanup/``:import importlibimport jsonimport sys+from datetime import datetime, timedelta, timezonefrom pathlib import Pathimport pytest@@ -187,6 +188,57 @@ class TestProfileUserTreesNeverCleaned:assert not sweepable.exists(), "unprotected empty dirs are still swept"+class TestProtectedDirsNeverRmtreed:+ """A tracked DIRECTORY under a protected top level (``cache/`` holds terminal snapshots)+ must never be rmtree'd by the tracked-item path, only by-file aging; ``kanban/`` is never+ tracked at all (its attachments/workspaces have their own lifecycle)."""++ def test_stale_cache_dir_entry_is_skipped_but_its_old_files_still_age_out(self, _isolate_env):+ dg = _load_lib()+ cache = _isolate_env / "cache"+ (cache / "terminal").mkdir(parents=True)+ old_file = cache / "scratch.txt"+ old_file.write_text("x")+ assert dg.guess_category(cache) is None, "the cache dir itself is never tracked"+ assert dg.guess_category(old_file) == "temp", "files under cache/ still age out as temp"+ old_ts = (datetime.now(timezone.utc) - timedelta(days=8)).isoformat()+ dg.save_tracked([+ {"path": str(cache), "category": "temp", "timestamp": old_ts, "size": 0},+ {"path": str(old_file), "category": "temp", "timestamp": old_ts, "size": 1},+ ])++ summary = dg.quick()++ assert (cache / "terminal").is_dir(), "protected top-level dir must survive a stale tracked entry"+ assert not old_file.exists(), "old temp FILE under cache/ is still pruned (control)"+ assert summary["deleted"] == 1+ assert dg.load_tracked() == [], "the stale dir entry is dropped, not retried every session"+ assert "SKIPPED" in (_isolate_env / "disk-cleanup" / "cleanup.log").read_text()++ def test_kanban_test_files_are_never_tracked_or_deleted(self, _isolate_env):+ pi = _load_plugin_init()+ dg = _load_lib()+ att = _isolate_env / "kanban" / "attachments" / "t1" / "test_evidence.sh"+ att.parent.mkdir(parents=True)+ att.write_text("x")+ assert dg.guess_category(att) is None+ # A stale pre-fix entry must be dropped by re-validation instead of deleted.+ dg.save_tracked([{"path": str(att), "category": "test",+ "timestamp": datetime.now(timezone.utc).isoformat(), "size": 1}])+ pi._on_post_tool_call(tool_name="write_file", args={"path": str(att), "content": "x"},+ result="OK", task_id="t1", session_id="s_kb")+ scratch = _isolate_env / "test_scratch.py"+ scratch.write_text("x")+ pi._on_post_tool_call(tool_name="write_file", args={"path": str(scratch), "content": "x"},+ result="OK", task_id="t1", session_id="s_kb")++ pi._on_session_end(session_id="s_kb", completed=True, interrupted=False)++ assert att.exists(), "kanban attachments are task-managed, never auto-deleted"+ assert not scratch.exists(), "root-level scratch files are still cleaned up (control)"+ assert dg.load_tracked() == []++class TestStaleCronEntryMigration:"""Regression tests for #37721 — stale cron-output entries in tracked.json."""diff --git a/website/docs/user-guide/features/built-in-plugins.md b/website/docs/user-guide/features/built-in-plugins.mdindex 25372ac93af..5203ff9e7af 100644--- a/website/docs/user-guide/features/built-in-plugins.md+++ b/website/docs/user-guide/features/built-in-plugins.md@@ -111,7 +111,7 @@ Auto-tracks and removes ephemeral files created during sessions — test scripts| `tracked.json.bak` | Atomic-write backup of the above || `cleanup.log` | Append-only audit trail of every track / skip / reject / delete |-**Safety** — cleanup only ever touches paths under `HERMES_HOME` or `/tmp/hermes-*`. Windows mounts (`/mnt/c/...`) are rejected. Well-known top-level state dirs (`logs/`, `memories/`, `sessions/`, `cron/`, `cache/`, `skills/`, `plugins/`, `disk-cleanup/` itself) are never removed even when empty — a fresh install does not get gutted on first session end. User project trees (`workspace/`, `projects/`, `plans/`, `home/`) are never tracked or swept at all: a `test_*.py` or `tmp_*` file inside your project is source code, not scratch.+**Safety** — cleanup only ever touches paths under `HERMES_HOME` or `/tmp/hermes-*`. Windows mounts (`/mnt/c/...`) are rejected. Well-known top-level state dirs (`logs/`, `memories/`, `sessions/`, `cron/`, `cache/`, `skills/`, `plugins/`, `disk-cleanup/` itself) are never removed even when empty — a fresh install does not get gutted on first session end. User project trees (`workspace/`, `projects/`, `plans/`, `home/`) are never tracked or swept at all: a `test_*.py` or `tmp_*` file inside your project is source code, not scratch. `kanban/` (task attachments and workspaces) is never tracked either, and a tracked *directory* under a protected top level such as `cache/` is never removed — only the files inside it age out.**Enabling:** `hermes plugins enable disk-cleanup` (or check the box in `hermes plugins`).