The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): `gateway restart` brings an auto-started gateway back
unsupportedpastels0087b9de1f13
diff --git a/gateway/control_socket.py b/gateway/control_socket.pyindex ebb6c9e4195..a35e92ff100 100644--- a/gateway/control_socket.py+++ b/gateway/control_socket.py@@ -128,15 +128,30 @@ def _detect_supervisor() -> str:return "external" if "--external-supervisor" in sys.argv else "manual"+def launch_supervisor(identity: dict[str, Any]) -> Optional[str]:+ """What launched the gateway behind an ``identify`` answer (``manual``, ``desktop``, ``systemd``, ...).++ The session runtime protocol folds ``manual`` and ``desktop`` into ``supervisor: "none"``, so the+ launch value rides in ``launch_supervisor``. A gateway that predates that field and answers+ ``"none"`` is ambiguous: None (unknown), never ``manual``.+ """+ for key in ("launch_supervisor", "supervisor"):+ value = identity.get(key)+ if isinstance(value, str) and value and value != "none":+ return value+ return None++def build_identify_payload() -> dict[str, Any]:"""Default ``identify`` answer, built from gateway.status primitives."""from gateway.status import _build_pid_record, _get_code_identity_fields, _profile_label_for_home, read_runtime_statusrecord = _build_pid_record()+ supervisor = _detect_supervisor()payload: dict[str, Any] = {"protocol": CONTROL_PROTOCOL_VERSION,**{k: record.get(k) for k in ("kind", "pid", "start_time", "hermes_home")},"profile": _profile_label_for_home(record.get("hermes_home") or ""),- "supervisor": _detect_supervisor(), **_get_code_identity_fields()}+ "supervisor": supervisor, "launch_supervisor": supervisor, **_get_code_identity_fields()}with contextlib.suppress(Exception):# served_profiles (multiplex mode) is stamped into runtime status by the runner.served = (read_runtime_status() or {}).get("served_profiles")diff --git a/hermes_cli/data_cleanup_holders.py b/hermes_cli/data_cleanup_holders.pyindex 37c04f4def4..d2fe6a10693 100644--- a/hermes_cli/data_cleanup_holders.py+++ b/hermes_cli/data_cleanup_holders.py@@ -15,7 +15,7 @@ _OWNER_STOP_HINTS = {def _drain_manual_gateway(home: Path) -> None:- from gateway.control_socket import identify_gateway, pause_gateway_for_update+ from gateway.control_socket import identify_gateway, launch_supervisor, pause_gateway_for_updatefrom gateway.status import get_process_start_time, get_running_pid_identity_strict, _pid_existsidentity = identify_gateway(home)@@ -25,9 +25,9 @@ def _drain_manual_gateway(home: Path) -> None:returnif not identity.get("hermes_home") or Path(identity["hermes_home"]).resolve() != home:raise RuntimeError(f"gateway control identity does not match {home}")- owner = identity.get("supervisor")+ owner = launch_supervisor(identity)if owner != "manual":- hint = _OWNER_STOP_HINTS.get(owner, "stop it through its supervisor before retrying")+ hint = _OWNER_STOP_HINTS.get(owner or "", "stop it through its supervisor before retrying")raise RuntimeError(f"{owner or 'unknown'} gateway still owns {home}; {hint}")if identity.get("served_profiles"):raise RuntimeError("gateway serves multiple profiles; stop it explicitly before deleting one profile's data")diff --git a/hermes_cli/gateway_supervised_restart.py b/hermes_cli/gateway_supervised_restart.pyindex 20062688dfc..27fbbc5bf32 100644--- a/hermes_cli/gateway_supervised_restart.py+++ b/hermes_cli/gateway_supervised_restart.py@@ -23,7 +23,7 @@ def gateway_declares_external_supervisor(pid: int, home: Path | None = None) ->"""True when the running gateway ``pid`` was launched for an external supervisor.The supervisor is SELF-declared by the gateway from its launch context: the control socket- ``identify`` answer (any ``supervisor`` other than ``"manual"`` — a custom systemd unit or+ ``identify`` answer (any launch supervisor other than ``"manual"`` — a custom systemd unit orlaunchd agent sets INVOCATION_ID / the XPC name, so the gateway answers ``systemd``/``launchd``even though ``_installed_service_kind_for`` saw no canonical unit, and the same supervisor ownsthe respawn), OR the ``--external-supervisor`` argv marker read live (same marker@@ -32,13 +32,14 @@ def gateway_declares_external_supervisor(pid: int, home: Path | None = None) ->"""if not pid or pid <= 1:return False- from gateway.control_socket import identify_gateway+ from gateway.control_socket import identify_gateway, launch_supervisorfrom gateway.status import _get_process_hermes_home, read_runtime_statusfrom hermes_cli.gateway import _capture_gateway_argvhome = home or _get_process_hermes_home()identity = identify_gateway(home) or {}- if identity.get("pid") == pid and identity.get("supervisor") not in (None, "", "manual"):+ # Not ``identity["supervisor"]``: the runtime protocol reports a manual gateway as "none".+ if identity.get("pid") == pid and launch_supervisor(identity) not in (None, "manual"):return Trueargv = _capture_gateway_argv(pid)if argv is None:diff --git a/hermes_cli/update_inventory.py b/hermes_cli/update_inventory.pyindex 4a772082b3a..3f65f9db990 100644--- a/hermes_cli/update_inventory.py+++ b/hermes_cli/update_inventory.py@@ -202,8 +202,11 @@ def _collect_gateway_runtimes(plan: UpdatePlan, profile_homes: list, seen: set[iif pid in seen:continue # one multiplex gateway answers identify for several homes — one record per processseen.add(pid)- declared = record.get("supervisor")- sup = str(declared) if declared else supervisor(pid)+ from gateway.control_socket import launch_supervisor++ # The protocol's "none" (manual or desktop) is no answer: classify it outside-in.+ declared = launch_supervisor(record)+ sup = declared if declared else supervisor(pid)else:# Verified identity, not bare PID existence: a ``stopped`` record whose PID was recycled# by an unrelated process fabricated a phantom gateway the restart phase could neverdiff --git a/tests/hermes_cli/test_gateway_launch_supervisor.py b/tests/hermes_cli/test_gateway_launch_supervisor.pynew file mode 100644index 00000000000..0e3a9f044e6--- /dev/null+++ b/tests/hermes_cli/test_gateway_launch_supervisor.py@@ -0,0 +1,116 @@+"""Local readers of a gateway's ``identify`` answer see what launched it, not the protocol's "none".++The session runtime protocol reports a manual or Desktop-spawned gateway as ``supervisor: "none"``.+``hermes gateway restart`` read that as an external supervisor: it SIGUSR1'd an auto-started+gateway, waited for a relaunch that never came, and exited 1 with no gateway running (#134889).+"""+from pathlib import Path+from types import SimpleNamespace++import pytest++from gateway import control_socket+from gateway import status as gateway_status+from hermes_cli import gateway as gw+from hermes_cli import gateway_supervised_restart as supervised++PLAIN_ARGV = ["/usr/bin/python", "-m", "hermes_cli.main", "gateway", "run"]+SUPERVISED_ARGV = [*PLAIN_ARGV, "--external-supervisor"]+MANUAL = {"pid": 4321, "supervisor": "none", "launch_supervisor": "manual"}++[email protected]("identity, expected", [+ ({"supervisor": "none", "launch_supervisor": "manual"}, "manual"),+ ({"supervisor": "none", "launch_supervisor": "desktop"}, "desktop"),+ ({"supervisor": "systemd", "launch_supervisor": "systemd"}, "systemd"),+ ({"supervisor": "manual"}, "manual"), # bare control socket, no runtime mapping+ ({"supervisor": "launchd"}, "launchd"), # a gateway from before launch_supervisor+ ({"supervisor": "none"}, None), # ...that mapped manual/desktop: unknown+ ({}, None), ({"supervisor": ""}, None), ({"launch_supervisor": 7, "supervisor": "none"}, None),+])+def test_launch_supervisor(identity, expected):+ assert control_socket.launch_supervisor(identity) == expected+++def test_identify_payload_carries_the_launch_supervisor(monkeypatch):+ monkeypatch.setattr(control_socket, "_detect_supervisor", lambda: "desktop")+ payload = control_socket.build_identify_payload()+ assert payload["supervisor"] == payload["launch_supervisor"] == "desktop"++[email protected]("identity, argv, external", [+ (MANUAL, PLAIN_ARGV, False),+ ({**MANUAL, "launch_supervisor": "desktop"}, PLAIN_ARGV, True),+ ({**MANUAL, "launch_supervisor": "external"}, PLAIN_ARGV, True),+ ({"pid": 4321, "supervisor": "none"}, PLAIN_ARGV, False),+ ({"pid": 4321, "supervisor": "none"}, SUPERVISED_ARGV, True),+ ({**MANUAL, "pid": 999}, PLAIN_ARGV, False), # another process's answer proves nothing+])+def test_declares_external_supervisor(monkeypatch, tmp_path, identity, argv, external):+ monkeypatch.setattr(control_socket, "identify_gateway", lambda home, **k: identity)+ monkeypatch.setattr(gw, "_capture_gateway_argv", lambda pid: argv)+ assert supervised.gateway_declares_external_supervisor(4321, home=tmp_path) is external+++def test_restart_of_a_manual_gateway_stops_it_and_runs_a_new_one(monkeypatch):+ calls = {"sigusr1": False, "stopped": False, "started": False}+ monkeypatch.setattr(gw, "_refuse_from_inside_gateway", lambda *a, **k: None)+ monkeypatch.setattr(gw, "_guard_named_profile_under_multiplexer", lambda **k: None)+ monkeypatch.setattr(gw, "_dispatch_via_service_manager_if_s6", lambda *a, **k: False)+ monkeypatch.setattr(gw, "_installed_service_kind_for", lambda windows: None)+ monkeypatch.setattr(gateway_status, "get_running_pid", lambda *a, **k: 4321)+ monkeypatch.setattr(gw, "_capture_gateway_argv", lambda pid: PLAIN_ARGV)+ monkeypatch.setattr(control_socket, "identify_gateway", lambda home, **k: MANUAL)+ monkeypatch.setattr(gw, "_graceful_restart_via_sigusr1", lambda *a, **k: calls.__setitem__("sigusr1", True))+ monkeypatch.setattr(gw, "stop_profile_gateway", lambda: calls.__setitem__("stopped", True) or True)+ monkeypatch.setattr(gw, "_wait_for_gateway_exit", lambda **k: None)+ monkeypatch.setattr(gw, "_wait_for_api_server_port_free", lambda *a, **k: None)+ monkeypatch.setattr(gw, "run_gateway", lambda **k: calls.__setitem__("started", True))+ monkeypatch.setattr("hermes_cli.main_dashboard._get_systemd_service_for_pid", lambda pid: None)++ gw._cmd_restart(SimpleNamespace(system=False, all=False, force=False))++ assert calls == {"sigusr1": False, "stopped": True, "started": True}+++class _PastOwnerCheck(Exception):+ pass++[email protected]("identity, refusal", [+ (MANUAL, None),+ ({**MANUAL, "launch_supervisor": "desktop"}, "desktop gateway still owns"),+ ({"pid": 4321, "supervisor": "none"}, "unknown gateway still owns"),+])+def test_profile_data_cleanup_drains_only_a_manual_gateway(monkeypatch, tmp_path, identity, refusal):+ from hermes_cli.data_cleanup_holders import _drain_manual_gateway++ home = Path(tmp_path).resolve()+ answer = {**identity, "hermes_home": str(home), "start_time": 111}+ monkeypatch.setattr(control_socket, "identify_gateway", lambda h, **k: answer)++ def pause(h):+ raise _PastOwnerCheck+ monkeypatch.setattr(control_socket, "pause_gateway_for_update", pause)+ monkeypatch.setattr(gateway_status, "get_process_start_time", lambda pid: 111)+ if refusal is None:+ with pytest.raises(_PastOwnerCheck):+ _drain_manual_gateway(home)+ else:+ with pytest.raises(RuntimeError, match=refusal):+ _drain_manual_gateway(home)++[email protected]("record, expected", [+ ({**MANUAL, "launch_supervisor": "desktop"}, "desktop"),+ ({"pid": 4321, "supervisor": "none"}, "manual"), # unknown: the outside-in classifier decides+])+def test_update_inventory_records_the_launch_supervisor(monkeypatch, tmp_path, record, expected):+ from hermes_cli import update_inventory, update_receipt++ monkeypatch.setattr(update_inventory, "_supervisor_classifier", lambda: lambda pid: "manual")+ monkeypatch.setattr(update_receipt, "_socket_identity", lambda home: (4321, record))+ monkeypatch.setattr(gw, "find_profile_gateway_processes", lambda *a, **k: [])+ plan = update_inventory.UpdatePlan()+ update_inventory._collect_gateway_runtimes(plan, [("default", tmp_path)], set())+ assert [runtime.supervisor for runtime in plan.runtimes] == [expected]