Skip to content

The agent that grows with you

fix(scratch): prune on 24h idle, judged by the whole subtree, not 72h top-level age

teknium11217c17f0df4
diff --git a/hermes_cli/doctor_state.py b/hermes_cli/doctor_state.py
index 3df67c6f7f5..f56548e861c 100644
--- a/hermes_cli/doctor_state.py
+++ b/hermes_cli/doctor_state.py
@@ -168,10 +168,10 @@ def _check_directory_structure(should_fix: bool, f: Finding) -> None:
def _check_scratch_dir(hermes_home: Path, _DHH: str) -> None:
"""Report the scratch dir (TMPDIR target) and its size; a user-set TMPDIR elsewhere is shown, not judged."""
from hermes_constants import (
- SCRATCH_DIR_MARKER_ENV, SCRATCH_MAX_AGE_HOURS, get_scratch_dir, scratch_dir_usage_bytes)
+ SCRATCH_DIR_MARKER_ENV, SCRATCH_MAX_IDLE_HOURS, get_scratch_dir, scratch_dir_usage_bytes)
scratch = get_scratch_dir(hermes_home, prune=False)
size = _human_bytes(scratch_dir_usage_bytes(scratch))
- check_ok(f"{_DHH}/cache/scratch/ is the scratch dir (TMPDIR; {size}, pruned after {SCRATCH_MAX_AGE_HOURS}h)")
+ check_ok(f"{_DHH}/cache/scratch/ is the scratch dir (TMPDIR; {size}, entries pruned after {SCRATCH_MAX_IDLE_HOURS}h idle)")
tmpdir = os.environ.get("TMPDIR", "")
if tmpdir and tmpdir != os.environ.get(SCRATCH_DIR_MARKER_ENV, ""):
check_info(f"TMPDIR={tmpdir} is set by you or the OS, so Hermes leaves it alone")
diff --git a/hermes_constants.py b/hermes_constants.py
index 9184c261368..9f19d7b4219 100644
--- a/hermes_constants.py
+++ b/hermes_constants.py
@@ -1000,10 +1000,15 @@ def apply_subprocess_home_env(env: MutableMapping[str, str]) -> None:
# --- Scratch dir: Hermes' own temp space, never the system /tmp ---
# System temp is tmpfs on most Linux distros and containers, so browser profiles, PTY probes,
# download spools and every ``tempfile.mkdtemp()`` a Hermes-launched script performs eat RAM
-# and vanish on reboot. ``HERMES_HOME/cache/scratch`` is real storage with a fixed retention.
+# and vanish on reboot. ``HERMES_HOME/cache/scratch`` is real storage with an IDLE retention:
+# an entry lives while anything inside it is still being written and goes 24h after the last
+# write anywhere in its subtree. A fixed age was wrong both ways — a directory's own mtime only
+# moves when a direct child is added or removed, so a lane writing deep inside a tree looked
+# untouched and lost its worktree at the deadline, while finished trees (a 7 GB clone with its
+# own venv per campaign lane) sat for three days and filled the disk.
SCRATCH_TMP_ENV_VARS = ("TMPDIR", "TMP", "TEMP")
SCRATCH_DIR_MARKER_ENV = "HERMES_SCRATCH_DIR"
-SCRATCH_MAX_AGE_HOURS = 72
+SCRATCH_MAX_IDLE_HOURS = 24
_SCRATCH_PRUNE_STAMP = ".last_prune"
_SCRATCH_PRUNE_INTERVAL_SECONDS = 3600
_scratch_pruned_once = False
@@ -1146,7 +1151,7 @@ def get_scratch_dir(home: str | Path | None = None, *, prune: bool = True) -> Pa
Every Hermes process and child gets ``TMPDIR``/``TMP``/``TEMP`` pointed here at boot (see
:func:`export_scratch_tmp_env`), so ``tempfile`` defaults land here without call sites
- knowing. Entries older than ``SCRATCH_MAX_AGE_HOURS`` are pruned at most once per process
+ knowing. Entries idle for ``SCRATCH_MAX_IDLE_HOURS`` are pruned at most once per process
and once per hour across processes (stamp file), so a fan-out of children stays cheap.
Permissions follow :func:`apply_secure_dir_policy`, so an explicit ``HERMES_HOME_MODE`` or
@@ -1165,11 +1170,43 @@ def get_scratch_dir(home: str | Path | None = None, *, prune: bool = True) -> Pa
return scratch
-def prune_scratch_dir(scratch: Path | None = None, max_age_hours: float = SCRATCH_MAX_AGE_HOURS) -> int:
- """Delete top-level scratch entries untouched for *max_age_hours*; return the count removed."""
+def _subtree_touched_since(path: Path, cutoff: float) -> bool:
+ """True when *path* or anything beneath it has an mtime at or after *cutoff*.
+
+ Stops at the first recent entry, so a live tree costs one hit and only a truly idle
+ tree pays for the full walk (once, right before it is deleted). Symlinks are never
+ followed: a link into the repo would make the target's activity keep the entry alive.
+ """
+ try:
+ if os.lstat(path).st_mtime >= cutoff:
+ return True
+ except OSError:
+ return False
+ if not path.is_dir() or path.is_symlink():
+ return False
+ stack = [str(path)]
+ while stack:
+ try:
+ with os.scandir(stack.pop()) as it:
+ for child in it:
+ try:
+ if child.stat(follow_symlinks=False).st_mtime >= cutoff:
+ return True
+ except OSError:
+ continue
+ if child.is_dir(follow_symlinks=False):
+ stack.append(child.path)
+ except OSError:
+ continue
+ return False
+
+
+def prune_scratch_dir(scratch: Path | None = None, max_idle_hours: float = SCRATCH_MAX_IDLE_HOURS) -> int:
+ """Delete top-level scratch entries with no write anywhere in their subtree for
+ *max_idle_hours*; return the count removed."""
import time
root = scratch if scratch is not None else get_scratch_dir(prune=False)
- cutoff = time.time() - max_age_hours * 3600
+ cutoff = time.time() - max_idle_hours * 3600
removed = 0
try:
entries = list(root.iterdir())
@@ -1179,7 +1216,7 @@ def prune_scratch_dir(scratch: Path | None = None, max_age_hours: float = SCRATC
if entry.name == _SCRATCH_PRUNE_STAMP:
continue
try:
- if entry.lstat().st_mtime >= cutoff:
+ if _subtree_touched_since(entry, cutoff):
continue
if entry.is_dir() and not entry.is_symlink():
shutil.rmtree(entry, ignore_errors=True)
diff --git a/tests/test_scratch_dir.py b/tests/test_scratch_dir.py
index 4d527d0eda4..4f41e2d8361 100644
--- a/tests/test_scratch_dir.py
+++ b/tests/test_scratch_dir.py
@@ -46,16 +46,23 @@ def test_bootstrap_import_exports_scratch_to_process_and_children(tmp_path):
assert out.stdout.split() == [expected, expected]
-def test_prune_removes_only_stale_top_level_entries(tmp_path):
+def test_prune_removes_idle_entries_and_keeps_trees_written_deep_inside(tmp_path):
+ """Idle retention: an entry goes when nothing in its subtree was written within the window;
+ a tree whose only recent write is three levels down is still in use and stays, even though
+ its top-level mtime is ancient (a directory's mtime ignores writes below its children)."""
scratch = get_scratch_dir(tmp_path, prune=False)
- stale, fresh = scratch / "stale", scratch / "fresh.txt"
- stale.mkdir()
- (stale / "f").write_text("x", encoding="utf-8")
+ idle, live, fresh = scratch / "idle", scratch / "live", scratch / "fresh.txt"
+ deep = live / "lane" / "wt"
+ deep.mkdir(parents=True)
+ idle.mkdir()
+ (idle / "f").write_text("x", encoding="utf-8")
+ (deep / "log").write_text("x", encoding="utf-8")
fresh.write_text("y", encoding="utf-8")
- ancient = time.time() - 100 * 3600
- os.utime(stale, (ancient, ancient))
+ ancient = time.time() - 30 * 3600
+ for path in (idle, idle / "f", live, live / "lane", deep):
+ os.utime(path, (ancient, ancient))
assert prune_scratch_dir(scratch) == 1
- assert not stale.exists() and fresh.exists()
+ assert not idle.exists() and live.exists() and fresh.exists()
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX directory modes")
diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md
index 96e507eead4..2e76fd58f43 100644
--- a/website/docs/user-guide/configuration.md
+++ b/website/docs/user-guide/configuration.md
@@ -249,9 +249,10 @@ backend, cron) and every child it launches gets `TMPDIR`, `TMP` and `TEMP` point
`mktemp`, browser profiles and probe scripts all land on real storage instead of a
RAM-backed system temp dir. The system prompt names this directory as the scratch
directory. Hermes only sets these when they are not already set — a `TMPDIR` exported
-by you or by the OS (macOS `/var/folders`, Windows `%TEMP%`) is left alone. Entries
-older than 72 hours are pruned at startup (at most once per hour). `hermes doctor`
-reports the directory and its size.
+by you or by the OS (macOS `/var/folders`, Windows `%TEMP%`) is left alone. Entries are
+pruned at startup (at most once per hour) once they have been **idle for 24 hours**: an entry
+stays as long as anything anywhere inside it was written in the last day, and goes a day after
+the last write. `hermes doctor` reports the directory and its size.
`desktop.font_family` sets the font for chat and the rest of the Hermes Desktop interface (the terminal pane has its own key above). Give it one installed family name (for example, `OpenDyslexic` or `Atkinson Hyperlegible`) or a CSS font stack; Hermes keeps the active theme's own stack behind it so CJK and emoji glyphs still resolve, and an empty value uses the theme's font. Edit it in **Settings → Appearance → Chat Font**.