Skip to content

The agent that grows with you

fix(terminal): confirm terminal-cache removal with an explicit lstat, not lexists — match the scratch half (review on #139850)

Teknium389bd5a2b0b9
diff --git a/tests/tools/test_local_temp_dir.py b/tests/tools/test_local_temp_dir.py
index f2db760bc74..d54d57d958b 100644
--- a/tests/tools/test_local_temp_dir.py
+++ b/tests/tools/test_local_temp_dir.py
@@ -165,5 +165,34 @@ def test_cleanup_terminal_temp_cache_revalidates_before_each_delete(tmp_path, mo
assert removed == len(set(fired) - {"hermes_bg_resumed.log"}) # never the stuck dir
+def test_cleanup_terminal_temp_cache_uninspectable_residue_is_not_counted(tmp_path, monkeypatch):
+ """An entry that survives its delete and cannot be lstat'd is not proven gone."""
+ import pathlib
+ import time
+
+ from tools.environments import local as local_mod
+
+ root = tmp_path / "cache" / "terminal"
+ root.mkdir(parents=True)
+ monkeypatch.setattr(local_mod, "_default_terminal_temp_dir", lambda: root)
+ old = time.time() - 100 * 3600
+ residue = root / "residue.txt"
+ residue.write_text("x")
+ os.utime(residue, (old, old))
+
+ tried = []
+ monkeypatch.setattr(pathlib.Path, "unlink", lambda self, *a, **k: tried.append(self))
+ real_lstat = os.lstat
+
+ def lstat(path, *args, **kwargs):
+ if tried and os.fspath(path) == os.fspath(residue):
+ raise PermissionError(13, "denied", os.fspath(path))
+ return real_lstat(path, *args, **kwargs)
+
+ monkeypatch.setattr(local_mod.os, "lstat", lstat)
+ assert local_mod.cleanup_terminal_temp_cache(max_age_hours=24) == 0
+ assert tried == [residue] and residue.exists()
+
+
if __name__ == "__main__":
sys.exit(pytest.main([__file__, "-q"]))
diff --git a/tools/environments/local.py b/tools/environments/local.py
index bcdff2daf36..9ac93d9b8e6 100644
--- a/tools/environments/local.py
+++ b/tools/environments/local.py
@@ -108,9 +108,14 @@ def cleanup_terminal_temp_cache(max_age_hours: float = TERMINAL_TEMP_MAX_IDLE_HO
shutil.rmtree(f, ignore_errors=True) if f.is_dir() else f.unlink()
except OSError:
continue
- # rmtree ignores errors: only a path that is really gone counts as removed.
- if not os.path.lexists(f):
+ # rmtree ignores errors: only a path that is really gone counts as removed, and only
+ # an explicit lstat proves absence (lexists() swallows OSError from lstat).
+ try:
+ os.lstat(f)
+ except FileNotFoundError:
removed += 1
+ except OSError:
+ pass
return removed