The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): BSD-compatible ps flags and all-profile launchd pid discovery (#74075)
Tranquil-Flowd8047c303b1a
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex 1181b55da9f..4f3301811d7 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -98,17 +98,25 @@ class ProfileGatewayProcess:pid: int-def _get_service_pids() -> set:+def _get_service_pids(all_profiles: bool = False) -> set:"""Return PIDs currently managed by systemd or launchd gateway services.Used to avoid killing freshly-restarted service processes when sweeping- for stale manual gateway processes after a service restart. Relies on the- service manager having committed the new PID before the restart command+ for stale manual gateway processes after a service restart. Relies on+ the service manager having committed the new PID before the restart commandreturns (true for both systemd and launchd in practice).++ ``all_profiles`` widens the launchd branch to every installed+ ``ai.hermes.gateway*`` agent — the update path needs the whole fleet+ excluded from its sweep so sibling-profile launchd gateways found by the+ ps scan aren't misclassified as manual processes (#73626). Default-scope+ callers (``gateway status``, cron checks) keep seeing only the current+ profile's service."""pids: set = set()# --- systemd (Linux): user and system scopes ---+ # systemd always lists every hermes-gateway* unit regardless of scope.if supports_systemd_services():for scope_args in [["systemctl", "--user"], ["systemctl"]]:try:@@ -148,30 +156,55 @@ def _get_service_pids() -> set:# --- launchd (macOS) ---if is_macos():try:- label = get_launchd_label()- result = subprocess.run(- ["launchctl", "list", label],- capture_output=True,- text=True, encoding='utf-8', errors='replace',- timeout=5,- )- if result.returncode == 0:- # Try plist format first (macOS 26+): "PID" = <N>;- pid = _parse_launchd_pid_from_list_output(result.stdout)- if pid is not None and pid > 0:- pids.add(pid)- else:- # Fall back to legacy tab-separated format:- # "PID\tStatus\tLabel"+ if all_profiles:+ # Enumerate every ai.hermes.gateway* agent across profiles+ # so the update sweep's exclude set is complete (#73626).+ # Without this, sibling-profile launchd gateways found by the+ # (now-working) ps scan would be misclassified as manual and+ # killed, racing with KeepAlive → duplicate gateways.+ result = subprocess.run(+ ["launchctl", "list"],+ capture_output=True,+ text=True, encoding='utf-8', errors='replace',+ timeout=5,+ )+ if result.returncode == 0:for line in result.stdout.strip().splitlines():parts = line.split()- if len(parts) >= 3 and parts[2] == label:+ if len(parts) >= 3 and parts[-1].startswith(+ "ai.hermes.gateway"+ ):try:pid = int(parts[0])if pid > 0:pids.add(pid)except ValueError:pass+ else:+ label = get_launchd_label()+ result = subprocess.run(+ ["launchctl", "list", label],+ capture_output=True,+ text=True, encoding='utf-8', errors='replace',+ timeout=5,+ )+ if result.returncode == 0:+ # Try plist format first (macOS 26+): "PID" = <N>;+ pid = _parse_launchd_pid_from_list_output(result.stdout)+ if pid is not None and pid > 0:+ pids.add(pid)+ else:+ # Fall back to legacy tab-separated format:+ # "PID\tStatus\tLabel"+ for line in result.stdout.strip().splitlines():+ parts = line.split()+ if len(parts) >= 3 and parts[2] == label:+ try:+ pid = int(parts[0])+ if pid > 0:+ pids.add(pid)+ except ValueError:+ passexcept (FileNotFoundError, subprocess.TimeoutExpired):pass@@ -626,7 +659,13 @@ def _scan_gateway_pids(if not _found_via_proc:result = subprocess.run(- ["ps", "-A", "eww", "-o", "pid=,command="],+ # ``-Aww`` (not ``-A eww``): the BSD ``e`` flag (show+ # environment) is illegal on macOS/BSD ps and makes the+ # whole command fail with rc 1, silently returning [] on+ # every macOS machine (#73626). The matcher only needs+ # argv, not env vars, so ``e`` is unnecessary. ``-ww``+ # keeps unlimited-width output on both BSD and procps ps.+ ["ps", "-Aww", "-o", "pid=,command="],capture_output=True,text=True, encoding='utf-8', errors='replace',timeout=10,@@ -734,7 +773,7 @@ def find_gateway_pids(_append_unique_pid(pids, get_running_pid(), _exclude)except Exception:pass- for pid in _get_service_pids():+ for pid in _get_service_pids(all_profiles=all_profiles):_append_unique_pid(pids, pid, _exclude)try:include_restart_managers = not supports_systemd_services()diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 52cbefda443..3cf74ff1b08 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -6996,7 +6996,7 @@ def _cmd_update_impl(args, gateway_mode: bool):# Kill any remaining gateway processes not managed by a service.# Exclude PIDs that belong to just-restarted services so we don't# immediately kill the process that systemd/launchd just spawned.- service_pids = _get_service_pids()+ service_pids = _get_service_pids(all_profiles=True)manual_pids = find_gateway_pids(exclude_pids=service_pids, all_profiles=True)@@ -7149,7 +7149,7 @@ def _cmd_update_impl(args, gateway_mode: bool):# manager can relaunch with fresh code.try:_time.sleep(3.0)- _service_pids_after = _get_service_pids()+ _service_pids_after = _get_service_pids(all_profiles=True)_surviving = find_gateway_pids(exclude_pids=_service_pids_after,all_profiles=True,diff --git a/tests/hermes_cli/test_gateway_proc_fallback.py b/tests/hermes_cli/test_gateway_proc_fallback.pyindex 7872ec2b464..c2f44796502 100644--- a/tests/hermes_cli/test_gateway_proc_fallback.py+++ b/tests/hermes_cli/test_gateway_proc_fallback.py@@ -112,3 +112,191 @@ class TestProcFallback:# PermissionError swallowed — empty result, no crashassert 12345 not in pidsmock_ps.assert_not_called() # /proc dir existed, so ps not called+++class TestPsFallbackBsdCompat:+ """Verify the ps fallback command uses BSD/macOS-compatible flags.++ The old ``ps -A eww`` command fails on macOS/BSD because the BSD ``e``+ flag (show environment) is not valid there. The fix replaces it with+ ``ps -Aww`` which works on both BSD and procps ps.+ """++ def test_ps_flags_are_bsd_compatible(self):+ """ps is called with ``-Aww``, not ``-A eww``."""+ with (+ patch("hermes_cli.gateway.is_windows", return_value=False),+ patch("os.path.isdir", side_effect=lambda p: p != "/proc"),+ patch("hermes_cli.gateway._get_ancestor_pids", return_value=set()),+ patch("subprocess.run") as mock_run,+ ):+ # Return a failing rc=1 so the scan finishes quickly.+ mock_run.return_value = MagicMock(+ returncode=1, stdout="", stderr=""+ )+ pids = gateway_mod._scan_gateway_pids(set())++ assert not pids # rc=1 → empty result+ # Find the ps call among all subprocess.run invocations+ ps_call = None+ for call_args in mock_run.call_args_list:+ args = call_args[0][0] if call_args[0] else []+ if args and args[0] == "ps":+ ps_call = args+ break+ assert ps_call is not None, "ps was not invoked at all"+ assert "-Aww" in ps_call, (+ f"Expected ps -Aww, got: {ps_call}"+ )+ assert "eww" not in " ".join(ps_call), (+ f"ps eww flag still present: {ps_call}"+ )++ def test_ps_command_includes_pid_and_command_columns(self):+ """The ps command requests ``pid=,command=`` output columns."""+ with (+ patch("hermes_cli.gateway.is_windows", return_value=False),+ patch("os.path.isdir", side_effect=lambda p: p != "/proc"),+ patch("hermes_cli.gateway._get_ancestor_pids", return_value=set()),+ patch("subprocess.run") as mock_run,+ ):+ mock_run.return_value = MagicMock(+ returncode=0, stdout=" 123 gateway run\n", stderr=""+ )+ gateway_mod._scan_gateway_pids(set())++ ps_call = None+ for call_args in mock_run.call_args_list:+ args = call_args[0][0] if call_args[0] else []+ if args and args[0] == "ps":+ ps_call = args+ break+ assert ps_call is not None+ assert "-o" in ps_call and "pid=,command=" in ps_call, (+ f"Missing -o pid=,command= in: {ps_call}"+ )+++class TestGetServicePidsAllProfiles:+ """_get_service_pids(all_profiles=...) discovery across profiles."""++ def test_default_scope_uses_current_profile_label(self):+ """Without all_profiles, only the current profile's launchd agent is+ queried (``launchctl list <label>``)."""+ with (+ patch("hermes_cli.gateway.is_macos", return_value=True),+ patch("hermes_cli.gateway.supports_systemd_services", return_value=False),+ patch(+ "hermes_cli.gateway.get_launchd_label",+ return_value="ai.hermes.gateway.myprofile",+ ),+ patch("subprocess.run") as mock_run,+ ):+ mock_run.return_value = MagicMock(+ returncode=0, stdout="123\t0\tai.hermes.gateway.myprofile", stderr=""+ )+ pids = gateway_mod._get_service_pids()++ assert pids == {123}+ # Must have used ``launchctl list <label>``, not bare ``launchctl list``+ launchctl_calls = [+ c[0][0]+ for c in mock_run.call_args_list+ if c[0] and c[0][0] and c[0][0][0] == "launchctl"+ ]+ assert len(launchctl_calls) == 1+ assert launchctl_calls[0][1] == "list"+ assert launchctl_calls[0][2] == "ai.hermes.gateway.myprofile"++ def test_all_profiles_enumerates_all_gateway_labels(self):+ """With all_profiles=True, ``launchctl list`` is called without a label+ filter, and every row whose last column starts with ``ai.hermes.gateway``+ is collected."""+ with (+ patch("hermes_cli.gateway.is_macos", return_value=True),+ patch("hermes_cli.gateway.supports_systemd_services", return_value=False),+ patch("subprocess.run") as mock_run,+ ):+ mock_run.return_value = MagicMock(+ returncode=0,+ stdout=(+ "123\t0\tai.hermes.gateway.profile-a\n"+ "456\t0\tai.hermes.gateway.profile-b\n"+ "789\t0\tcom.apple.some.other.agent\n"+ ),+ stderr="",+ )+ pids = gateway_mod._get_service_pids(all_profiles=True)++ assert pids == {123, 456}+ # The non-gateway label (789) must NOT be included.+ assert 789 not in pids+ # Must have used bare ``launchctl list``+ launchctl_calls = [+ c[0][0]+ for c in mock_run.call_args_list+ if c[0] and c[0][0] and c[0][0][0] == "launchctl"+ ]+ assert len(launchctl_calls) == 1+ assert launchctl_calls[0] == ["launchctl", "list"]++ def test_all_profiles_empty_when_no_gateway_labels(self):+ """When no ai.hermes.gateway* labels exist, all_profiles returns empty."""+ with (+ patch("hermes_cli.gateway.is_macos", return_value=True),+ patch("hermes_cli.gateway.supports_systemd_services", return_value=False),+ patch("subprocess.run") as mock_run,+ ):+ mock_run.return_value = MagicMock(+ returncode=0,+ stdout="789\t0\tcom.apple.some.other.agent\n",+ stderr="",+ )+ pids = gateway_mod._get_service_pids(all_profiles=True)++ assert pids == set()++ def test_all_profiles_handles_broken_pid_column(self):+ """Non-integer PID entries are silently skipped."""+ with (+ patch("hermes_cli.gateway.is_macos", return_value=True),+ patch("hermes_cli.gateway.supports_systemd_services", return_value=False),+ patch("subprocess.run") as mock_run,+ ):+ mock_run.return_value = MagicMock(+ returncode=0,+ stdout=(+ "-\t0\tai.hermes.gateway.broken\n"+ " 123 \t0\tai.hermes.gateway.ok\n"+ ),+ stderr="",+ )+ pids = gateway_mod._get_service_pids(all_profiles=True)++ assert pids == {123}++ def test_all_profiles_preserves_systemd_behavior(self):+ """systemd scope is unaffected by the all_profiles switch — it already+ lists every hermes-gateway* unit unconditionally."""+ with (+ patch("hermes_cli.gateway.is_macos", return_value=False),+ patch("hermes_cli.gateway.supports_systemd_services", return_value=True),+ patch("subprocess.run") as mock_run,+ ):+ def _run_side_effect(args, **kwargs):+ args_list = list(args) if args else []+ cmd_str = " ".join(str(a) for a in args_list[:4])+ if "list-units" in cmd_str:+ return MagicMock(+ returncode=0,+ stdout="hermes-gateway-jarvis.service loaded active running\n",+ stderr="",+ )+ if "show" in cmd_str and "MainPID" in cmd_str:+ return MagicMock(returncode=0, stdout="123\n", stderr="")+ return MagicMock(returncode=0, stdout="", stderr="")++ mock_run.side_effect = _run_side_effect+ pids = gateway_mod._get_service_pids(all_profiles=True)++ assert pids == {123}