The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): accept verified host ownership and report refused stops
hxy91819fa0fc39ee58f
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex 04a152dee88..b477796e61c 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -5302,7 +5302,8 @@ def _cmd_start(args):def _cmd_stop(args):_refuse_from_inside_gateway("stop", "restart loops")- from hermes_cli.gateway_profile_lifecycle import host_scope_for_all_verb, profile_lifecycle, separate_gateway_pids+ from hermes_cli.gateway_profile_lifecycle import (+ host_scope_for_all_verb, profile_lifecycle, report_profile_stop_failure, separate_gateway_pids)if profile_lifecycle("stop", args):returnstop_all = getattr(args, "all", False)@@ -5345,7 +5346,7 @@ def _cmd_stop(args):elif stop_profile_gateway():print("✓ Stopped gateway for this profile")else:- print("✗ No gateway running for this profile")+ report_profile_stop_failure()def _stop_host_multiplexer(owner) -> int:diff --git a/hermes_cli/gateway_profile_lifecycle.py b/hermes_cli/gateway_profile_lifecycle.pyindex b4a0c960bdc..3d25e47d7df 100644--- a/hermes_cli/gateway_profile_lifecycle.py+++ b/hermes_cli/gateway_profile_lifecycle.py@@ -151,9 +151,9 @@ def print_parked_status() -> bool:def owned_gateway_pid() -> int | None:"""Return only a freshly confirmed process owned by this profile.- A missing (or cached missing) host is not ownership evidence. Refresh the host- probe, then resolve the candidate's live process home independently of runtime- status: a satellite's status legitimately carries another home's shared PID.+ A missing (or cached missing) host is not ownership evidence. Accept a fresh+ host identity matching PID/home, otherwise require pinned process launch evidence:+ a satellite's runtime status legitimately carries another home's shared PID."""from gateway import host_attachfrom gateway.status import get_running_pid, _get_process_hermes_home, _same_hermes_home@@ -166,8 +166,13 @@ def owned_gateway_pid() -> int | None:host_attach.invalidate_host_gateway_cache()owner = host_attach.host_gateway()home = _get_process_hermes_home()- if owner is not None and owner.pid == pid and not _same_hermes_home(owner.home, home):- return None+ if owner is not None and owner.pid == pid:+ if not _same_hermes_home(owner.home, home):+ return None+ # host_gateway refreshed liveness/incarnation and matched the control+ # socket's PID/home. A bare foreground launch needs no argv profile.+ if owner.served_known:+ return pid if get_running_pid() == pid else Noneprocess_home = _hermes_home_for_pid(pid, require_launch_identity=True)if process_home is None or not _same_hermes_home(process_home, home):return None@@ -177,3 +182,21 @@ def owned_gateway_pid() -> int | None:# An inaccessible rendezvous or process is never permission to kill it.logger.debug("Could not prove gateway process ownership", exc_info=True)return None+++def report_profile_stop_failure() -> None:+ """Do not report absence when a live PID was refused or the probe failed."""+ from gateway.status import get_running_pid+ from hermes_cli import gateway as gw++ try:+ absent = get_running_pid() is None and not gw.find_gateway_pids()+ except Exception:+ logger.debug("Could not confirm gateway absence after stop", exc_info=True)+ absent = False+ if absent:+ print("✗ No gateway running for this profile")+ return+ gw.print_error("Gateway stop was not confirmed; a gateway may still be running. "+ "Check gateway status and process ownership.")+ raise SystemExit(1)diff --git a/tests/gateway/test_multiplex_hot_serve_live.py b/tests/gateway/test_multiplex_hot_serve_live.pyindex 8716e5636c6..49b2a1f82d4 100644--- a/tests/gateway/test_multiplex_hot_serve_live.py+++ b/tests/gateway/test_multiplex_hot_serve_live.py@@ -84,12 +84,12 @@ def mux(tmp_path, peer):return {'root': root, 'boot': boot, 'env': env, 'config': config, 'log': tmp_path / 'gateway.log'}-def start_daemon(mux, timeout=90):+def start_daemon(mux, timeout=90, *, extra_args=()):"""Boot the multiplexer the way ``hermes gateway run`` does; the canonical gateway command-linematcher (``gateway.status.looks_like_gateway_command_line``) is what the CLI's liveness probesapply to the recorded PID, so the fixture must spawn a recognisable launcher."""log = mux['log'].open('a+', encoding='utf-8', errors='replace')- proc = subprocess.Popen([sys.executable, '-m', 'hermes_cli.main', 'gateway', 'run', '--quiet'], cwd=ROOT,+ proc = subprocess.Popen([sys.executable, '-m', 'hermes_cli.main', 'gateway', 'run', '--quiet', *extra_args], cwd=ROOT,env=mux['env'], stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)desc = {}deadline = time.monotonic() + timeout@@ -412,3 +412,16 @@ def test_standalone_secondary_stops_without_stopping_host(mux):if child is not None:stop(child, expect=None)stop(host, expect=None)+++def test_unsupervised_host_without_profile_flag_can_stop(mux):+ proc, _ = start_daemon(mux, extra_args=('--no-supervise',))+ try:+ result = subprocess.run(+ [sys.executable, '-m', 'hermes_cli.main', 'gateway', 'stop'],+ cwd=ROOT, env=mux['env'], capture_output=True, text=True, timeout=45, check=False)+ assert result.returncode == 0, (result.stdout, result.stderr)+ assert 'Stopped gateway for this profile' in result.stdout, (result.stdout, result.stderr)+ proc.wait(timeout=30)+ finally:+ stop(proc, expect=None)diff --git a/tests/hermes_cli/test_gateway_multiplex_lifecycle.py b/tests/hermes_cli/test_gateway_multiplex_lifecycle.pyindex 2c98fd404e3..bada54fcad7 100644--- a/tests/hermes_cli/test_gateway_multiplex_lifecycle.py+++ b/tests/hermes_cli/test_gateway_multiplex_lifecycle.py@@ -331,7 +331,7 @@ def test_process_discovery_excludes_host_even_after_unserve(homes, monkeypatch,from gateway import status, host_attachfrom hermes_cli import gateway as gw, dashboard_procsroot, secondary = homes- owner = SimpleNamespace(pid=4242, home=root, profiles=('default', 'worker') if served else ('default',))+ owner = SimpleNamespace(pid=4242, home=root, served_known=True, profiles=('default', 'worker') if served else ('default',))monkeypatch.setenv('HERMES_HOME', str(secondary))monkeypatch.setattr(host_attach, '_probe_host_gateway', lambda wait: owner)monkeypatch.setattr(dashboard_procs, '_hermes_home_for_pid', lambda pid, **kw: str(root if pid == 4242 else secondary))@@ -453,3 +453,48 @@ def test_launch_identity_does_not_follow_sticky_selection(homes, monkeypatch, idmonkeypatch.setattr(host_attach, '_probe_host_gateway', lambda wait: None)monkeypatch.setattr(status, 'get_running_pid', lambda **kw: 4242)assert gw._owned_gateway_pid() == (None if identity == 'ambiguous' else 4242)++[email protected]('runtime', ['present', 'absent', 'unknown'])+def test_cli_stop_reports_unconfirmed_separately_from_absent(homes, monkeypatch, capsys, runtime):+ from gateway import status+ from hermes_cli import gateway as gw, gateway_profile_lifecycle as lifecycle+ monkeypatch.setattr(lifecycle, 'profile_lifecycle', lambda *a: False)+ monkeypatch.setattr(gw, '_refuse_from_inside_gateway', lambda *a: None)+ monkeypatch.setattr(gw, 'find_gateway_pids', lambda **kw: [])+ monkeypatch.setattr(gw, '_served_by_another_host_gateway', lambda: None)+ monkeypatch.setattr(gw, 'named_profile_served_by_running_multiplexer', lambda: False)+ monkeypatch.setattr(gw, '_dispatch_via_service_manager_if_s6', lambda *a: False)+ monkeypatch.setattr(gw, '_stop_installed_service', lambda *a: False)+ monkeypatch.setattr(gw, 'stop_profile_gateway', lambda: False)++ def pid():+ if runtime == 'unknown':+ raise OSError('cannot inspect gateway')+ return 4242 if runtime == 'present' else None++ monkeypatch.setattr(status, 'get_running_pid', pid)+ if runtime == 'absent':+ gw._cmd_stop(SimpleNamespace())+ assert 'No gateway running' in capsys.readouterr().out+ else:+ with pytest.raises(SystemExit) as result:+ gw._cmd_stop(SimpleNamespace())+ assert result.value.code != 0+ output = capsys.readouterr().out+ assert 'No gateway running' not in output+ assert 'not confirmed' in output++[email protected]('verified,changed', [(True, False), (True, True), (False, False)])+def test_same_home_record_requires_identity_and_stable_pid(homes, monkeypatch, verified, changed):+ from gateway import host_attach, status+ from hermes_cli import gateway as gw, dashboard_procs+ root, _ = homes+ monkeypatch.setenv('HERMES_HOME', str(root))+ owner = host_attach.HostGateway(4242, root, ('default',), served_known=verified)+ monkeypatch.setattr(host_attach, '_probe_host_gateway', lambda wait: owner)+ monkeypatch.setattr(dashboard_procs, '_hermes_home_for_pid', lambda pid, **kw: None)+ pids = iter([4242, 4343 if changed else 4242])+ monkeypatch.setattr(status, 'get_running_pid', lambda: next(pids))+ assert gw._owned_gateway_pid() == (4242 if verified and not changed else None)