The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(disk-cleanup): track only files a tool call created, never pre-existing ones
Froraut17d55a20327e
diff --git a/plugins/disk-cleanup/README.md b/plugins/disk-cleanup/README.mdindex bf4c88f2693..2ea05e1128c 100644--- a/plugins/disk-cleanup/README.md+++ b/plugins/disk-cleanup/README.md@@ -14,7 +14,8 @@ never needs to remember to call a tool.| Hook | Behaviour ||---|---|-| `post_tool_call` | When `write_file` / `terminal` / `patch` creates a file matching `test_*`, `tmp_*`, or `*.test.*` inside `HERMES_HOME`, track it silently as `test` / `temp` / `cron-output`. |+| `pre_tool_call` | Snapshot which paths named in the call's arguments already exist. |+| `post_tool_call` | When `write_file` / `terminal` / `patch` creates a file matching `test_*`, `tmp_*`, or `*.test.*` inside `HERMES_HOME` — a path named in the call that did not exist before it — track it silently as `test` / `temp` / `cron-output`. Existing files the call edits, runs or lists are never tracked. || `on_session_end` | If any test files were auto-tracked during this turn, run `quick` cleanup (no prompts). |Deletion rules (same as the original PR):diff --git a/plugins/disk-cleanup/__init__.py b/plugins/disk-cleanup/__init__.pyindex 414f48651c4..4602391404e 100644--- a/plugins/disk-cleanup/__init__.py+++ b/plugins/disk-cleanup/__init__.py@@ -1,6 +1,6 @@"""disk-cleanup plugin — auto-cleanup of ephemeral Hermes session files.-``post_tool_call`` silently tracks test/temp paths created by write_file/patch/terminal;+``pre_tool_call`` + ``post_tool_call`` silently track test/temp paths CREATED by write_file/patch/terminal;``on_session_end`` runs :func:`disk_cleanup.quick` when any test file was tracked this turn;``/disk-cleanup`` exposes status / dry-run / quick / deep / track / forget."""@@ -12,6 +12,7 @@ import osimport reimport shleximport threading+import timefrom pathlib import Pathfrom typing import Any, Callable, Dict, List, Optional, Set@@ -26,21 +27,14 @@ _recent_test_tracks: Dict[str, Set[str]] = {}_lock = threading.Lock()-# Tool-call result shapes we can parse-_WRITE_FILE_PATH_KEY = "path"-_TERMINAL_PATH_REGEX = re.compile(- r"(?:^|\s)(/[^\s'\"`]+|~/[^\s'\"`]+|[A-Za-z]:[\\/][^\s'\"`]+)"-)---def _extract_path_arg(args: Dict[str, Any], result: str) -> Set[str]:- """write_file/patch: the single ``path`` arg (re-tracking existing files is a no-op)."""+def _extract_path_arg(args: Dict[str, Any]) -> Set[str]:+ """write_file/patch: the single ``path`` arg."""path = args.get("path")return {path} if isinstance(path, str) and path else set()-def _extract_paths_from_terminal(args: Dict[str, Any], result: str) -> Set[str]:- """Candidate paths from a terminal command + output; guess_category/is_safe_path filter later."""+def _extract_paths_from_terminal(args: Dict[str, Any]) -> Set[str]:+ """Candidate paths named in a terminal command; guess_category/is_safe_path filter later."""paths: Set[str] = set()cmd = args.get("command") or ""if isinstance(cmd, str) and cmd:@@ -57,30 +51,62 @@ def _extract_paths_from_terminal(args: Dict[str, Any], result: str) -> Set[str]:paths.add(tok)except ValueError:pass- # Only scan the result text if it's a reasonable size (avoid 50KB dumps).- if isinstance(result, str) and len(result) < 4096:- paths.update(_TERMINAL_PATH_REGEX.findall(result))return paths-_PATH_EXTRACTORS: Dict[str, Callable[[Dict[str, Any], str], Set[str]]] = {+_PATH_EXTRACTORS: Dict[str, Callable[[Dict[str, Any]], Set[str]]] = {"write_file": _extract_path_arg,"patch": _extract_path_arg,"terminal": _extract_paths_from_terminal}+# tool_call_id -> (snapshot time, the call's argument paths that already existed, or None if unknown).+# Tracking is for what a call CREATED: 'test' items are deleted at age 0 when the turn ends (rmtree+# for dirs), so a user's test_* script the agent patched, ran or merely listed must never be queued.+_pre_call: Dict[str, tuple] = {}+_PRE_CALL_TTL_S = 3600.0 # a call whose post hook never fires (blocked) must not leak its entry+++def _on_pre_tool_call(tool_name: str = "", args: Optional[Dict[str, Any]] = None,+ tool_call_id: str = "", **_: Any) -> None:+ """Snapshot which argument paths exist before the call. Never raises: pre_tool_call hooks+ fail CLOSED (a raise would block the tool), so an error just records "unknown"."""+ extractor = _PATH_EXTRACTORS.get(tool_name)+ if not tool_call_id or extractor is None or not isinstance(args, dict):+ return None+ now = time.time()+ try:+ existing: Optional[Set[str]] = {+ str(Path(p).expanduser()) for p in extractor(args) if Path(p).expanduser().exists()}+ except Exception:+ existing = None+ with _lock:+ for key in [k for k, (taken, _e) in _pre_call.items() if now - taken > _PRE_CALL_TTL_S]:+ del _pre_call[key]+ _pre_call[tool_call_id] = (now, existing)+ return None++def _on_post_tool_call(tool_name: str = "", args: Optional[Dict[str, Any]] = None, result: Any = None,task_id: str = "", session_id: str = "", tool_call_id: str = "", **_: Any) -> None:- """Auto-track ephemeral files created by recent tool calls. Best-effort, never raises."""+ """Auto-track ephemeral files THIS call created: a path from the call's own arguments that was+ absent in the pre-call snapshot and exists now. Paths seen only in terminal OUTPUT (a `find` or+ `ls` listing) carry no such proof and are never tracked; no snapshot means no proof either.+ Best-effort, never raises."""extractor = _PATH_EXTRACTORS.get(tool_name)if not isinstance(args, dict) or extractor is None:return- for path_str in extractor(args, result if isinstance(result, str) else ""):+ with _lock:+ _taken, existing = _pre_call.pop(tool_call_id, (0.0, None)) if tool_call_id else (0.0, None)+ if existing is None:+ return+ for path_str in extractor(args):try:p = Path(path_str).expanduser()+ created = str(p) not in existing and p.exists()except Exception:continue- category = dg.guess_category(p) if p.exists() else None+ category = dg.guess_category(p) if created else Noneif category is not None and dg.track(str(p), category, silent=True) and category == "test":with _lock:_recent_test_tracks.setdefault(task_id or session_id or "default", set()).add(str(p))@@ -196,6 +222,7 @@ def _handle_slash(raw_args: str) -> Optional[str]:def register(ctx) -> None:+ ctx.register_hook("pre_tool_call", _on_pre_tool_call)ctx.register_hook("post_tool_call", _on_post_tool_call)ctx.register_hook("on_session_end", _on_session_end)ctx.register_command("disk-cleanup", handler=_handle_slash,diff --git a/tests/plugins/test_disk_cleanup_plugin.py b/tests/plugins/test_disk_cleanup_plugin.pyindex 9a4ad34f9b4..3d361a87446 100644--- a/tests/plugins/test_disk_cleanup_plugin.py+++ b/tests/plugins/test_disk_cleanup_plugin.py@@ -47,6 +47,18 @@ def _load_lib():return mod+_CALL_IDS = iter(range(1, 10**6))+++def _run_tool(pi, tool_name, args, create=None, result="OK", **ids):+ """The real hook order: pre_tool_call snapshot, the call's side effect, post_tool_call."""+ call_id = f"call-{next(_CALL_IDS)}"+ pi._on_pre_tool_call(tool_name=tool_name, args=args, tool_call_id=call_id)+ if create is not None:+ create()+ pi._on_post_tool_call(tool_name=tool_name, args=args, result=result, tool_call_id=call_id, **ids)++def _load_plugin_init():"""Import the plugin's __init__.py (which depends on the library)."""repo_root = Path(__file__).resolve().parents[2]@@ -157,18 +169,12 @@ class TestProfileUserTreesNeverCleaned:dg = _load_lib()keep = _isolate_env / "workspace" / "proj" / "tests" / "test_parse.py"keep.parent.mkdir(parents=True)- keep.write_text("x")scratch = _isolate_env / "tmp_scratch.py"- scratch.write_text("x")+ for p in (keep, scratch):+ _run_tool(pi, "write_file", {"path": str(p), "content": "x"},+ create=lambda p=p: p.write_text("x"), task_id="t_ws", session_id="s_ws")assert dg.guess_category(keep) is Noneassert dg.guess_category(scratch) == "test"- for p in (keep, scratch):- pi._on_post_tool_call(- tool_name="write_file",- args={"path": str(p), "content": "x"},- result="OK",- task_id="t_ws", session_id="s_ws",- )pi._on_session_end(session_id="s_ws", completed=True, interrupted=False)assert keep.exists(), "session-end cleanup must not touch workspace project files"assert not scratch.exists(), "root-level scratch files are still cleaned up"@@ -225,12 +231,11 @@ class TestProtectedDirsNeverRmtreed:# 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")+ _run_tool(pi, "write_file", {"path": str(att), "content": "x"},+ create=lambda: att.write_text("y"), 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")+ _run_tool(pi, "write_file", {"path": str(scratch), "content": "x"},+ create=lambda: scratch.write_text("x"), task_id="t1", session_id="s_kb")pi._on_session_end(session_id="s_kb", completed=True, interrupted=False)@@ -482,13 +487,8 @@ class TestPostToolCallHook:def test_write_file_test_pattern_tracked(self, _isolate_env):pi = _load_plugin_init()p = _isolate_env / "test_created.py"- p.write_text("x")- pi._on_post_tool_call(- tool_name="write_file",- args={"path": str(p), "content": "x"},- result="OK",- task_id="t1", session_id="s1",- )+ _run_tool(pi, "write_file", {"path": str(p), "content": "x"},+ create=lambda: p.write_text("x"), task_id="t1", session_id="s1")tracked_file = _isolate_env / "disk-cleanup" / "tracked.json"data = json.loads(tracked_file.read_text())assert len(data) == 1@@ -498,13 +498,8 @@ class TestPostToolCallHook:def test_terminal_command_picks_up_paths(self, _isolate_env):pi = _load_plugin_init()p = _isolate_env / "tmp_created.log"- p.write_text("x")- pi._on_post_tool_call(- tool_name="terminal",- args={"command": f"touch {p}"},- result=f"created {p}\n",- task_id="t3", session_id="s3",- )+ _run_tool(pi, "terminal", {"command": f"touch {p}"}, create=lambda: p.write_text("x"),+ result=f"created {p}\n", task_id="t3", session_id="s3")tracked_file = _isolate_env / "disk-cleanup" / "tracked.json"data = json.loads(tracked_file.read_text())assert any(Path(i["path"]) == p.resolve() for i in data)@@ -522,17 +517,38 @@ class TestPostToolCallHook:assert not tracked_file.exists() or tracked_file.read_text().strip() == "[]"+ def test_paths_the_call_did_not_create_are_never_tracked(self, _isolate_env):+ """'test' items are deleted at age 0 when the turn ends (rmtree for dirs), so only what a+ call CREATED may be tracked. A user's cron script the agent patched, and a hook dir it+ merely listed (by argument or in `find` output), must survive the turn."""+ import os+ pi = _load_plugin_init()+ script = _isolate_env / "scripts" / "test_uptime.py"+ script.parent.mkdir()+ script.write_text("print('up')\n")+ hook_dir = _isolate_env / "hooks" / "test_notify"+ hook_dir.mkdir(parents=True)+ old = 1_700_000_000+ os.utime(script, (old, old))+ os.utime(hook_dir, (old, old))++ _run_tool(pi, "patch", {"path": str(script), "old_string": "up", "new_string": "ok"},+ create=lambda: script.write_text("print('ok')\n"), session_id="s_keep")+ _run_tool(pi, "terminal", {"command": f"ls -la {hook_dir}"}, result="total 0\n",+ session_id="s_keep")+ _run_tool(pi, "terminal", {"command": f"find {_isolate_env} -name 'test_*'"},+ result=f"{script}\n{hook_dir}\n", session_id="s_keep")+ pi._on_session_end(session_id="s_keep", completed=True, interrupted=False)++ assert script.exists() and hook_dir.is_dir()++class TestOnSessionEndHook:def test_runs_quick_when_test_files_tracked(self, _isolate_env):pi = _load_plugin_init()p = _isolate_env / "test_cleanup.py"- p.write_text("x")- pi._on_post_tool_call(- tool_name="write_file",- args={"path": str(p), "content": "x"},- result="OK",- task_id="", session_id="s1",- )+ _run_tool(pi, "write_file", {"path": str(p), "content": "x"},+ create=lambda: p.write_text("x"), task_id="", session_id="s1")assert p.exists()pi._on_session_end(session_id="s1", completed=True, interrupted=False)assert not p.exists(), "test file should be auto-deleted"