The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(scratch): keep an idle entry a live Hermes-owned process works in; reap only orphans (#132401)
Teknium7cc1353633e2
diff --git a/hermes_constants_scratch.py b/hermes_constants_scratch.pyindex be599c0c5c0..e8b465021e7 100644--- a/hermes_constants_scratch.py+++ b/hermes_constants_scratch.py@@ -4,10 +4,15 @@ Deleting an idle ``cache/scratch/<entry>`` is not enough on its own: a lane's e2headless 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 untilsomeone runs ``git worktree prune``. Both are reaped here, right before ``rmtree``.++A process Hermes itself started is never an orphan, though: an idle entry a registered live+process still works inside is kept, not reaped (#132401). Ownership comes from the two+registries Hermes writes, not from a marker file a lane must remember to drop."""from __future__ import annotationsimport contextlib+import jsonimport loggingimport osimport shutil@@ -158,6 +163,57 @@ def _own_lineage() -> set[int]:return pids+def _registered_live_pids(home: Path) -> set[int]:+ """Live pids Hermes registered for *home*: the machine spawn ledger (every long-lived entry+ point and MCP helper, ``hermes_cli.process_identity``) and the background-process checkpoint+ (``tools.process_registry``, ``processes.json``). A recorded start time that no longer+ matches is a reused pid, not ownership."""+ import psutil++ from hermes_constants import get_default_hermes_root++ root = get_default_hermes_root(home=home)+ sources = [(root / "spawn-ledger.json", "create_time")]+ sources += [(base / "processes.json", "host_start_time") for base in {home, root}]+ pids: set[int] = set()+ for path, stamp_key in sources:+ try:+ entries = json.loads(path.read_text(encoding="utf-8-sig"))+ except (OSError, ValueError):+ continue+ for entry in entries if isinstance(entries, list) else []:+ pid, stamp = (entry.get("pid"), entry.get(stamp_key)) if isinstance(entry, dict) else (None, None)+ if not isinstance(pid, int) or pid <= 0 or entry.get("pid_scope", "host") != "host":+ continue+ try:+ if stamp is None:+ alive = psutil.pid_exists(pid)+ elif stamp_key == "create_time":+ alive = abs(psutil.Process(pid).create_time() - float(stamp)) < 2.0+ else:+ from gateway.status import get_process_start_time++ alive = get_process_start_time(pid) == stamp+ except (psutil.Error, OSError, TypeError, ValueError):+ continue+ if alive:+ pids.add(pid)+ return pids+++def _owned_by_hermes(proc, registered: set[int]) -> bool:+ """Registered itself, or a descendant of a live registered process (a background shell's+ child). An orphan whose spawning shell is gone was reparented away from that lineage, so+ it is not owned and is still reaped."""+ import psutil++ try:+ # pid 1 is excluded as an ancestor: a Hermes running as a container init adopts every orphan.+ return proc.pid in registered or any(p.pid in registered and p.pid != 1 for p in proc.parents())+ except (psutil.Error, OSError):+ return False++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.@@ -165,6 +221,9 @@ def reap_processes_rooted_in(scratch_root: Path, doomed: list[Path], audit: loggOnly the cwd is consulted: a process merely holding a file open inside scratch (aneditor, a log tail) is not ours to kill, but one *living* in a directory we areabout to delete, or in one already gone, has nothing left to run for.++ A process Hermes owns (:func:`_owned_by_hermes`) is never signalled; each doomed entry it+ works inside is dropped from *doomed* in place and recorded as kept."""import psutil@@ -190,6 +249,21 @@ def reap_processes_rooted_in(scratch_root: Path, doomed: list[Path], audit: loggcontinueif deleted or not os.path.exists(cwd_path) or any(_under(cwd_path, t) for t in targets):victims.append((proc, cwd_path))+ registered = _registered_live_pids(Path(root).parent.parent) if victims else set()+ owned = [(proc, cwd_path) for proc, cwd_path in victims if _owned_by_hermes(proc, registered)]+ for proc, cwd_path in owned:+ for entry in [e for e in doomed if _under(cwd_path, os.path.realpath(str(e)))]:+ doomed.remove(entry)+ try:+ name = proc.name()+ except (psutil.Error, OSError):+ name = "?"+ audit.info("scratch prune: kept %r — live Hermes process pid=%d (%r) works inside",+ os.fspath(entry), proc.pid, name)+ # Re-filter against the shrunk *doomed*: an orphan in a kept entry is spared with it (the+ # reap only exists to clear the way for rmtree); one whose cwd is already gone still goes.+ victims = [(proc, cwd_path) for proc, cwd_path in victims if (proc, cwd_path) not in owned+ and (not os.path.exists(cwd_path) or any(_under(cwd_path, os.path.realpath(str(e))) for e in doomed))]if not victims:return 0for proc, cwd_path in victims:diff --git a/tests/test_scratch_dir.py b/tests/test_scratch_dir.pyindex 120c6c881f8..28a86cf2ec6 100644--- a/tests/test_scratch_dir.py+++ b/tests/test_scratch_dir.py@@ -1,6 +1,8 @@"""Scratch dir contract: TMPDIR/TMP/TEMP follow HERMES_HOME/cache/scratch unless the user set them."""+import contextlibimport os+import shleximport shutilimport statimport subprocess@@ -9,6 +11,7 @@ import timefrom pathlib import Pathfrom unittest.mock import patch+import psutilimport pytestfrom hermes_constants import apply_scratch_tmp_env, get_scratch_dir, prune_scratch_dir@@ -556,3 +559,48 @@ def test_postremoval_unreadable_entry_is_not_counted_as_removed(tmp_path: Path)assert f"removed {str(entry)!r} (" not in log, logassert "could not confirm removal" in log, logassert "could not fully remove" not in log, log++[email protected](sys.platform == "win32", reason="POSIX shell orphaning")[email protected]_system_guard_bypass # a red run must kill the orphan this test made (reparented to init)+def test_prune_keeps_entry_a_registered_hermes_process_works_in_but_reaps_orphans(tmp_path, monkeypatch):+ """#132401 live-worker guard: a background process Hermes itself started (tracked in the+ process registry's ``processes.json``) is never reaped, and the idle entry it works in is+ kept with an audit line. The orphaned grandchild of a registered shell that already exited+ is no longer Hermes' — it is still reaped and its entry removed. Red on the cwd-only reap."""+ from tools.process_registry import ProcessRegistry++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ scratch = get_scratch_dir(tmp_path, prune=False)+ owned_dir, orphan_dir = scratch / "live-worker", scratch / "dead-lane"+ owned_dir.mkdir()+ orphan_dir.mkdir()+ sleeper = f"{shlex.quote(sys.executable)} -c 'import time; time.sleep(60)'"+ pidfile = tmp_path / "orphan.pid"+ registry = ProcessRegistry()+ worker = registry.spawn_local(sleeper, cwd=str(owned_dir))+ lane = registry.spawn_local(f"{sleeper} >/dev/null 2>&1 </dev/null & echo $! > {shlex.quote(str(pidfile))}",+ cwd=str(orphan_dir))+ deadline = time.time() + 15+ while not (lane.exited and pidfile.exists() and pidfile.read_text().strip()) and time.time() < deadline:+ registry.poll(lane.id)+ time.sleep(0.1)+ orphan = int(pidfile.read_text())+ ancient = time.time() - 30 * 3600+ for path in (owned_dir, orphan_dir):+ os.utime(path, (ancient, ancient))+ try:+ assert prune_scratch_dir(scratch) == 1+ assert owned_dir.exists() and not orphan_dir.exists()+ assert worker.process.poll() is None, "registered Hermes worker was reaped"+ deadline = time.time() + 10+ while psutil.pid_exists(orphan) and psutil.Process(orphan).status() != psutil.STATUS_ZOMBIE \+ and time.time() < deadline:+ time.sleep(0.1)+ assert not psutil.pid_exists(orphan) or psutil.Process(orphan).status() == psutil.STATUS_ZOMBIE+ log = (tmp_path / "logs" / "scratch-prune.log").read_text(encoding="utf-8-sig")+ assert f"kept {str(owned_dir)!r} — live Hermes process pid=" in log, log+ finally:+ registry.kill_process(worker.id)+ with contextlib.suppress(psutil.Error):+ psutil.Process(orphan).kill()diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex cdcdfcaba10..668b809069f 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -264,9 +264,12 @@ stays as long as anything anywhere inside it was written in the last day, and gothe last write. Before an idle entry is deleted, Hermes also stops any process still runningwith 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. Each entry is re-checked right before it is deleted, so+registration that pointed into it. A process Hermes itself started and still tracks (a+background `terminal` process, the gateway, a CLI session, or anything they launched that is+still their child) is never stopped: an idle entry one of them is working inside is kept+instead. Each entry is re-checked right before it is deleted, soone written to while the prune was stopping processes is kept. Every removal, stopped-process and entry kept by that re-check is recorded in `~/.hermes/logs/scratch-prune.log`. `hermes doctor`+process and kept entry is recorded in `~/.hermes/logs/scratch-prune.log`. `hermes doctor`reports the directory and its size, andwarns about directories over 1 GB elsewhere under `cache/` that no pruner covers.