The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(disk-cleanup): the ls-files cache must not outlive the git index
David Crandall9d6609a14bc0
diff --git a/plugins/disk-cleanup/disk_cleanup.py b/plugins/disk-cleanup/disk_cleanup.pyindex ad999914d2c..84b1570dc53 100755--- a/plugins/disk-cleanup/disk_cleanup.py+++ b/plugins/disk-cleanup/disk_cleanup.py@@ -12,6 +12,7 @@ import contextlibimport functoolsimport jsonimport logging+import osimport shutilfrom datetime import datetime, timezonefrom pathlib import Path@@ -340,15 +341,74 @@ _TEST_PATTERNS = ("test_", "tmp_")_TEST_SUFFIXES = (".test.py", ".test.js", ".test.ts", ".test.md")[email protected]_cache(maxsize=1)[email protected]_cache(maxsize=8) # keyed by home: a multiplexed process serves several profiles+def _git_index_path(home: str) -> Optional[str]:+ """Absolute path of *home*'s git index, or ``None`` when *home* is not a git worktree.++ ``rev-parse --git-path index`` is the portable answer: a plain checkout reports+ ``.git/index``, a linked worktree (``.git`` is a pointer FILE) the per-worktree index+ under the main repo's ``.git/worktrees/<name>/``, and an explicit ``GIT_INDEX_FILE``+ wins. Cached per home: callers only ever need the *stat* of the result, never this+ subprocess.+ """+ import subprocess++ try:+ r = subprocess.run(+ ["git", "-C", home, "rev-parse", "--git-path", "index"],+ capture_output=True, text=True, timeout=20,+ )+ except (OSError, subprocess.SubprocessError):+ return None+ if r.returncode != 0:+ return None+ out = r.stdout.strip()+ if not out:+ return None+ p = Path(out)+ return str(p if p.is_absolute() else Path(home) / p)+++def _git_index_signature(home: str) -> Optional[Tuple[int, int, int]]:+ """``(st_mtime_ns, st_size, st_ino)`` of *home*'s git index — a cheap, subprocess-free+ fingerprint that changes whenever something is staged, committed or unstaged.++ ``None`` when there is no index to stat (not a repo, or nothing added yet). Never+ raises: a guard that cannot read the index must fall back to the pre-existing+ behaviour, never break the agent loop.+ """+ idx = _git_index_path(home)+ if idx is None:+ return None+ try:+ st = os.stat(idx)+ except OSError:+ return None+ return (st.st_mtime_ns, st.st_size, st.st_ino)++def _git_tracked_index(home: str) -> frozenset:- """The set of repo-relative paths ``git ls-files`` reports for *home*, cached per process.+ """The set of repo-relative paths ``git ls-files`` reports for *home*.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.++ The result is cached on the git index's stat signature as well as *home*, so it cannot+ outlive the index it was read from. A long-lived process (the gateway) that cached the+ set while a scratch ``test_*`` file was still untracked must not keep reporting it as+ untracked after that file is staged or committed — otherwise ``quick()`` re-validates+ the stored ``test`` entry through ``guess_category()``, sees the stale set, and unlinks+ a file git now owns (#122232). A new index is a new key, so no explicit invalidation+ hook is needed anywhere.+Returns an empty set when git is unavailable or the call fails — the caller then treatsnothing as tracked, i.e. the pre-existing behaviour."""+ return _ls_files_cached(home, _git_index_signature(home))++[email protected]_cache(maxsize=8) # keyed by (home, index signature) — bounded, so index churn cannot grow it+def _ls_files_cached(home: str, _index_signature: Optional[Tuple[int, int, int]]) -> frozenset:import subprocesstry:diff --git a/tests/plugins/test_disk_cleanup_plugin.py b/tests/plugins/test_disk_cleanup_plugin.pyindex 7eddd66a5dc..29668675377 100644--- a/tests/plugins/test_disk_cleanup_plugin.py+++ b/tests/plugins/test_disk_cleanup_plugin.py@@ -329,6 +329,57 @@ class TestGitWorktreeFilesNeverCleaned:assert not scratch.exists()assert result["deleted"] == 1+ def test_file_staged_after_first_classification_is_never_deleted(self, _isolate_env):+ """The cached ``git ls-files`` set must not outlive the index it was read from.++ Reviewer's repro on the guard added by this PR: ``guess_category()`` runs on+ every post-tool-call, so a long-lived process (the gateway) caches the ls-files+ set while ``test_scratch.py`` is still untracked. The same process then stages+ and commits that file (e.g. an auto-snapshot) and a later ``quick()``+ re-validates the stored "test" entry through ``guess_category()`` — the stale+ cache still reports the file as untracked, so ``_delete_item()`` unlinks a file+ git now owns (``git status`` shows ``D test_scratch.py``).++ No ``cache_clear()`` anywhere in this test: the guard has to notice the index+ change on its own, exactly as it must inside the live gateway process.+ """+ 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")+ control = _isolate_env / "tmp_control.log"+ control.write_text("x")++ # 1. First classification happens while the file is still untracked — this is+ # what fills the per-process index cache.+ assert dg._inside_git_worktree(scratch) is False+ assert dg.guess_category(scratch) == "test"+ assert dg.guess_category(control) == "test"+ dg.save_tracked([{"path": str(scratch), "category": "test",+ "timestamp": datetime.now(timezone.utc).isoformat(), "size": 1},+ {"path": str(control), "category": "test",+ "timestamp": datetime.now(timezone.utc).isoformat(), "size": 1}])++ # 2. Git takes ownership of the file without the plugin being told.+ subprocess.run(["git", "-C", str(_isolate_env), "add", "test_scratch.py"], check=True)+ subprocess.run(["git", "-C", str(_isolate_env),+ "-c", "[email protected]", "-c", "user.name=Test",+ "commit", "-q", "-m", "own it"], check=True)++ # The guard must read the new index, not the one it cached in step 1.+ assert dg._inside_git_worktree(scratch) is True+ assert dg.guess_category(scratch) is None++ # 3. quick() re-validates: the file git now owns survives, and the never-tracked+ # control in the same repo is still cleaned (not a blanket stop on cleanup).+ result = dg.quick()+ assert scratch.exists(), "a file git now owns must never be auto-deleted"+ assert not control.exists(), "untracked scratch beside it is still disposable"+ assert result["deleted"] == 1+ assert dg.load_tracked() == [], "both entries are resolved, neither is kept"+class TestStaleCronEntryMigration:"""Regression tests for #37721 — stale cron-output entries in tracked.json."""