The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(scratch): record every pruned entry and reaped process in logs/scratch-prune.log
unsupportedpastels67784d8a89c5
diff --git a/hermes_constants.py b/hermes_constants.pyindex bbdf2e9ea49..ced1e33e8bd 100644--- a/hermes_constants.py+++ b/hermes_constants.py@@ -918,11 +918,13 @@ def get_scratch_dir(home: str | Path | None = None, *, prune: bool = True) -> Padef 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*, reaping processes and git worktree registrations rooted in them- first (``hermes_constants_scratch``); return the count removed."""+ first (``hermes_constants_scratch``); return the count removed. Each removal and kill is+ recorded in ``<home>/logs/scratch-prune.log`` (*scratch* is ``<home>/cache/scratch``)."""from hermes_constants_scratch import prune_idle_entriesroot = scratch if scratch is not None else get_scratch_dir(prune=False)- return prune_idle_entries(root, max_idle_hours, frozenset({_SCRATCH_PRUNE_STAMP}))+ log_file = root.parent.parent / "logs" / "scratch-prune.log"+ return prune_idle_entries(root, max_idle_hours, frozenset({_SCRATCH_PRUNE_STAMP}), log_file)def _prune_scratch_dir_once(scratch: Path) -> None:diff --git a/hermes_constants_scratch.py b/hermes_constants_scratch.pyindex 68c54805dc9..b39bbfae0bd 100644--- a/hermes_constants_scratch.py+++ b/hermes_constants_scratch.py@@ -12,6 +12,7 @@ import osimport shutilimport subprocessimport time+from logging.handlers import RotatingFileHandlerfrom pathlib import Pathlogger = logging.getLogger(__name__)@@ -20,6 +21,58 @@ logger = logging.getLogger(__name__)_REAP_GRACE_SECONDS = 3.0# ``.git`` files (linked worktrees) are looked for this deep; lanes nest repo/tree/subtree._GIT_FILE_MAX_DEPTH = 4+# logs/scratch-prune.log: one line per entry deleted and per process signalled (#132401). Same+# fixed rotation as tool_calls.log.+_PRUNE_LOG_MAX_BYTES = 5 * 1024 * 1024+_PRUNE_LOG_BACKUPS = 3+++def _open_prune_log(log_file: Path | None) -> logging.Logger:+ """Logger for one prune's records, with its own RotatingFileHandler on *log_file*, so a+ prune that runs at boot (before ``setup_logging()``) still leaves them on disk. Records also+ propagate through this module's logger to whatever logging is set up.++ One unregistered logger per prune, closed when it ends: no process holds the file open+ between prunes (an open handle blocks rollover on Windows), and prunes of two homes never+ share a handler. Without a *log_file* (test-runner temp roots) this module's logger is used.+ """+ if log_file is None:+ return logger+ try:+ log_file.parent.mkdir(parents=True, exist_ok=True)+ except OSError as exc:+ logger.warning("scratch prune: cannot create %s: %s", log_file.parent, exc)+ return logger+ audit = logging.Logger(logger.name, logging.INFO)+ audit.parent = logger+ handler = RotatingFileHandler(+ log_file, maxBytes=_PRUNE_LOG_MAX_BYTES, backupCount=_PRUNE_LOG_BACKUPS, encoding="utf-8", delay=True,+ )+ handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))+ audit.addHandler(handler)+ return audit+++def _tree_bytes(path: Path) -> int:+ """Apparent size of *path* and everything under it, symlinks not followed."""+ try:+ total = os.lstat(path).st_size+ except OSError:+ return 0+ stack = [str(path)] if path.is_dir() and not path.is_symlink() else []+ while stack:+ try:+ with os.scandir(stack.pop()) as it:+ for child in it:+ try:+ total += child.stat(follow_symlinks=False).st_size+ except OSError:+ continue+ if child.is_dir(follow_symlinks=False):+ stack.append(child.path)+ except OSError:+ continue+ return totaldef subtree_touched_since(path: Path, cutoff: float) -> bool:@@ -73,7 +126,7 @@ def _own_lineage() -> set[int]:return pids-def reap_processes_rooted_in(scratch_root: Path, doomed: list[Path]) -> int:+def reap_processes_rooted_in(scratch_root: Path, doomed: list[Path], audit: logging.Logger = logger) -> int:"""TERM (then KILL) same-user processes whose cwd is inside an entry about to bepruned, or is a path under *scratch_root* that no longer exists. Returns the count.@@ -87,7 +140,7 @@ def reap_processes_rooted_in(scratch_root: Path, doomed: list[Path]) -> int: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] = []+ victims: list[tuple[psutil.Process, str]] = []for proc in psutil.process_iter(["pid"]):if proc.pid in skip:continue@@ -104,20 +157,26 @@ def reap_processes_rooted_in(scratch_root: Path, doomed: list[Path]) -> int:if not _under(cwd_path, root):continueif deleted or not os.path.exists(cwd_path) or any(_under(cwd_path, t) for t in targets):- victims.append(proc)+ victims.append((proc, cwd_path))if not victims:return 0- for proc in victims:+ for proc, cwd_path in victims:try:+ name = proc.name()proc.terminate()except (psutil.Error, OSError):continue- _, alive = psutil.wait_procs(victims, timeout=_REAP_GRACE_SECONDS)+ audit.info("scratch prune: sent TERM pid=%d name=%s cwd=%s", proc.pid, name, cwd_path)+ _, alive = psutil.wait_procs([proc for proc, _ in victims], timeout=_REAP_GRACE_SECONDS)for proc in alive:try:+ # A zombie already exited; only its parent has not collected it yet.+ if proc.status() == psutil.STATUS_ZOMBIE:+ continueproc.kill()except (psutil.Error, OSError):continue+ audit.info("scratch prune: sent KILL pid=%d (still running after TERM)", proc.pid)logger.info("scratch prune: reaped %d process(es) rooted in pruned entries", len(victims))return len(victims)@@ -164,10 +223,25 @@ def release_git_worktrees(repos: set[str]) -> None: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:+def prune_idle_entries(+ root: Path, max_idle_hours: float, skip_names: frozenset[str], log_file: Path | None = None,+) -> 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."""+ Each removal and each signalled process is recorded in *log_file*. Returns the count+ actually removed."""+ audit = _open_prune_log(log_file)+ try:+ return _prune_idle_entries(root, max_idle_hours, skip_names, audit)+ finally:+ if audit is not logger:+ for handler in audit.handlers:+ handler.close()+++def _prune_idle_entries(+ root: Path, max_idle_hours: float, skip_names: frozenset[str], audit: logging.Logger,+) -> int:cutoff = time.time() - max_idle_hours * 3600try:entries = [e for e in root.iterdir() if e.name not in skip_names]@@ -177,22 +251,29 @@ def prune_idle_entries(root: Path, max_idle_hours: float, skip_names: frozenset[# 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)+ reap_processes_rooted_in(root, doomed, audit)except Exception as exc: # psutil missing or restricted host: the deletion still proceeds- logger.debug("scratch prune: process reap skipped: %s", exc)+ logger.debug("scratch prune: process reap skipped: %s", exc, exc_info=True)if not doomed:return 0repos: set[str] = set()removed = 0for entry in doomed:+ size = _tree_bytes(entry)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:+ except OSError as exc:+ audit.info("scratch prune: could not remove %s: %s", entry, exc)+ continue+ # rmtree ignores errors, so only a path that is really gone counts as removed.+ if os.path.lexists(entry):+ audit.info("scratch prune: could not fully remove %s", entry)continue+ audit.info("scratch prune: removed %s (%d bytes)", entry, size)+ removed += 1release_git_worktrees(repos)return removeddiff --git a/tests/test_scratch_dir.py b/tests/test_scratch_dir.pyindex 284a23fb1c8..6c1e5e71ee4 100644--- a/tests/test_scratch_dir.py+++ b/tests/test_scratch_dir.py@@ -1,10 +1,12 @@"""Scratch dir contract: TMPDIR/TMP/TEMP follow HERMES_HOME/cache/scratch unless the user set them."""import os+import shutilimport statimport subprocessimport sysimport time+from pathlib import Pathfrom unittest.mock import patchimport pytest@@ -254,6 +256,43 @@ def test_prune_reaps_process_living_in_idle_entry_and_spares_live_tree(tmp_path)proc.wait(timeout=10)+def test_prune_records_removals_and_kills_in_scratch_prune_log(tmp_path: Path) -> None:+ """Every removed entry and every signalled process leaves a line in+ ``<home>/logs/scratch-prune.log``: the prune's own handler writes it, so the boot-time+ prune (before ``setup_logging()``) is not silent. An entry rmtree could not delete is+ neither counted nor recorded as removed (#132401)."""+ import subprocess++ scratch = get_scratch_dir(tmp_path, prune=False)+ gone, stuck = scratch / "idle-lane", scratch / "stuck-lane"+ ancient = time.time() - 30 * 3600+ for entry in (gone, stuck):+ entry.mkdir()+ (entry / "out.md").write_text("deliverable", encoding="utf-8")+ for path in (entry / "out.md", entry):+ os.utime(path, (ancient, ancient))+ worker = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"], cwd=str(gone),+ stdin=subprocess.DEVNULL)+ real_rmtree = shutil.rmtree++ def rmtree(path: str | os.PathLike[str], *args: object, **kwargs: object) -> None:+ if os.path.realpath(path) != os.path.realpath(stuck):+ real_rmtree(path, *args, **kwargs)++ try:+ with patch("hermes_constants_scratch.shutil.rmtree", rmtree):+ assert prune_scratch_dir(scratch) == 1+ assert worker.wait(timeout=10) is not None+ finally:+ if worker.poll() is None:+ worker.kill()+ worker.wait(timeout=10)+ log = (tmp_path / "logs" / "scratch-prune.log").read_text(encoding="utf-8-sig")+ assert f"removed {gone} (" in log+ assert f"sent TERM pid={worker.pid} " in log+ assert f"could not fully remove {stuck}" in log and f"removed {stuck}" not in log++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 nodangling registration (10 sat in one repo's ``git worktree list`` after cleanup)."""