Skip to content

The agent that grows with you

fix(update): restart this install's legacy hash-suffixed launchd gateways

liuhao10247c295a8e97f9
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 7e3b20ada26..b821bf57f92 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -2775,6 +2775,79 @@ def launchd_gateway_labels_for_install() -> list[str]:
return root_label + sorted(profile_labels)
+def legacy_launchd_labels_for_install(exclude=()) -> list[str]:
+ """Launchd labels of THIS install that the profile-layout derivation can't map (#115254).
+
+ A unit whose label predates the profile-name suffix scheme (``ai.hermes.gateway-<8hex>`` from the
+ historical hash suffix) is invisible to ``launchd_gateway_labels_for_install()`` and therefore to
+ the update restart pass. This scans the account's LaunchAgents for such plists and credits one
+ only when attribution to THIS install is provable — see ``_launchd_plist_belongs_to_install`` —
+ so the derivation's boundary holds: a sandboxed HERMES_HOME never restarts another install's
+ fleet (#41403).
+ """
+ import plistlib
+ import pwd
+
+ try:
+ home = Path(pwd.getpwuid(os.getuid()).pw_dir) # windows-footgun: ok — POSIX launchd (macOS) helper, never invoked on Windows
+ except Exception:
+ return []
+ agents_dir = home / "Library" / "LaunchAgents"
+ if not agents_dir.is_dir():
+ return []
+ try:
+ venv = _detect_venv_dir()
+ venv = venv.resolve() if venv else None
+ except OSError:
+ venv = None
+ excluded = set(exclude)
+ labels: set[str] = set()
+ for plist_path in sorted(agents_dir.glob("ai.hermes.gateway*.plist")):
+ try:
+ data = plistlib.loads(plist_path.read_bytes())
+ except Exception:
+ continue # unreadable/malformed plist: attribution can't be proven — fail closed
+ label = data.get("Label") if isinstance(data, dict) else None
+ if not isinstance(label, str) or label in excluded or not label.startswith("ai.hermes.gateway"):
+ continue
+ if _launchd_plist_belongs_to_install(data, venv):
+ labels.add(label)
+ return sorted(labels)
+
+
+def _launchd_plist_belongs_to_install(data: dict, venv: Path | None) -> bool:
+ """Whether a launchd gateway plist is a unit of THIS install.
+
+ Two provable anchors, either suffices: the ProgramArguments run this install's venv python
+ (the pull is shared across the install's profiles, so every unit of this install points there),
+ or the pinned ``HERMES_HOME`` is one of this install's homes (a native service home or a home
+ under this root's ``profiles/`` tree). Anything else — including a plist whose anchors can't be
+ read — belongs to another install and must stay untouched.
+ """
+ argv = data.get("ProgramArguments")
+ if venv is not None and isinstance(argv, list) and argv:
+ try:
+ if Path(str(argv[0])).resolve().parent.parent == venv:
+ return True
+ except OSError:
+ pass
+ env_home = (data.get("EnvironmentVariables") or {}).get("HERMES_HOME")
+ if not env_home:
+ return False
+ try:
+ resolved = Path(str(env_home)).expanduser().resolve()
+ except (OSError, RuntimeError):
+ return False
+ if resolved in _native_service_homes():
+ return True
+ from hermes_constants import get_default_hermes_root
+ try:
+ rel = resolved.relative_to(get_default_hermes_root().resolve()).parts
+ except ValueError:
+ return False
+ return not rel or (len(rel) == 2 and rel[0] == "profiles")
+
+
def _detect_venv_dir() -> Path | None:
"""Active virtualenv dir: ``sys.prefix``, then ``VIRTUAL_ENV`` (uv sets it without changing
sys.prefix), then .venv/venv under PROJECT_ROOT; None if none found."""
diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.py
index a38df7074f0..c97e0dc2109 100644
--- a/hermes_cli/update_cmd_fleet.py
+++ b/hermes_cli/update_cmd_fleet.py
@@ -792,7 +792,8 @@ def _restart_macos_launchd_gateways(
cannot leave the rest of the fleet on old code (#68523).
"""
from hermes_cli.gateway import (
- get_launchd_label, get_launchd_plist_path, launchd_gateway_labels_for_install, _graceful_restart_via_sigusr1, _launchd_kickstart,
+ get_launchd_label, get_launchd_plist_path, launchd_gateway_labels_for_install, legacy_launchd_labels_for_install,
+ _graceful_restart_via_sigusr1, _launchd_kickstart,
_locate_launchd_gateway_service, _wait_for_launchd_service_pid,
)
if require_supervision:
@@ -805,7 +806,15 @@ def _restart_macos_launchd_gateways(
failed_or_stale_units.extend(_failed)
current_label = get_launchd_label()
- for label in launchd_gateway_labels_for_install():
+ derived_labels = launchd_gateway_labels_for_install()
+ # Units labelled before the profile-name suffix scheme (ai.hermes.gateway-<hash>) are invisible
+ # to the derivation; legacy_launchd_labels_for_install() credits one only when its plist is
+ # provably this install's, so the #41403 boundary (never touch another install's fleet) holds.
+ # See #115254.
+ legacy_labels = legacy_launchd_labels_for_install(exclude=set(derived_labels) | {current_label})
+ if legacy_labels:
+ print(f" ↻ legacy-labelled units of this install join the restart: {', '.join(legacy_labels)}")
+ for label in derived_labels + legacy_labels:
if label == current_label:
continue
try:
diff --git a/tests/hermes_cli/test_update_launchd_fleet_restart.py b/tests/hermes_cli/test_update_launchd_fleet_restart.py
index 2f96f613384..9ca6a9bd86a 100644
--- a/tests/hermes_cli/test_update_launchd_fleet_restart.py
+++ b/tests/hermes_cli/test_update_launchd_fleet_restart.py
@@ -22,6 +22,7 @@ from __future__ import annotations
import subprocess
import sys
+from pathlib import Path
import pytest
@@ -245,7 +246,7 @@ class TestGetServicePidsScoping:
def _fleet(monkeypatch, tmp_path, *, current, labels, located,
registered=None, plist_exists=True,
drain_results=None, kick_errors=None, wait_results=None,
- current_supervised=True):
+ current_supervised=True, legacy_labels=()):
"""Wire a fake launchd fleet through hermes_cli.gateway seams.
``located`` maps label -> (domain, pid) as ``_locate_launchd_gateway_service``
@@ -287,6 +288,9 @@ def _fleet(monkeypatch, tmp_path, *, current, labels, located,
monkeypatch.setattr(gw, "get_launchd_label", lambda: current)
monkeypatch.setattr(gw, "get_launchd_plist_path", lambda: plist)
monkeypatch.setattr(gw, "launchd_gateway_labels_for_install", lambda: list(labels))
+ monkeypatch.setattr(
+ gw, "legacy_launchd_labels_for_install", lambda exclude=(): list(legacy_labels)
+ )
monkeypatch.setattr(gw, "_locate_launchd_gateway_service", fake_locate)
monkeypatch.setattr(gw, "_launchd_service_registered", fake_registered)
monkeypatch.setattr(
@@ -613,6 +617,134 @@ class TestRestartMacosLaunchdGateways:
assert failed == ["ai.hermes.gateway-zombie"]
+def _write_launchd_plist(agents_dir: Path, label: str, *, argv=(), hermes_home=None, raw=None):
+ """One gateway LaunchAgent plist under a fake account's LaunchAgents dir."""
+ import plistlib
+
+ agents_dir.mkdir(parents=True, exist_ok=True)
+ path = agents_dir / f"{label}.plist"
+ if raw is not None:
+ path.write_text(raw)
+ return path
+ data: dict = {"Label": label, "ProgramArguments": list(argv)}
+ if hermes_home is not None:
+ data["EnvironmentVariables"] = {"HERMES_HOME": str(hermes_home)}
+ path.write_bytes(plistlib.dumps(data))
+ return path
+
+
+def _fake_launchd_account(monkeypatch, tmp_path) -> Path:
+ """Point the real-account-home lookup (pwd.getpwuid) at a tmp home; return its LaunchAgents dir."""
+ import pwd as pwd_module
+ from types import SimpleNamespace
+
+ monkeypatch.setattr(
+ pwd_module, "getpwuid", lambda _uid: SimpleNamespace(pw_dir=str(tmp_path))
+ )
+ return tmp_path / "Library" / "LaunchAgents"
+
+
+class TestLegacyLaunchdLabelsForInstall:
+ """#115254 — hash-suffixed labels of THIS install join the restart pass;
+ attribution is fail-closed so another install's fleet stays untouched."""
+
+ def test_hash_suffixed_unit_running_this_installs_venv_is_credited(self, monkeypatch, tmp_path):
+ agents = _fake_launchd_account(monkeypatch, tmp_path)
+ venv = tmp_path / "install" / ".venv"
+ monkeypatch.setattr(gw, "_detect_venv_dir", lambda: venv)
+ _write_launchd_plist(
+ agents, "ai.hermes.gateway-398559f7",
+ argv=[str(venv / "bin" / "python"), "-m", "hermes_cli.stderr_timestamp"],
+ hermes_home=tmp_path / "elsewhere", # venv anchor alone must suffice
+ )
+ assert gw.legacy_launchd_labels_for_install() == ["ai.hermes.gateway-398559f7"]
+
+ def test_unit_pinning_this_installs_profile_home_is_credited(self, monkeypatch, tmp_path):
+ agents = _fake_launchd_account(monkeypatch, tmp_path)
+ root = tmp_path / "hermes-root"
+ monkeypatch.setattr(gw, "_detect_venv_dir", lambda: None)
+ monkeypatch.setattr(gw, "_native_service_homes", lambda: set())
+ import hermes_constants
+ monkeypatch.setattr(hermes_constants, "get_default_hermes_root", lambda: root)
+ _write_launchd_plist(
+ agents, "ai.hermes.gateway-gopod",
+ argv=[], hermes_home=root / "profiles" / "gopod",
+ )
+ assert gw.legacy_launchd_labels_for_install() == ["ai.hermes.gateway-gopod"]
+
+ def test_another_installs_unit_is_never_credited(self, monkeypatch, tmp_path):
+ """The #41403 boundary: a sandboxed HERMES_HOME must not restart (or
+ even enumerate) a sibling install's units — neither anchor matches."""
+ agents = _fake_launchd_account(monkeypatch, tmp_path)
+ venv = tmp_path / "this-install" / ".venv"
+ monkeypatch.setattr(gw, "_detect_venv_dir", lambda: venv)
+ monkeypatch.setattr(gw, "_native_service_homes", lambda: set())
+ import hermes_constants
+ monkeypatch.setattr(hermes_constants, "get_default_hermes_root", lambda: tmp_path / "this-root")
+ _write_launchd_plist(
+ agents, "ai.hermes.gateway-5db8084b",
+ argv=[str(tmp_path / "other-install" / ".venv" / "bin" / "python")],
+ hermes_home=tmp_path / "other-root" / "profiles" / "gopod",
+ )
+ assert gw.legacy_launchd_labels_for_install() == []
+
+ def test_malformed_plist_is_skipped_fail_closed(self, monkeypatch, tmp_path):
+ agents = _fake_launchd_account(monkeypatch, tmp_path)
+ monkeypatch.setattr(gw, "_detect_venv_dir", lambda: None)
+ _write_launchd_plist(agents, "ai.hermes.gateway-broken", raw="not a plist at all")
+ assert gw.legacy_launchd_labels_for_install() == []
+
+ def test_exclude_hides_derived_and_current_labels(self, monkeypatch, tmp_path):
+ agents = _fake_launchd_account(monkeypatch, tmp_path)
+ venv = tmp_path / "install" / ".venv"
+ monkeypatch.setattr(gw, "_detect_venv_dir", lambda: venv)
+ _write_launchd_plist(agents, "ai.hermes.gateway-398559f7", argv=[str(venv / "bin" / "python")])
+ _write_launchd_plist(agents, "ai.hermes.gateway-gopod", argv=[str(venv / "bin" / "python")])
+ assert gw.legacy_launchd_labels_for_install(
+ exclude={"ai.hermes.gateway-gopod", "ai.hermes.gateway"}
+ ) == ["ai.hermes.gateway-398559f7"]
+
+ def test_missing_agents_dir_means_no_legacy_units(self, monkeypatch, tmp_path):
+ _fake_launchd_account(monkeypatch, tmp_path) # home exists; LaunchAgents does not
+ monkeypatch.setattr(gw, "_detect_venv_dir", lambda: None)
+ assert gw.legacy_launchd_labels_for_install() == []
+
+
+class TestRestartMacosLaunchdGatewaysLegacyUnits:
+ def test_legacy_labelled_sibling_is_restarted_like_any_other(self, monkeypatch, tmp_path, capsys):
+ """The update restart pass iterates the derivation PLUS the install's
+ legacy-labelled units (#115254): the hash-suffixed sibling is drained,
+ kickstarted and verified in its own domain."""
+ current = "ai.hermes.gateway"
+ legacy = "ai.hermes.gateway-398559f7"
+ rec = _fleet(
+ monkeypatch,
+ tmp_path,
+ current=current,
+ labels=[current, "ai.hermes.gateway-gopod"],
+ legacy_labels=[legacy],
+ located={
+ current: (f"gui/{UID}", 100),
+ "ai.hermes.gateway-gopod": (f"gui/{UID}", 200),
+ legacy: (f"user/{UID}", 300),
+ },
+ )
+ restarted: list[str] = []
+ failed: list[str] = []
+
+ _restart_macos_launchd_gateways(restarted, failed, drain_budget=0.0)
+
+ assert rec.kickstarts == [
+ f"gui/{UID}/ai.hermes.gateway-gopod",
+ f"user/{UID}/{legacy}",
+ ]
+ assert restarted == [current, "ai.hermes.gateway-gopod", legacy]
+ assert failed == []
+ assert set(rec.drains) == {200, 300}
+ out = capsys.readouterr().out
+ assert legacy in out # the join is announced, not silent
+
+
class TestWaitForLaunchdServicePid:
def test_returns_true_once_pid_changes(self, monkeypatch):
pids = iter([200, 200, 4242])