The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(terminal): a foreground command dies with the Hermes process that ran it (orphans_after_10s 2 -> 0)
kshitijk4poor63519c9a7404
diff --git a/tests/tools/test_local_env_cwd_recovery.py b/tests/tools/test_local_env_cwd_recovery.pyindex 0f0e5d4e736..bdeb2d672b2 100644--- a/tests/tools/test_local_env_cwd_recovery.py+++ b/tests/tools/test_local_env_cwd_recovery.py@@ -77,6 +77,12 @@ def _close_fds(fds):class TestRunBashCwdRecovery:"""End-to-end recovery: deleted ``self.cwd`` must not crash Popen."""+ @pytest.fixture(autouse=True)+ def _no_supervisor(self, monkeypatch):+ # The faked Popen must see only the command, not the owner-death supervisor's spawn.+ monkeypatch.setattr("tools.environments.local.own_process_groups", lambda pgids: None)+ monkeypatch.setattr("tools.environments.local.release_process_groups", lambda pgids: None)+def test_recovers_when_cwd_deleted_after_init(self, tmp_path, caplog):"""Reproduces the wedge from #17558: cwd was valid when thesnapshot was taken, but a subsequent command deleted it before thediff --git a/tests/tools/test_terminal_owned_jobs.py b/tests/tools/test_terminal_owned_jobs.pynew file mode 100644index 00000000000..87b7a127e65--- /dev/null+++ b/tests/tools/test_terminal_owned_jobs.py@@ -0,0 +1,116 @@+"""POSIX: terminal commands die with the Hermes process that started them.++The owners are real host processes using the real ``LocalEnvironment.execute``. One owner is SIGKILLed,+so no Python cleanup of ours runs; the other is the live-owner control.+"""++import json+import os+from pathlib import Path+import subprocess+import sys++import psutil+import pytest++from tests.waiting import wait_until++pytestmark = pytest.mark.platforms("posix")++_OWNER = r'''+import json, os, sys, threading, time+from pathlib import Path+root, role = Path(sys.argv[1]), sys.argv[2]+from tools.environments.local import LocalEnvironment+ids = {}+env = LocalEnvironment(cwd=str(root), timeout=600)+fg = root / f"{role}.fg"+threading.Thread(target=env.execute, args=(f"sleep 120 & echo $! > {fg}; wait",), daemon=True).start()+wait_until = time.time() + 30+while not fg.exists() and time.time() < wait_until:+ time.sleep(0.05)+ids["foreground"] = [int(fg.read_text().strip())]+out = {}+for name, pids in ids.items():+ out[name] = [{"pid": pid, "created": __import__("psutil").Process(pid).create_time()} for pid in pids]+(root / (role + ".tmp")).write_text(json.dumps(out))+os.replace(root / (role + ".tmp"), root / (role + ".json"))+while True:+ time.sleep(1)+'''+++def _alive(identity):+ """Zombie-aware: a killed non-child lingers as a zombie until its reaper collects it."""+ try:+ proc = psutil.Process(identity["pid"])+ return proc.create_time() == identity["created"] and proc.status() != psutil.STATUS_ZOMBIE+ except psutil.NoSuchProcess:+ return False+++def _read(path):+ wait_until(path.exists, timeout=60, what=f"owner receipt {path.name}")+ return json.loads(path.read_text(encoding="utf-8-sig"))+++def _run_owners(tmp_path, roles):+ script = tmp_path / "disposable owner.py"+ script.write_text(_OWNER, encoding="utf-8")+ env = dict(os.environ, HOME=str(tmp_path), HERMES_HOME=str(tmp_path / "home"),+ PYTHONPATH=str(Path(__file__).resolve().parents[2]))+ env.pop("_HERMES_GATEWAY", None)+ log = (tmp_path / "owners.log").open("w", encoding="utf-8")+ owners = {role: subprocess.Popen([sys.executable, str(script), str(tmp_path), role], env=env,+ stdin=subprocess.DEVNULL, stdout=log, stderr=log)+ for role in roles}+ return owners, log+++def _cleanup(owners, log, ids):+ for identity in (i for group in ids.values() for job in group.values() for i in job):+ if _alive(identity):+ psutil.Process(identity["pid"]).kill()+ for owner in owners.values():+ if owner.poll() is None:+ owner.kill()+ owner.wait(timeout=10)+ log.close()+++# Commands reparent to init once their owner dies, so cleaning them up leaves this test's subtree; real+# signal delivery to real orphans is the point of the test.[email protected]_system_guard_bypass+def test_owner_sigkill_takes_its_running_command_not_a_live_owners(tmp_path):+ owners, log = _run_owners(tmp_path, ("control", "victim"))+ ids = {}+ try:+ ids = {role: _read(tmp_path / f"{role}.json") for role in owners}+ owners["victim"].kill() # SIGKILL: no atexit, no finally, nothing of ours runs+ owners["victim"].wait(timeout=10)++ wait_until(lambda: not any(_alive(i) for i in ids["victim"]["foreground"]), timeout=15,+ what="the dead owner's foreground command to exit")+ assert all(_alive(i) for i in ids["control"]["foreground"]), (+ "a live owner's command was killed", ids["control"])+ finally:+ _cleanup(owners, log, ids)+++def _record_calls(monkeypatch):+ from tools.environments import local as local_mod++ calls = []+ monkeypatch.setattr(local_mod, "own_process_groups", lambda pgids: calls.append(("own", list(pgids))))+ monkeypatch.setattr(local_mod, "release_process_groups", lambda pgids: calls.append(("release", list(pgids))))+ return calls+++def test_a_returned_command_releases_its_group(monkeypatch, tmp_path):+ from tools.environments.local import LocalEnvironment++ calls = _record_calls(monkeypatch)+ env = LocalEnvironment(cwd=str(tmp_path), timeout=30)+ calls.clear()+ assert env.execute("echo hi")["returncode"] == 0+ assert [verb for verb, _ in calls] == ["own", "release"] and calls[0][1] == calls[1][1], callsdiff --git a/tools/environments/local.py b/tools/environments/local.pyindex 1dc153c38bc..47b6ee2139c 100644--- a/tools/environments/local.py+++ b/tools/environments/local.py@@ -21,6 +21,7 @@ from hermes_constants import get_process_hermes_homefrom tools.environments.base import BaseEnvironmentfrom tools.environments.base_output import _pipe_stdinfrom hermes_cli._subprocess_compat import windows_hide_flags+from hermes_cli.process_identity import own_process_groups, release_process_groupsfrom tools.environments.local_env_policy import (_ALWAYS_STRIP_FOLDED, _ALWAYS_STRIP_KEYS, _HERMES_PROVIDER_ENV_BLOCKLIST, _HERMES_PROVIDER_ENV_FORCE_PREFIX,_is_hermes_internal_secret, _is_provider_env_blocklisted, _is_terminal_first_party_env,@@ -1141,13 +1142,20 @@ class LocalEnvironment(BaseEnvironment):cmd_string = _prepend_shell_init(cmd_string, _resolve_shell_init_files())args = [bash, *(["-l"] if login else []), "-c", cmd_string]self._recover_cwd()+ # Not spawn_owned: an awaited command needs no spawn-ledger entry; own_process_groups below hands+ # its group to the owner-death supervisor and _wait_for_process releases it.proc = subprocess.Popen(args, text=True, env=run_env, encoding="utf-8", errors="replace",stdout=subprocess.PIPE, stderr=subprocess.STDOUT,stdin=subprocess.PIPE if stdin_data is not None else subprocess.DEVNULL,+ # detached-spawn: ok — owned via own_process_groups right belowstart_new_session=True, cwd=self.cwd,**({"creationflags": windows_hide_flags()} if _IS_WINDOWS else {}))if not _IS_WINDOWS:+ # The command dies with this process however it dies: a SIGKILLed / OOM-killed host left a+ # running `npm run dev` or `sleep` on init. Released once the wait returns (see below).+ own_process_groups([proc.pid])+ proc._hermes_owned_pgid = proc.pidwith contextlib.suppress(ProcessLookupError):proc._hermes_pgid = os.getpgid(proc.pid)# Record the group leader's start-time fingerprint so _kill_process can@@ -1160,6 +1168,17 @@ class LocalEnvironment(BaseEnvironment):_pipe_stdin(proc, stdin_data)return proc+ def _wait_for_process(self, proc, *args, **kwargs) -> dict:+ """Base wait, then hand the command's group back from the owner-death supervisor: once the+ command returned, what it left running in the background (`server &`) is not ours to kill,+ exactly as on a graceful exit."""+ try:+ return super()._wait_for_process(proc, *args, **kwargs)+ finally:+ if (owned_pgid := getattr(proc, "_hermes_owned_pgid", None)) is not None:+ proc._hermes_owned_pgid = None+ release_process_groups([owned_pgid])+def _kill_process(self, proc):"""Kill the entire process group (all children)."""try: