The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(disk-cleanup): a git-tracked file is never disposable, even when HERMES_HOME is the checkout
David Crandall0e799da22370
diff --git a/plugins/disk-cleanup/disk_cleanup.py b/plugins/disk-cleanup/disk_cleanup.pyindex 0a4c25ae1bb..ad999914d2c 100755--- a/plugins/disk-cleanup/disk_cleanup.py+++ b/plugins/disk-cleanup/disk_cleanup.py@@ -340,18 +340,68 @@ _TEST_PATTERNS = ("test_", "tmp_")_TEST_SUFFIXES = (".test.py", ".test.js", ".test.ts", ".test.md")[email protected]_cache(maxsize=1)+def _git_tracked_index(home: str) -> frozenset:+ """The set of repo-relative paths ``git ls-files`` reports for *home*, cached per process.++ One subprocess for the whole home instead of one per candidate file: ``guess_category``+ runs on every post-tool-call, and this install's userfiles repo tracks thousands of paths.+ Returns an empty set when git is unavailable or the call fails — the caller then treats+ nothing as tracked, i.e. the pre-existing behaviour.+ """+ import subprocess++ try:+ r = subprocess.run(+ ["git", "-C", home, "ls-files", "-z"],+ capture_output=True, text=True, timeout=20,+ )+ except (OSError, subprocess.SubprocessError):+ return frozenset()+ if r.returncode != 0:+ return frozenset()+ return frozenset(p for p in r.stdout.split("\0") if p)+++def _git_tracks(home: Path, rel: str) -> bool:+ """True when ``git`` tracks *rel* (repo-relative, ``/``-separated) inside *home*."""+ try:+ return rel.replace("\\", "/") in _git_tracked_index(str(home))+ except Exception: # pragma: no cover — never let a cleanup guard break the agent loop+ return False++def _inside_git_worktree(path: Path) -> bool:- """True if *path* sits inside a Git worktree/checkout: a ``.git`` entry (a directory in a- normal checkout, a pointer FILE in a linked worktree) exists anywhere on the directory chain.- Files there are Git-owned — a ``test_*`` file in a worktree is typically a committed- regression test, not session scratch (#115295).-- Only ``.git`` entries strictly BELOW ``HERMES_HOME`` count for in-home paths: a home kept- in a dotfiles repo (``~/.git``) would otherwise make every scratch file look Git-owned."""- parents = list(path.resolve().parents)+ """True if *path* is Git-owned: a ``.git`` entry (a directory in a normal checkout, a+ pointer FILE in a linked worktree) exists on the directory chain, or — when+ ``HERMES_HOME`` is itself a checkout — git actually TRACKS the file.++ Files whose repo tracks them are Git-owned — a ``test_*`` file in a worktree is typically+ a committed regression test, not session scratch (#115295).++ Only ``.git`` entries strictly BELOW ``HERMES_HOME`` count for the parent-chain probe: a+ home kept in a dotfiles repo (``~/.git``) would otherwise make every scratch file look+ Git-owned.++ The parent-chain probe alone misses the case where ``HERMES_HOME`` IS a git checkout (this+ install: ``~/.hermes`` is the userfiles repo). There every in-home file sits inside a+ worktree, yet only the TRACKED ones are Git-owned — a scratch file merely living beside+ them is not, and treating the whole home as protected would disable cleanup entirely. Ask+ git about the individual path instead.+ """+ home = get_hermes_home()+ resolved = path.resolve()+ parents = list(resolved.parents)+ below = parentswith contextlib.suppress(ValueError):- parents = parents[: parents.index(get_hermes_home())]- return any((parent / ".git").exists() for parent in parents)+ below = parents[: parents.index(home)]+ if any((parent / ".git").exists() for parent in below):+ return True+ if not (home / ".git").exists():+ return False+ with contextlib.suppress(ValueError):+ return _git_tracks(home, str(resolved.relative_to(home)))+ return Falsedef guess_category(path: Path) -> Optional[str]:diff --git a/tests/plugins/test_disk_cleanup_plugin.py b/tests/plugins/test_disk_cleanup_plugin.pyindex a4128c64557..7eddd66a5dc 100644--- a/tests/plugins/test_disk_cleanup_plugin.py+++ b/tests/plugins/test_disk_cleanup_plugin.py@@ -277,6 +277,58 @@ class TestGitWorktreeFilesNeverCleaned:assert not scratch.exists()assert result["deleted"] == 1+ def test_tracked_file_in_hermes_home_checkout_is_never_disposable(self, _isolate_env):+ """HERMES_HOME itself is a git checkout: a file git TRACKS is Git-owned, so a+ ``test_*``/``tmp_*`` name must not classify it as disposable.++ Observed live: ``~/.hermes`` is the userfiles repo, so ``~/.hermes/scripts/`` sits+ inside a worktree but is not *below* HERMES_HOME — the parent-chain probe found no+ ``.git`` and the bundled disk-cleanup plugin deleted two committed regression tests+ (``scripts/test_analyze_upstream_opportunities.py``,+ ``scripts/test_customization_protocol_v2.py``), committing the deletion."""+ import subprocess++ dg = _load_lib()+ subprocess.run(["git", "init", "-q", str(_isolate_env)], check=True)+ (dg.get_hermes_home() / "scripts").mkdir()+ tracked = _isolate_env / "scripts" / "test_committed.py"+ tracked.write_text("x")+ scratch = _isolate_env / "test_untracked.py"+ scratch.write_text("x")+ subprocess.run(["git", "-C", str(_isolate_env), "add", "scripts/test_committed.py"],+ check=True)++ assert dg._inside_git_worktree(tracked) is True+ assert dg._inside_git_worktree(scratch) is False+ assert dg.guess_category(tracked) is None+ assert dg.guess_category(scratch) == "test"++ # A stale pre-fix entry is dropped by quick()'s re-validation, not deleted.+ dg.save_tracked([{"path": str(tracked), "category": "test",+ "timestamp": datetime.now(timezone.utc).isoformat(), "size": 1}])+ result = dg.quick()+ assert tracked.exists(), "a git-tracked test file must never be auto-deleted"+ assert result["deleted"] == 0++ def test_untracked_scratch_beside_tracked_files_is_still_cleaned(self, _isolate_env):+ """Control for the checkout case: the guard protects what git TRACKS, not the whole+ home. An untracked ``test_*`` scratch file in the same repo is still disposable, so+ the fix must not disable cleanup for every file under a git-backed HERMES_HOME."""+ import subprocess++ dg = _load_lib()+ subprocess.run(["git", "init", "-q", str(_isolate_env)], check=True)+ scratch = _isolate_env / "test_scratch.py"+ scratch.write_text("x")++ assert dg._inside_git_worktree(scratch) is False+ assert dg.guess_category(scratch) == "test"+ dg.save_tracked([{"path": str(scratch), "category": "test",+ "timestamp": datetime.now(timezone.utc).isoformat(), "size": 1}])+ result = dg.quick()+ assert not scratch.exists()+ assert result["deleted"] == 1+class TestStaleCronEntryMigration:"""Regression tests for #37721 — stale cron-output entries in tracked.json."""