diff --git a/agent/prompt_builder.py b/agent/prompt_builder.py index 6c0b6edc57..8ddbeb8903 100644 --- a/agent/prompt_builder.py +++ b/agent/prompt_builder.py @@ -999,7 +999,7 @@ def _local_host_hints() -> list[str]: # naming Hermes' scratch dir here is what makes the TMPDIR export a habit rather than a hidden default. try: host_lines.append(f"Scratch directory: {get_scratch_dir()} (TMPDIR points here; write temporary files " - "and probes there, never under the system temp dir; entries are pruned after 72h)") + "and probes there, never under the system temp dir; entries idle for 24h are pruned)") except OSError: pass if not (sys.platform == "win32" and not is_wsl()): diff --git a/hermes_cli/doctor_state.py b/hermes_cli/doctor_state.py index f56548e861..df3c8f4931 100644 --- a/hermes_cli/doctor_state.py +++ b/hermes_cli/doctor_state.py @@ -165,6 +165,31 @@ def _check_directory_structure(should_fix: bool, f: Finding) -> None: check_info(f"{fname} not created yet (will be created when the agent first writes a memory)") +# Cache-root entries at least this big that no pruner covers get a doctor warning. +_UNPRUNED_CACHE_WARN_BYTES = 1 << 30 +_PRUNED_CACHE_DIRS = frozenset({"scratch", "terminal"}) + + +def unpruned_cache_hogs(hermes_home: Path, min_bytes: int = _UNPRUNED_CACHE_WARN_BYTES) -> list[tuple[str, int]]: + """``(name, bytes)`` for ``cache/`` entries outside the pruned dirs that exceed *min_bytes*. + + Finished campaign trees parked at the cache root sat for weeks (95 GB on one host) + because only ``scratch/`` and ``terminal/`` are reaped; doctor is where that shows.""" + from hermes_constants import scratch_dir_usage_bytes + + cache = hermes_home / "cache" + hogs: list[tuple[str, int]] = [] + try: + entries = [e for e in cache.iterdir() if e.is_dir() and not e.is_symlink() and e.name not in _PRUNED_CACHE_DIRS] + except OSError: + return hogs + for entry in entries: + size = scratch_dir_usage_bytes(entry) + if size >= min_bytes: + hogs.append((entry.name, size)) + return sorted(hogs, key=lambda item: -item[1]) + + 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 ( @@ -172,6 +197,12 @@ def _check_scratch_dir(hermes_home: Path, _DHH: str) -> None: 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}, entries pruned after {SCRATCH_MAX_IDLE_HOURS}h idle)") + for name, nbytes in unpruned_cache_hogs(hermes_home): + check_warn( + f"{_DHH}/cache/{name}/ is {_human_bytes(nbytes)} and outside every pruner " + f"(only cache/scratch/ and cache/terminal/ are reaped) — move task files under " + f"cache/scratch// or delete it" + ) 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 9f19d7b421..6aaacef5ea 100644 --- a/hermes_constants.py +++ b/hermes_constants.py @@ -1170,62 +1170,14 @@ def get_scratch_dir(home: str | Path | None = None, *, prune: bool = True) -> Pa return scratch -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 + *max_idle_hours*, reaping processes and git worktree registrations rooted in them + first (``hermes_constants_scratch``); return the count removed.""" + from hermes_constants_scratch import prune_idle_entries + root = scratch if scratch is not None else get_scratch_dir(prune=False) - cutoff = time.time() - max_idle_hours * 3600 - removed = 0 - try: - entries = list(root.iterdir()) - except OSError: - return 0 - for entry in entries: - if entry.name == _SCRATCH_PRUNE_STAMP: - continue - try: - if _subtree_touched_since(entry, cutoff): - continue - if entry.is_dir() and not entry.is_symlink(): - shutil.rmtree(entry, ignore_errors=True) - else: - entry.unlink() - removed += 1 - except OSError: - continue - return removed + return prune_idle_entries(root, max_idle_hours, frozenset({_SCRATCH_PRUNE_STAMP})) def _prune_scratch_dir_once(scratch: Path) -> None: diff --git a/hermes_constants_scratch.py b/hermes_constants_scratch.py new file mode 100644 index 0000000000..46d6e03c8f --- /dev/null +++ b/hermes_constants_scratch.py @@ -0,0 +1,197 @@ +"""Scratch-dir retention: idle detection plus the reaping an idle tree needs before it goes. + +Deleting an idle ``cache/scratch/`` is not enough on its own: a lane's e2e run leaves +headless browsers whose cwd was inside the tree (they survived for days with a ``(deleted)`` +cwd), and a repo whose linked worktree lived in the tree keeps a dangling registration until +someone runs ``git worktree prune``. Both are reaped here, right before ``rmtree``. +""" +from __future__ import annotations + +import logging +import os +import shutil +import subprocess +import time +from pathlib import Path + +logger = logging.getLogger(__name__) + +# How long a TERMed process gets before KILL; browsers exit well within this. +_REAP_GRACE_SECONDS = 3.0 +# ``.git`` files (linked worktrees) are looked for this deep; lanes nest repo/tree/subtree. +_GIT_FILE_MAX_DEPTH = 4 + + +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 _under(path: str, root: str) -> bool: + return path == root or path.startswith(root.rstrip(os.sep) + os.sep) + + +def _own_lineage() -> set[int]: + """This process and its ancestors: never reap the shell that is running the prune.""" + import psutil + + pids: set[int] = set() + try: + proc = psutil.Process() + while proc is not None and proc.pid not in pids: + pids.add(proc.pid) + proc = proc.parent() + except (psutil.Error, OSError): + pass + return pids + + +def reap_processes_rooted_in(scratch_root: Path, doomed: list[Path]) -> int: + """TERM (then KILL) same-user processes whose cwd is inside an entry about to be + pruned, or is a path under *scratch_root* that no longer exists. Returns the count. + + Only the cwd is consulted: a process merely holding a file open inside scratch (an + editor, a log tail) is not ours to kill, but one *living* in a directory we are + about to delete, or in one already gone, has nothing left to run for. + """ + import psutil + + root = os.path.realpath(str(scratch_root)) + targets = [os.path.realpath(str(p)) for p in doomed] + skip = _own_lineage() + uid = os.getuid() if hasattr(os, "getuid") else None + victims: list[psutil.Process] = [] + for proc in psutil.process_iter(["pid"]): + if proc.pid in skip: + continue + try: + if uid is not None and proc.uids().real != uid: + continue + cwd = proc.cwd() + except (psutil.Error, OSError): + continue + if not cwd: + continue + deleted = cwd.endswith(" (deleted)") + cwd_path = cwd[: -len(" (deleted)")] if deleted else cwd + if not _under(cwd_path, root): + continue + if deleted or not os.path.exists(cwd_path) or any(_under(cwd_path, t) for t in targets): + victims.append(proc) + if not victims: + return 0 + for proc in victims: + try: + proc.terminate() + except (psutil.Error, OSError): + continue + _, alive = psutil.wait_procs(victims, timeout=_REAP_GRACE_SECONDS) + for proc in alive: + try: + proc.kill() + except (psutil.Error, OSError): + continue + logger.info("scratch prune: reaped %d process(es) rooted in pruned entries", len(victims)) + return len(victims) + + +def _linked_worktree_repos(entry: Path) -> set[str]: + """Repos whose linked worktrees live inside *entry* (``.git`` FILES, ``gitdir: /.git/worktrees/``).""" + repos: set[str] = set() + stack = [(str(entry), 0)] + while stack: + current, depth = stack.pop() + try: + with os.scandir(current) as it: + for child in it: + if child.name == ".git" and child.is_file(follow_symlinks=False): + try: + line = Path(child.path).read_text(encoding="utf-8", errors="replace").strip() + except OSError: + continue + if line.startswith("gitdir:"): + gitdir = Path(line[len("gitdir:"):].strip()) + # /.git/worktrees/ -> + if gitdir.parent.name == "worktrees" and gitdir.parent.parent.name == ".git": + repos.add(str(gitdir.parent.parent.parent)) + elif child.is_dir(follow_symlinks=False) and depth < _GIT_FILE_MAX_DEPTH \ + and child.name not in ("node_modules", ".venv", "venv"): + stack.append((child.path, depth + 1)) + except OSError: + continue + return repos + + +def release_git_worktrees(repos: set[str]) -> None: + """``git worktree prune`` in each repo: drops registrations whose tree we just deleted.""" + for repo in sorted(repos): + if not os.path.isdir(repo): + continue + try: + subprocess.run( + ["git", "-C", repo, "worktree", "prune"], + stdin=subprocess.DEVNULL, capture_output=True, text=True, encoding="utf-8", errors="replace", + timeout=15, check=False, + ) + except (OSError, subprocess.SubprocessError) as exc: + logger.debug("git worktree prune in %s failed: %s", repo, exc) + + +def prune_idle_entries(root: Path, max_idle_hours: float, skip_names: frozenset[str]) -> int: + """Delete top-level entries of *root* with no write anywhere in their subtree for + *max_idle_hours*, reaping processes and worktree registrations rooted in them first. + Returns the count removed.""" + cutoff = time.time() - max_idle_hours * 3600 + try: + entries = [e for e in root.iterdir() if e.name not in skip_names] + except OSError: + return 0 + doomed = [e for e in entries if not subtree_touched_since(e, cutoff)] + # Runs even with nothing to delete: orphans whose cwd was removed by an earlier pass + # (or by hand) are found by the deleted-cwd rule, not by membership in ``doomed``. + try: + reap_processes_rooted_in(root, doomed) + except Exception as exc: # psutil missing or restricted host: the deletion still proceeds + logger.debug("scratch prune: process reap skipped: %s", exc) + if not doomed: + return 0 + repos: set[str] = set() + removed = 0 + for entry in doomed: + try: + if entry.is_dir() and not entry.is_symlink(): + repos |= _linked_worktree_repos(entry) + shutil.rmtree(entry, ignore_errors=True) + else: + entry.unlink() + removed += 1 + except OSError: + continue + release_git_worktrees(repos) + return removed diff --git a/tests/hermes_cli/test_doctor_cache_hogs.py b/tests/hermes_cli/test_doctor_cache_hogs.py new file mode 100644 index 0000000000..4555e1ea43 --- /dev/null +++ b/tests/hermes_cli/test_doctor_cache_hogs.py @@ -0,0 +1,16 @@ +"""``hermes doctor`` names cache-root dirs that no pruner covers once they are big enough.""" + +from hermes_cli.doctor_state import unpruned_cache_hogs + + +def test_unpruned_cache_hogs_skips_pruned_dirs_and_small_entries(tmp_path): + cache = tmp_path / "cache" + for name in ("scratch", "terminal", "campaign-x", "web"): + (cache / name).mkdir(parents=True) + with open(cache / name / "blob", "wb") as fh: + fh.truncate(2048) + fh.write(b"x" * 2048) + hogs = unpruned_cache_hogs(tmp_path, min_bytes=1024) + assert {name for name, _ in hogs} == {"campaign-x", "web"} + assert not unpruned_cache_hogs(tmp_path, min_bytes=1 << 20) + assert all(size >= 2048 for _, size in hogs) diff --git a/tests/test_scratch_dir.py b/tests/test_scratch_dir.py index 4f41e2d836..99dcad8dc5 100644 --- a/tests/test_scratch_dir.py +++ b/tests/test_scratch_dir.py @@ -40,7 +40,7 @@ def test_bootstrap_import_exports_scratch_to_process_and_children(tmp_path): "print(tempfile.gettempdir()); " "print(subprocess.run([sys.executable, '-c', 'import tempfile;print(tempfile.gettempdir())']," " capture_output=True, text=True).stdout.strip())") - out = subprocess.run([sys.executable, "-c", code], env=env, capture_output=True, text=True, + out = subprocess.run([sys.executable, "-c", code], env=env, capture_output=True, text=True, encoding="utf-8", cwd=os.path.dirname(os.path.dirname(os.path.abspath(__file__))), check=True) expected = str(tmp_path / "cache" / "scratch") assert out.stdout.split() == [expected, expected] @@ -193,3 +193,64 @@ def test_config_and_constants_share_one_policy_implementation(tmp_path, monkeypa os.chmod(f, 0o640) config._secure_file(f) assert stat.S_IMODE(os.stat(f).st_mode) == 0o640 + + +def test_prune_reaps_process_living_in_idle_entry_and_spares_live_tree(tmp_path): + """A process whose cwd is inside an idle entry is gone by the time the entry is + (a lane's headless browsers survived for days with a deleted cwd); one living in a + tree that is still being written is not touched.""" + import subprocess + + scratch = get_scratch_dir(tmp_path, prune=False) + idle, live = scratch / "idle-lane" / "wt", scratch / "live-lane" / "wt" + idle.mkdir(parents=True) + live.mkdir(parents=True) + ancient = time.time() - 30 * 3600 + for path in (idle.parent, idle, live.parent, live): + os.utime(path, (ancient, ancient)) + (live / "log").write_text("still writing", encoding="utf-8") + sleeper = [sys.executable, "-c", "import time; time.sleep(60)"] + doomed = subprocess.Popen(sleeper, cwd=str(idle), stdin=subprocess.DEVNULL) + spared = subprocess.Popen(sleeper, cwd=str(live), stdin=subprocess.DEVNULL) + try: + assert prune_scratch_dir(scratch) == 1 + assert doomed.wait(timeout=10) is not None + assert spared.poll() is None + assert not idle.parent.exists() and live.exists() + finally: + for proc in (doomed, spared): + if proc.poll() is None: + proc.kill() + proc.wait(timeout=10) + + +def test_prune_releases_git_worktree_registration_of_idle_entry(tmp_path): + """Deleting a scratch entry that held a linked worktree leaves the repo with no + dangling registration (10 sat in one repo's ``git worktree list`` after cleanup).""" + import subprocess + + def git(*args, cwd): + subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, + stdin=subprocess.DEVNULL, env={**os.environ, "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@x", + "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "t@x"}) + + repo = tmp_path / "repo" + repo.mkdir() + git("init", "-q", cwd=repo) + (repo / "f").write_text("x", encoding="utf-8") + git("add", "f", cwd=repo) + git("commit", "-q", "-m", "init", cwd=repo) + scratch = get_scratch_dir(tmp_path, prune=False) + tree = scratch / "lane" / "abwt" + tree.parent.mkdir() + git("worktree", "add", "-q", "--detach", str(tree), cwd=repo) + ancient = time.time() - 30 * 3600 + for dirpath, dirnames, filenames in os.walk(tree.parent): + for name in dirnames + filenames: + os.utime(os.path.join(dirpath, name), (ancient, ancient), follow_symlinks=False) + os.utime(tree.parent, (ancient, ancient)) + assert prune_scratch_dir(scratch) == 1 + listing = subprocess.run(["git", "worktree", "list", "--porcelain"], cwd=repo, capture_output=True, + text=True, stdin=subprocess.DEVNULL, check=True).stdout + assert str(tree) not in listing and not tree.exists() diff --git a/tests/tools/test_local_temp_dir.py b/tests/tools/test_local_temp_dir.py index c0e79a1d20..e9e839fe20 100644 --- a/tests/tools/test_local_temp_dir.py +++ b/tests/tools/test_local_temp_dir.py @@ -114,7 +114,7 @@ def test_cleanup_terminal_temp_cache(tmp_path, monkeypatch): f.write_text("x") os.utime(f, (old, old)) - removed = local_mod.cleanup_terminal_temp_cache(max_age_hours=72) + removed = local_mod.cleanup_terminal_temp_cache(max_idle_hours=24) assert removed == 4 # stale snap + 3 dead-group files assert keep.exists() assert live_pid.exists() and live_log.exists() diff --git a/tools/environments/local.py b/tools/environments/local.py index 3cdeb36f28..5c9f4202bf 100644 --- a/tools/environments/local.py +++ b/tools/environments/local.py @@ -38,8 +38,9 @@ logger = logging.getLogger(__name__) # --- Terminal temp-cache pruning --- # get_temp_dir() defaults to HERMES_HOME/cache/terminal (real storage, not tmpfs), so # stale artifacts don't vanish on reboot: the gateway housekeeping loop prunes hourly -# and a once-per-process sweep covers CLI-only installs. -TERMINAL_TEMP_MAX_AGE_HOURS = 72 +# and a once-per-process sweep covers CLI-only installs. Retention is idle-based like +# the scratch dir: an entry goes 24h after the last write anywhere inside it. +TERMINAL_TEMP_MAX_IDLE_HOURS = 24 _terminal_temp_prune_lock = threading.Lock() _terminal_temp_pruned_once = False # Background artifacts come in triplets (hermes_bg_.log/.pid/.exit). A live @@ -57,13 +58,16 @@ def _default_terminal_temp_dir() -> "Path | None": return None -def cleanup_terminal_temp_cache(max_age_hours: int = TERMINAL_TEMP_MAX_AGE_HOURS) -> int: - """Delete session temp artifacts older than *max_age_hours*; return count. +def cleanup_terminal_temp_cache(max_idle_hours: float = TERMINAL_TEMP_MAX_IDLE_HOURS) -> int: + """Delete session temp artifacts idle for *max_idle_hours* (no write anywhere in a + directory's subtree); return count. Only the managed default dir is pruned — never a user-pointed ``terminal.temp_dir``.""" + from hermes_constants_scratch import subtree_touched_since + root = _default_terminal_temp_dir() if root is None: return 0 - cutoff = time.time() - (max_age_hours * 3600) + cutoff = time.time() - (max_idle_hours * 3600) try: entries = list(root.iterdir()) except OSError: @@ -82,7 +86,10 @@ def cleanup_terminal_temp_cache(max_age_hours: int = TERMINAL_TEMP_MAX_AGE_HOURS removed = 0 for f, mt in mtimes.items(): m = _BG_GROUP_RE.match(f.name) - if (group_newest[m.group(1)] if m else mt) >= cutoff: + if m: + if group_newest[m.group(1)] >= cutoff: + continue + elif subtree_touched_since(f, cutoff): continue try: shutil.rmtree(f, ignore_errors=True) if f.is_dir() else f.unlink() diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md index 2e76fd58f4..baef49f522 100644 --- a/website/docs/user-guide/configuration.md +++ b/website/docs/user-guide/configuration.md @@ -238,9 +238,9 @@ honors an explicit `TMPDIR`/`TMP`/`TEMP` from the environment and otherwise uses a managed directory on real storage at `~/.hermes/cache/terminal` instead of `/tmp` — on many distros (Arch-based setups in particular) `/tmp` is a small RAM-backed tmpfs that Hermes session artifacts can fill under -load. The managed directory is auto-pruned: artifacts older than 72 hours are -swept hourly by gateway housekeeping and once per process on CLI-only -installs. Set `temp_dir` to an existing absolute path to redirect session +load. The managed directory is auto-pruned: artifacts idle for 24 hours (no write +anywhere inside them) are swept hourly by gateway housekeeping and once per process +on CLI-only installs. Set `temp_dir` to an existing absolute path to redirect session temp anywhere else; user-set paths are never auto-pruned. Independently of `terminal.temp_dir`, every Hermes process (CLI, TUI, gateway, Desktop @@ -252,7 +252,11 @@ directory. Hermes only sets these when they are not already set — a `TMPDIR` e 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. +the last write. Before an idle entry is deleted, Hermes also stops any process still running +with its working directory inside that entry (or inside a scratch path that no longer exists, +such as a headless browser left behind by a test run) and drops any `git worktree` +registration that pointed into it. `hermes doctor` reports the directory and its size, and +warns about directories over 1 GB elsewhere under `cache/` that no pruner covers. `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**.