The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): adopt the orchestrator's marker without psutil in -S children
ethernet6a8669269564
diff --git a/hermes_cli/update_lock.py b/hermes_cli/update_lock.pyindex 078df581bfb..acfbbc36395 100644--- a/hermes_cli/update_lock.py+++ b/hermes_cli/update_lock.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport loggingimport os+import subprocessimport timefrom contextlib import suppressfrom dataclasses import dataclass@@ -69,6 +70,35 @@ def _handoff_pid() -> int | None:return pid if pid > 0 else None+def _stdlib_parent_pid(pid: int) -> int | None:+ """The parent of ``pid`` without psutil, or ``None`` when unresolvable.++ The update-takeover child is spawned ``-I -S -B`` (hermes_cli/_old_updater.py) so+ psutil cannot import there — and that grandchild is exactly the process that most+ needs the two-hop ancestry walk to adopt the orchestrator's marker. /proc serves+ Linux; macOS keeps /proc absent, so shell out to ps once per hop.+ """+ try:+ if os.path.isdir("/proc"):+ with open(f"/proc/{pid}/stat", "rb") as fh:+ stat = fh.read()+ else:+ out = subprocess.run(+ ["ps", "-o", "ppid=", "-p", str(pid)],+ capture_output=True, text=True, check=True, timeout=5,+ ).stdout+ value = int(out.strip() or -1)+ return value if value > 0 else None+ except (OSError, ValueError, subprocess.SubprocessError):+ return None+ # Field 4 (1-indexed) is ppid, but comm may contain spaces/parens: split+ # after the closing paren of comm instead of on whitespace.+ try:+ return int(stat[stat.rindex(b")") + 2:].split()[1])+ except (ValueError, IndexError):+ return None++def _is_ancestor_pid(pid: int) -> bool:"""True when ``pid`` is a live ancestor of this process.@@ -83,6 +113,19 @@ def _is_ancestor_pid(pid: int) -> bool:try:import psutilreturn any(parent.pid == pid for parent in psutil.Process().parents())+ except ImportError:+ # -I -S -B takeover child: walk the same chain with stdlib probes.+ child = os.getpid()+ for _ in range(32):+ parent = _stdlib_parent_pid(child)+ if parent is None:+ return False+ if parent == pid:+ return True+ if parent == child: # pid 1 re-parenting or a kernel loop guard+ return False+ child = parent+ return Falseexcept Exception as exc:logger.debug("Could not walk process ancestry for pid %s: %s", pid, exc)return Falsediff --git a/tests/hermes_cli/test_update_lock.py b/tests/hermes_cli/test_update_lock.pyindex 912d217d898..5d6f8c39ffd 100644--- a/tests/hermes_cli/test_update_lock.py+++ b/tests/hermes_cli/test_update_lock.py@@ -18,6 +18,7 @@ from __future__ import annotationsimport osimport time+from pathlib import Pathimport pytest@@ -30,6 +31,10 @@ from hermes_cli.update_lock import (update_marker_path,)+# Repo root: the -I -S -B subprocesses insert it on sys.path to import the+# real hermes_cli without site-packages.+REPO_ROOT = Path(__file__).resolve().parents[2]+# A pid no live process owns. os.kill(pid, 0) must report it dead so a crashed# updater can never wedge every future update. Deliberately larger than any# platform's pid_t so it also covers the corrupt-marker path (OverflowError).@@ -252,7 +257,97 @@ class TestAncestryHandoff:lock.release()assert marker.exists(), "the parent still needs its marker after our stage ends"- assert int(marker.read_text(encoding="utf-8").splitlines()[0]) == os.getppid()++ def test_grandchild_adopts_orchestrator_marker_without_psutil(self, marker, tmp_path):+ """Regression: the desktop hand-off's grandchild refused its own orchestrator.++ The posix shim (grandparent) holds the marker and spawns ``hermes update``+ (direct child — adopts via getppid). An old-updater update into a PM tree+ then hands off again: ``_old_updater._run_child`` spawns+ ``_update_takeover.py`` as ``python -I -S -B``, where psutil cannot import+ (-S skips site-packages). The psutil-only ancestry walk returned False for+ the two-hops-up shim, and the takeover child refused with exit 2 —+ "Another Hermes update is already running (PID <the shim itself>)" —+ observed live on a macOS rehearsal install. The stdlib fallback walk is+ what must adopt here.+ """+ import subprocess+ import sys+ from textwrap import dedent++ # Simulate the orchestrator: this test process holds the marker and+ # spawns the -I -B middle, which spawns the -I -S -B takeover-like leaf.+ marker.write_text(f"{os.getpid()}\n{int(time.time())}\n", encoding="utf-8")++ leaf = dedent(+ """+ import sys+ from pathlib import Path+ sys.path.insert(0, %(root)r)+ from hermes_cli.update_lock import UpdateLock+ lock = UpdateLock(path=Path(%(marker)r))+ if not lock.acquire():+ print("REFUSED", lock.holder.pid)+ raise SystemExit(2)+ assert lock.acquired is False, "the orchestrator's claim is not ours to own"+ print("ADOPTED")+ """+ ) % {"root": str(REPO_ROOT), "marker": str(marker)}+ middle = dedent(+ """+ import subprocess, sys+ code = subprocess.run(+ [sys.executable, "-I", "-S", "-B", "-c", %(leaf)r],+ ).returncode+ raise SystemExit(code)+ """+ ) % {"leaf": leaf}++ result = subprocess.run(+ [sys.executable, "-I", "-B", "-c", middle],+ capture_output=True, text=True, timeout=120,+ )+ assert result.returncode == 0, result.stderr+ assert "ADOPTED" in result.stdout+ assert marker.exists(), "the orchestrator still needs its marker after the leaf ends"++ def test_unrelated_live_holder_is_still_refused_under_stdlib_walk(self, marker, tmp_path):+ """The stdlib fallback must not widen the lock: a foreign pid stays foreign.++ The marker owner is a live *sibling* of the leaf (a sleeper spawned by+ this test), never an ancestor of it — the shape of an unrelated+ concurrent updater. The leaf's ancestry walk dead-ends at pytest and+ the sibling must keep the lock.+ """+ import subprocess+ import sys+ import time as time_mod+ from textwrap import dedent++ sleeper = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(300)"])+ try:+ marker.write_text(f"{sleeper.pid}\n{int(time_mod.time())}\n", encoding="utf-8")+ assert read_live_update(path=marker) is not None++ leaf = dedent(+ """+ import sys+ from pathlib import Path+ sys.path.insert(0, %(root)r)+ from hermes_cli.update_lock import UpdateLock+ lock = UpdateLock(path=Path(%(marker)r))+ print("ADOPTED" if lock.acquire() else "REFUSED")+ """+ ) % {"root": str(REPO_ROOT), "marker": str(marker)}+ result = subprocess.run(+ [sys.executable, "-I", "-S", "-B", "-c", leaf],+ capture_output=True, text=True, timeout=120,+ )+ assert result.returncode == 0, result.stderr+ assert "REFUSED" in result.stdout+ finally:+ sleeper.kill()+ sleeper.wait()def test_live_non_ancestor_holder_is_still_refused(self, marker):"""Ancestry must not open the lock to unrelated concurrent updaters."""