The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): keep satellite stops off the shared host process
hxy91819d516ce878de8
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex 7ec682d9966..709ae094d15 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -68,6 +68,7 @@ from hermes_cli.setup import (prompt_yes_no,)from hermes_cli.colors import Colors, color+from hermes_cli.gateway_profile_lifecycle import owned_gateway_pid as _owned_gateway_pidlogger = logging.getLogger(__name__)# Shared ``subprocess.run`` kwargs for text-mode probes (stdout/stderr captured, decode-tolerant).@@ -756,8 +757,7 @@ def find_gateway_pids(exclude_pids: set | None = None, all_profiles: bool = Falspids: list[int] = []if not all_profiles:try:- from gateway.status import get_running_pid- _append_unique_pid(pids, get_running_pid(), _exclude)+ _append_unique_pid(pids, _owned_gateway_pid(), _exclude)except Exception:passfor pid in _get_service_pids(all_profiles=all_profiles):@@ -1982,7 +1982,7 @@ def stop_profile_gateway() -> bool:except ImportError:return False- pid = get_running_pid()+ pid = _owned_gateway_pid()if pid is None:return _reap_unsupervised_gateway_orphans()host = _host_multiplexer_for_all_verb()diff --git a/hermes_cli/gateway_profile_lifecycle.py b/hermes_cli/gateway_profile_lifecycle.pyindex bfb0499882b..207eb16bfd7 100644--- a/hermes_cli/gateway_profile_lifecycle.py+++ b/hermes_cli/gateway_profile_lifecycle.py@@ -141,3 +141,21 @@ def print_parked_status() -> bool:for profile in parked:print(f"Profile '{profile}': parked (hermes -p {profile} gateway start)")return False+++def owned_gateway_pid() -> int | None:+ """A gateway this profile may stop, excluding its shared host's liveness PID.++ Runtime status for a satellite reports the host PID, including briefly after+ unserve while status catches up. Check host ownership regardless of its roster.+ A separate forced/standalone gateway still owns its normal process lifecycle.+ """+ from gateway.status import get_running_pid+ from hermes_cli import gateway as gw++ pid = get_running_pid()+ if pid is not None:+ owner = gw._host_multiplexer_for_all_verb()+ if owner is not None and owner.pid == pid and not gw._host_multiplexer_is_ours(owner):+ return None+ return piddiff --git a/tests/gateway/test_multiplex_hot_serve_live.py b/tests/gateway/test_multiplex_hot_serve_live.pyindex 6fbfc48f551..cb9724dcae6 100644--- a/tests/gateway/test_multiplex_hot_serve_live.py+++ b/tests/gateway/test_multiplex_hot_serve_live.py@@ -312,3 +312,77 @@ def test_invalid_hot_profile_config_is_parked_and_unserved(mux):wait_recorded(root, lambda r: 'boot' not in r, 'parked boot withdrawn from the recorded set')finally:stop(proc, expect=None)+++async def chat_for(root, home, desc, *, during_turn=None):+ """Exercise the real session/agent path; only the model HTTP wire is a fixture."""+ grant = control(root, 'session-ticket', {'profile_id': str(home.resolve()),+ 'instance_id': desc['instance_id'], 'purpose': 'interactive'})+ url = desc['api_origin'].replace('http:', 'ws:') + '/api/ws'+ async with connect(url, subprotocols=['hermes-gateway-v1', 'hermes-gateway-ticket.' + grant['ticket']]) as ws:+ async def until(predicate):+ async with asyncio.timeout(40):+ while True:+ reply = json.loads(await ws.recv())+ if predicate(reply):+ return reply++ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': 'session.create',+ 'params': {'request_id': 'profile-stop-chat', 'source': 'cli'}}))+ created = await until(lambda r: r.get('id') == 1)+ assert 'result' in created, created+ sid = created['result']['session_id']+ # Keep the same connection and conversation for a second turn after the stop.+ for index in range(2):+ text = 'WS_SHARED BLOCK_FIFO' if during_turn and index == 0 else 'WS_SHARED'+ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': index + 2, 'method': 'prompt.submit',+ 'params': {'session_id': sid, 'text': text, 'input_id': f'profile-stop-{index}'}}))+ submitted = await until(lambda r: r.get('id') == index + 2)+ assert 'result' in submitted, submitted+ if during_turn and index == 0:+ await during_turn()+ terminal = await until(lambda r: r.get('params', {}).get('type') in {'message.complete', 'error'})+ assert 'LOCAL_ACK_WS_SHARED' in json.dumps(terminal), terminal+++def test_stop_secondary_keeps_host_and_survives_host_restart(mux, peer):+ """A satellite's runtime PID is its serving host, never its process to kill."""+ import threading+ peer.blocked, peer.release = threading.Event(), threading.Event()+ root, boot = mux['root'], mux['boot']+ proc, desc = start_daemon(mux)++ async def stop_during_primary_turn():+ assert await asyncio.to_thread(peer.blocked.wait, 10), 'primary turn never reached model'+ try:+ stopped = await asyncio.to_thread(subprocess.run,+ [sys.executable, '-m', 'hermes_cli.main', '-p', 'boot', 'gateway', 'stop'],+ cwd=ROOT, env=mux['env'], capture_output=True, text=True, timeout=45, check=False)+ assert stopped.returncode == 0, (stopped.stdout, stopped.stderr)+ assert (boot / 'gateway.parked').exists(), (stopped.stdout, stopped.stderr)+ assert proc.poll() is None, tail(mux)+ after = control(root, 'identify')+ assert after['instance_id'] == desc['instance_id']+ assert served_homes(after) == {root.resolve()}+ finally:+ peer.release.set()++ try:+ asyncio.run(chat_for(root, root, desc, during_turn=stop_during_primary_turn))+ # An explicit host restart exercises persisted stop intent, not merely cached status.+ stop(proc)+ proc, desc = start_daemon(mux)+ assert served_homes(desc) == {root.resolve()}+ started = subprocess.run(+ [sys.executable, '-m', 'hermes_cli.main', '-p', 'boot', 'gateway', 'start'],+ cwd=ROOT, env=mux['env'], capture_output=True, text=True, timeout=45, check=False,+ )+ assert started.returncode == 0, (started.stdout, started.stderr)+ assert not (boot / 'gateway.parked').exists()+ after = control(root, 'identify')+ assert after['instance_id'] == desc['instance_id']+ assert served_homes(after) == {root.resolve(), boot.resolve()}+ asyncio.run(chat_for(root, boot, after))+ finally:+ peer.release.set()+ stop(proc, expect=None)diff --git a/tests/hermes_cli/test_gateway_multiplex_lifecycle.py b/tests/hermes_cli/test_gateway_multiplex_lifecycle.pyindex 78abf6f90eb..0b559d3094e 100644--- a/tests/hermes_cli/test_gateway_multiplex_lifecycle.py+++ b/tests/hermes_cli/test_gateway_multiplex_lifecycle.py@@ -324,3 +324,25 @@ def test_status_flags_a_gateway_this_hermes_cannot_attach(homes, monkeypatch, caassert ('✓ Gateway is running (PID: 4242)' in output) is healthyassert ('incompatible: runtime_protocol' in output) is not healthyassert ('hermes gateway restart' in output) is not healthy++[email protected]('served', [True, False])+def test_process_discovery_excludes_host_even_after_unserve(homes, monkeypatch, served):+ from gateway import status+ from hermes_cli import gateway as gw+ root, secondary = homes+ owner = SimpleNamespace(pid=4242, home=root, profiles=('default', 'worker') if served else ('default',))+ monkeypatch.setenv('HERMES_HOME', str(secondary))+ monkeypatch.setattr(gw, '_host_multiplexer_for_all_verb', lambda: owner)+ monkeypatch.setattr(gw, '_get_service_pids', lambda **kw: [])+ monkeypatch.setattr(gw, '_scan_gateway_pids', lambda *a, **kw: [])+ monkeypatch.setattr(status, 'get_running_pid', lambda **kw: owner.pid)+ assert gw.find_gateway_pids() == []+ assert gw.stop_profile_gateway() is False+ # A distinct --force gateway must retain its own lifecycle even while the host serves us.+ monkeypatch.setattr(status, 'get_running_pid', lambda **kw: 4343)+ assert gw.find_gateway_pids() == [4343]+ # The launching profile still owns the shared process.+ monkeypatch.setenv('HERMES_HOME', str(root))+ monkeypatch.setattr(status, 'get_running_pid', lambda **kw: owner.pid)+ assert gw.find_gateway_pids() == [owner.pid]