Skip to content

The agent that grows with you

fix: credit legacy launchd units by pinned HERMES_HOME only

teknium1ccb5aedad875
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index b821bf57f92..6d3746f4090 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -2780,74 +2780,42 @@ def legacy_launchd_labels_for_install(exclude=()) -> list[str]:
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).
+ the update restart pass. This reads the account's LaunchAgents and credits a plist only when its
+ pinned ``HERMES_HOME`` is this install's root or one of its ``profiles/<name>`` homes — ownership
+ judged from the plist's content, never from label shape or directory membership — so the
+ derivation's boundary holds: a sandboxed HERMES_HOME (tests, side-by-side installs) never
+ enumerates, let alone restarts, another install's fleet (#41403).
"""
import plistlib
import pwd
+ from hermes_constants import get_default_hermes_root
+
try:
home = Path(pwd.getpwuid(os.getuid()).pw_dir) # windows-footgun: ok — POSIX launchd (macOS) helper, never invoked on Windows
+ root = get_default_hermes_root().resolve()
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())
+ label = data["Label"]
+ pinned = Path(str(data["EnvironmentVariables"]["HERMES_HOME"])).expanduser().resolve()
+ rel = pinned.relative_to(root).parts
except Exception:
- continue # unreadable/malformed plist: attribution can't be proven — fail closed
- label = data.get("Label") if isinstance(data, dict) else None
+ continue # unreadable plist, no pinned home, or a home outside this root: not ours — fail closed
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):
+ if not rel or (len(rel) == 2 and rel[0] == "profiles"):
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/tests/hermes_cli/test_update_launchd_fleet_restart.py b/tests/hermes_cli/test_update_launchd_fleet_restart.py
index 9ca6a9bd86a..85fba9dcb62 100644
--- a/tests/hermes_cli/test_update_launchd_fleet_restart.py
+++ b/tests/hermes_cli/test_update_launchd_fleet_restart.py
@@ -645,69 +645,26 @@ def _fake_launchd_account(monkeypatch, tmp_path) -> Path:
class TestLegacyLaunchdLabelsForInstall:
- """#115254 — hash-suffixed labels of THIS install join the restart pass;
- attribution is fail-closed so another install's fleet stays untouched."""
+ """#115254 — hash-suffixed labels of THIS install join the restart pass; ownership is judged
+ from the plist's pinned HERMES_HOME, fail-closed, so another install's fleet stays untouched
+ (the #41403 boundary) and a sandboxed HERMES_HOME never enumerates the account's real units."""
- 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):
+ def test_only_units_pinned_to_this_installs_homes_are_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)
+ venv_python = str(root.parent / "install" / ".venv" / "bin" / "python")
+ _write_launchd_plist(agents, "ai.hermes.gateway-398559f7", argv=[venv_python], hermes_home=root / "profiles" / "gopod")
+ _write_launchd_plist(agents, "ai.hermes.gateway-1a2b3c4d", argv=[venv_python], hermes_home=root)
+ _write_launchd_plist(agents, "ai.hermes.gateway-gopod", argv=[venv_python], hermes_home=root / "profiles" / "gopod")
+ # Another install's unit: same venv on disk, but its home lives under a different root.
+ _write_launchd_plist(agents, "ai.hermes.gateway-5db8084b", argv=[venv_python], hermes_home=tmp_path / "other-root" / "profiles" / "gopod")
+ _write_launchd_plist(agents, "ai.hermes.gateway-nohome", argv=[venv_python]) # no pinned home: unattributable
_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() == []
+ assert gw.legacy_launchd_labels_for_install(exclude={"ai.hermes.gateway-gopod", "ai.hermes.gateway"}) == [
+ "ai.hermes.gateway-1a2b3c4d", "ai.hermes.gateway-398559f7",
+ ]
class TestRestartMacosLaunchdGatewaysLegacyUnits: