The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: hermes update restarts only the gateways of the home it updates (#93349)
teknium1c500dc6d99e9
diff --git a/hermes_cli/AGENTS.md b/hermes_cli/AGENTS.mdindex 421af5da92e..32e557dbac4 100644--- a/hermes_cli/AGENTS.md+++ b/hermes_cli/AGENTS.md@@ -152,10 +152,15 @@ it guards. `plan → snapshot → apply → restart-per-kind → verify → reponone of them; without the graft the swap deletes them). Post-swap, the Desktoprebuild decision also trusts the build stamp under HERMES_HOME, so an install that already lostits artifacts in an earlier update is rebuilt instead of "forgotten" (#90495).-- **Restart-per-kind**: systemd and launchd restarts are FLEET-WIDE (every `hermes-gateway*` unit /- `ai.hermes.gateway*` LaunchAgent), drain-first (SIGUSR1), with per-unit/per-label failure- isolation. Restarting only the invoking profile's service leaves siblings on stale `sys.modules`- until they crash — the largest dupe-PR cluster in the repo's history came from that bug.+- **Restart-per-kind**: systemd and launchd restarts are FLEET-WIDE within the updating install (every+ `hermes-gateway*` unit / `ai.hermes.gateway*` LaunchAgent whose home is the updating root or one of its+ `profiles/<name>`), drain-first (SIGUSR1), with per-unit/per-label failure isolation. Restarting only the+ invoking profile's service leaves siblings on stale `sys.modules` until they crash — the largest dupe-PR+ cluster in the repo's history came from that bug. The fleet is bounded by HOME, not by namespace:+ `hermes_cli/update_fleet_scope.py` judges every unit/label/process by the home it actually runs on+ (live environ, unit `Environment=`, plist `HERMES_HOME`), and a runtime of another `HERMES_HOME` on the+ same account — a sibling install, the real `hermes-gateway.service` seen from a scratch home — is named and+ left alone, never restarted (#93349).- **Verify**: gateways stamp `code_sha`/`code_version` into `gateway_state.json` on everyruntime-status write (`gateway/status.py`); the updater compares each live gateway against thefresh checkout and prints a fleet version matrix. A provably-stale gateway fails the updatediff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.pyindex 60f0f6df6ae..e0ddca4d60a 100644--- a/hermes_cli/update_cmd_fleet.py+++ b/hermes_cli/update_cmd_fleet.py@@ -581,6 +581,8 @@ def _restart_systemd_gateway_units_best_effort(failed: list, listings) -> None:for key in keys:scope, scope_cmd, svc_name = targets[key]+ if not _systemd_unit_owned_by_update(scope_cmd, svc_name):+ continuemanage_cmd = list(scope_cmd) + ["--no-ask-password"]if _needs_sudo(scope):manage_cmd = ["sudo", "-n"] + manage_cmd@@ -867,6 +869,34 @@ def _systemctl_reset_and_restart(manage_cmd: list, svc_name: str, *, scope_cmd:return _systemctl(manage_cmd + ["restart", svc_name], timeout=timeout)+def _systemd_unit_owned_by_update(scope_cmd: list, svc_name: str) -> bool:+ """Gate a unit restart on the unit's home being one this update owns (#93349).++ ``hermes-gateway*`` is an account-wide namespace: a second install's ``hermes update`` used+ to drain and restart the account's real ``hermes-gateway.service`` because the unit was+ listed, not because it ran the updated code. Foreign or unreadable ownership prints a notice+ and leaves the unit alone; it is not a failed restart.+ """+ from hermes_cli.update_fleet_scope import describe_skipped_runtime, systemd_unit_hermes_home, home_in_update_scope+ home = systemd_unit_hermes_home(scope_cmd, svc_name)+ if home is not None and home_in_update_scope(home):+ return True+ print(describe_skipped_runtime("systemd unit", svc_name, home))+ return False+++def _scoped_manual_gateway_pids(pids, *, keep=(), quiet: bool = False) -> list[int]:+ """*pids* whose live home this update owns (plus *keep*, PIDs already mapped to this+ install's profile PID files); every other gateway process is named and left running."""+ from hermes_cli.update_fleet_scope import describe_skipped_runtime, partition_gateway_pids_by_scope+ keep = set(keep)+ owned, foreign = partition_gateway_pids_by_scope([pid for pid in pids if pid not in keep])+ if not quiet:+ for pid, home in foreign:+ print(describe_skipped_runtime("gateway process", f"PID {pid}", home))+ return [pid for pid in pids if pid in keep or pid in owned]++def _is_hermes_gateway_unit(unit: str) -> bool:"""Exact base unit or hyphenated profile family only: ``startswith("hermes-serve")``would accept ``hermes-server.service``."""@@ -1053,9 +1083,15 @@ def _restart_macos_launchd_gateways(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)}")+ from hermes_cli.update_fleet_scope import describe_skipped_runtime, launchd_label_foreign_homefor label in derived_labels + legacy_labels:if label == current_label:continue+ # Labels are account-global: root B's default profile derives the same bare label root A+ # installed. A plist pinning a foreign HERMES_HOME is another install's job (#93349).+ if (foreign_home := launchd_label_foreign_home(label)) is not None:+ print(describe_skipped_runtime("launchd job", label, foreign_home))+ continuetry:# Locate = liveness + domain in one probe; kickstart and fresh-PID checks# reuse that domain so a sibling is never probed in one and restarted in another.@@ -1107,7 +1143,7 @@ def _surviving_gateway_pids_after_failed_restart():"""try:from hermes_cli.gateway import find_gateway_pids- return list(find_gateway_pids(all_profiles=True))+ return _scoped_manual_gateway_pids(find_gateway_pids(all_profiles=True), quiet=True)except Exception as exc: # pragma: no cover - defensivelogger.debug("Could not probe for surviving gateways after update: %s", exc)return None@@ -1335,6 +1371,8 @@ def _restart_one_systemd_gateway_unit(check = _systemctl(scope_cmd + ["is-active", svc_name], timeout=5)if check.stdout.strip() != "active":return+ if not _systemd_unit_owned_by_update(scope_cmd, svc_name):+ return_repair_unit_without_fatal_exit_park(svc_name, scope)# None ⇒ no non-interactive privilege path; avoid manage-units verbs@@ -1541,6 +1579,9 @@ def _restart_manual_gateways(out: _GatewayRestartOutcome, _drain_budget) -> Nonefor proc in find_profile_gateway_processes(exclude_pids=service_pids)if proc.pid in manual_pids}+ # ``all_profiles`` is host-wide: a sibling install's gateway matches too. Only this update's+ # homes are stopped; the profile-mapped PIDs come from this install's own PID files (#93349).+ manual_pids = _scoped_manual_gateway_pids(manual_pids, keep=profile_processes)# Profile gateways we couldn't arm a relaunch for must NOT keep running stale:# the unmapped sweep below stops them and lists them under "Restart manually".# These must NOT be left running: their modules are the pre-update ones and every lazy import from here@@ -1756,7 +1797,7 @@ def _restart_gateway_fleet_after_update(_pre_update_plan, gateway_mode: bool):# Snapshot before any stop/drain so an empty survivor probe reads as "stopped# and never came back", not "nothing was running"; None fails closed.try:- out.pre_restart_gateway_pids = list(find_gateway_pids(all_profiles=True))+ out.pre_restart_gateway_pids = _scoped_manual_gateway_pids(find_gateway_pids(all_profiles=True), quiet=True)except Exception:out.pre_restart_gateway_pids = Nonediff --git a/hermes_cli/update_fleet_scope.py b/hermes_cli/update_fleet_scope.pynew file mode 100644index 00000000000..6c74c5d3e25--- /dev/null+++ b/hermes_cli/update_fleet_scope.py@@ -0,0 +1,148 @@+"""Home scoping for ``hermes update``'s fleet restart (#93349).++The restart phase enumerates ``hermes-gateway*``/``hermes-serve*`` units, ``ai.hermes.gateway*``+LaunchAgents and every ``gateway run`` process on the host. Those are HOST-wide namespaces: a+second Hermes install (another ``HERMES_HOME`` root under the same account, its own checkout and+venv) shares them, and the update used to restart that install's gateway too — including the+account's real ``hermes-gateway.service`` when a scratch home ran ``hermes update``.++The fleet an update owns is the set of homes its plan inventories: the updating root plus every+``<root>/profiles/<name>``. Ownership is judged from what a runtime actually runs on — the live+process environment (``HERMES_HOME``/``HOME``, via ``_hermes_home_for_pid``), the unit's declared+``Environment=`` or the plist's pinned ``HERMES_HOME`` — never from a unit label or an argv+substring. Unknown ownership is left alone: a restart we cannot prove is ours is somebody else's+outage.+"""++from __future__ import annotations++import shlex+from contextlib import suppress+from pathlib import Path+++def _resolved(path) -> Path | None:+ try:+ return Path(str(path)).expanduser().resolve()+ except (OSError, RuntimeError, ValueError):+ return None+++def update_scope_homes() -> set[Path]:+ """Resolved homes the running update owns: the invoking home, the install root and its profiles."""+ homes: set[Path] = set()+ with suppress(Exception):+ from hermes_constants import get_hermes_home+ if (home := _resolved(get_hermes_home())) is not None:+ homes.add(home)+ with suppress(Exception):+ from hermes_cli.update_receipt import _profile_homes+ for _profile, home in _profile_homes():+ if (resolved := _resolved(home)) is not None:+ homes.add(resolved)+ return homes+++def home_in_update_scope(home, scope: set[Path] | None = None) -> bool:+ """True when *home* (a path or string) is one of the homes this update owns."""+ if not home:+ return False+ resolved = _resolved(home)+ if resolved is None:+ return False+ return resolved in (update_scope_homes() if scope is None else scope)+++def gateway_pid_in_update_scope(pid: int, scope: set[Path] | None = None) -> bool | None:+ """Does gateway *pid* run on a home this update owns? ``None`` when its home cannot be read."""+ from hermes_cli.dashboard_procs import _hermes_home_for_pid+ try:+ home = _hermes_home_for_pid(pid)+ except Exception:+ return None+ if home is None:+ return None+ return home_in_update_scope(home, scope)+++def partition_gateway_pids_by_scope(pids, scope: set[Path] | None = None) -> tuple[list[int], list[tuple[int, str | None]]]:+ """``(owned, foreign)`` split of *pids*; ``foreign`` pairs each PID with its home (None = unreadable)."""+ scope = update_scope_homes() if scope is None else scope+ owned: list[int] = []+ foreign: list[tuple[int, str | None]] = []+ for pid in pids:+ verdict = gateway_pid_in_update_scope(pid, scope)+ if verdict:+ owned.append(pid)+ else:+ home = None+ if verdict is False:+ with suppress(Exception):+ from hermes_cli.dashboard_procs import _hermes_home_for_pid+ home = _hermes_home_for_pid(pid)+ foreign.append((pid, home))+ return owned, foreign+++def systemd_unit_hermes_home(scope_cmd: list, svc_name: str) -> str | None:+ """Home the systemd unit *svc_name* runs on: its live MainPID's environment first, then the+ unit's declared ``Environment=HERMES_HOME``; for a user-scope unit that declares none, the+ user's own default home. ``None`` when nothing readable names a home."""+ from hermes_cli.update_cmd_fleet import _systemctl, _unit_main_pid++ pid = _unit_main_pid(scope_cmd, svc_name)+ if pid > 0:+ with suppress(Exception):+ from hermes_cli.dashboard_procs import _hermes_home_for_pid+ if (home := _hermes_home_for_pid(pid)) is not None:+ return home+ try:+ shown = _systemctl(list(scope_cmd) + ["show", svc_name, "--property=Environment", "--value"], timeout=10)+ except Exception:+ return None+ if getattr(shown, "returncode", 1) != 0:+ return None+ env_line = (getattr(shown, "stdout", "") or "").strip()+ try:+ tokens = shlex.split(env_line)+ except ValueError:+ tokens = env_line.split()+ for token in tokens:+ key, sep, value = token.partition("=")+ if sep and key == "HERMES_HOME" and value.strip():+ return value.strip()+ if "--user" in scope_cmd:+ return str(Path.home() / ".hermes")+ return None+++def systemd_unit_in_update_scope(scope_cmd: list, svc_name: str, scope: set[Path] | None = None) -> bool | None:+ """Does unit *svc_name* belong to this update? ``None`` = ownership unreadable (leave it alone)."""+ home = systemd_unit_hermes_home(scope_cmd, svc_name)+ if home is None:+ return None+ return home_in_update_scope(home, scope)+++def launchd_label_foreign_home(label: str, scope: set[Path] | None = None) -> str | None:+ """The HERMES_HOME a derived launchd label's installed plist pins when that home is NOT one of+ this update's — labels are account-global, so root B's default profile derives the same bare+ ``ai.hermes.gateway`` root A installed. ``None`` = ours, or no/unreadable plist (the locate step+ decides whether a job exists; only a proven foreign home is refused)."""+ import plistlib+ with suppress(Exception):+ from hermes_cli.gateway import get_launchd_plist_path+ plist_path = get_launchd_plist_path().with_name(f"{label}.plist")+ if not plist_path.exists():+ return None+ data = plistlib.loads(plist_path.read_bytes())+ pinned = str(data["EnvironmentVariables"]["HERMES_HOME"])+ return None if home_in_update_scope(pinned, scope) else pinned+ return None+++def describe_skipped_runtime(kind: str, name: str, home: str | None) -> str:+ """One notice line for a runtime the update leaves alone (foreign home or unreadable ownership)."""+ if home is None:+ return f" ↷ {name}: {kind} whose Hermes home could not be read — left alone (not restarted)"+ return f" ↷ {name}: {kind} of another Hermes home ({home}) — left alone (not restarted)"diff --git a/tests/hermes_cli/test_update_fleet_home_scope.py b/tests/hermes_cli/test_update_fleet_home_scope.pynew file mode 100644index 00000000000..f8274097e49--- /dev/null+++ b/tests/hermes_cli/test_update_fleet_home_scope.py@@ -0,0 +1,95 @@+"""#93349 — ``hermes update`` restarts only the gateways of the home it is updating.++``hermes-gateway*`` units and ``gateway run`` processes are host-wide namespaces shared by every+Hermes install under the account. A scratch home's update used to drain and restart the account's+real ``hermes-gateway.service`` and SIGTERM sibling installs' gateways because they were listed,+not because they ran the updated code.+"""++from __future__ import annotations++import os+import signal+import subprocess+from pathlib import Path++import pytest++from hermes_cli import update_cmd_fleet as fleet+from hermes_cli import dashboard_procs++FOREIGN_HOME = "/srv/other-account-home/.hermes"+++def own_home(monkeypatch, tmp_path):+ home = tmp_path / "homeA" / ".hermes"+ home.mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(home))+ # The plan inventory is this install only; the fixture home has no profiles dir.+ monkeypatch.setattr("hermes_cli.update_receipt._profile_homes", lambda: [("default", home)])+ return home+++def _pid_homes(monkeypatch, mapping: dict):+ monkeypatch.setattr(dashboard_procs, "_hermes_home_for_pid", lambda pid: mapping.get(pid))+++def test_systemd_unit_of_another_home_is_left_alone(monkeypatch, own_home):+ """user/hermes-gateway runs on another HERMES_HOME → no drain, no restart, not a failure;+ the same unit running on the updating home is still restarted (control)."""+ homes = {4242: FOREIGN_HOME, 4343: str(own_home)}+ _pid_homes(monkeypatch, homes)+ main_pid = {"value": 4242}+ write_verbs: list[list[str]] = []++ def fake_systemctl(cmd, *, timeout):+ if "is-active" in cmd:+ return subprocess.CompletedProcess(cmd, 0, stdout="active\n", stderr="")+ if "show" in cmd and "--property=MainPID" in cmd:+ return subprocess.CompletedProcess(cmd, 0, stdout=f"{main_pid['value']}\n", stderr="")+ if "show" in cmd:+ return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")+ write_verbs.append(cmd)+ return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")++ monkeypatch.setattr(fleet, "_systemctl", fake_systemctl)+ monkeypatch.setattr(fleet, "_repair_unit_without_fatal_exit_park", lambda *a, **k: None)+ drained: list[int] = []+ monkeypatch.setattr(fleet, "_drain_or_signal_gateway_for_update", lambda pid, *a, **k: drained.append(pid) or True)+ monkeypatch.setattr(fleet, "_wait_for_service_active", lambda *a, **k: True)++ restarted: list[str] = []+ failed: list[str] = []+ fleet._restart_one_systemd_gateway_unit(+ "hermes-gateway", scope="user", scope_cmd=["systemctl", "--user"], drain_budget=5.0,+ _manage_cmd_cache={}, restarted_services=restarted, failed_or_stale_units=failed,+ )+ assert drained == [] and write_verbs == [] and restarted == [] and failed == []++ main_pid["value"] = 4343 # control: same unit name, this update's home+ fleet._restart_one_systemd_gateway_unit(+ "hermes-gateway", scope="user", scope_cmd=["systemctl", "--user"], drain_budget=5.0,+ _manage_cmd_cache={}, restarted_services=restarted, failed_or_stale_units=failed,+ )+ assert drained == [4343] and restarted == ["hermes-gateway"] and failed == []+++def test_manual_gateway_of_another_home_is_not_stopped(monkeypatch, own_home):+ """Of two ``gateway run`` processes on the host, only the one on the updating home is SIGTERMed;+ a process whose home cannot be read is spared as well."""+ _pid_homes(monkeypatch, {111: str(own_home), 222: FOREIGN_HOME, 333: None})+ monkeypatch.setattr("hermes_cli.gateway._get_service_pids", lambda **k: set())+ monkeypatch.setattr("hermes_cli.gateway.find_gateway_pids", lambda **k: [111, 222, 333])+ monkeypatch.setattr("hermes_cli.gateway.find_profile_gateway_processes", lambda **k: [])+ monkeypatch.setattr("hermes_cli.gateway._wait_for_gateway_exit", lambda **k: None)+ killed: list[tuple[int, int]] = []+ monkeypatch.setattr(os, "kill", lambda pid, sig: killed.append((pid, sig)))++ out = fleet._GatewayRestartOutcome(+ incomplete=False, phase_errors=[], pre_restart_gateway_pids=[], restarted_services=[],+ failed_or_stale_units=[], relaunched_profiles=[], externally_supervised_profiles=[], killed_pids=set(),+ )+ fleet._restart_manual_gateways(out, 5.0)+ assert killed == [(111, signal.SIGTERM)]+ assert out.killed_pids == {111}diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.mdindex 03d148f441f..68050f5ed79 100644--- a/website/docs/reference/cli-commands.md+++ b/website/docs/reference/cli-commands.md@@ -1965,7 +1965,7 @@ Pulls the latest `hermes-agent` code and reinstalls dependencies in the managedAdditional behavior:-- **Gateway restart.** After a successful update, Hermes attempts to restart all running gateway profiles automatically so they pick up the new code. Use `hermes gateway restart` when you want to restart a gateway without applying an update.+- **Gateway restart.** After a successful update, Hermes attempts to restart all running gateway profiles of the home being updated (its root and every `profiles/<name>` under it) automatically so they pick up the new code. Gateways and `hermes-gateway*` services that belong to a different `HERMES_HOME` on the same machine — another install, or a scratch home running `hermes update` — are named in the output and left alone. Use `hermes gateway restart` when you want to restart a gateway without applying an update.- **Restart-phase recovery.** If the in-process restart phase aborts while importing the freshly pulled tree, supervised gateway profiles are retried through a clean Python process. Only restarts independently confirmed by systemd (`systemctl --user is-active`) are reported as verified; a relaunch that merely exited 0 is recorded as `relaunch_attempted` and still fails the update conservatively. Manual gateways and serve/dashboard runtimes are never killed without a relaunch authority; they are recorded as skipped with a reason and remain in the incomplete-update report with the exact restart command.- **Update receipts + fleet version check.** Every run writes a machine-readable receipt to `~/.hermes/logs/update_receipts/` (pre-update fleet plan, steps, skips with reasons, restart outcome; `latest.json` points at the newest). After the restart phase the updater verifies each live gateway's running code against the updated checkout and prints a per-profile version matrix; a gateway still on pre-update code fails the update (exit 1) with the exact restart command.- **Local source changes.** For git installs, dirty tracked files and untracked files are auto-stashed before branch checkout or pull (`git stash push --include-untracked`). Interactive terminal updates ask before restoring the stash. Non-interactive updates restore it by default; set `updates.non_interactive_local_changes: discard` only on managed installs where local source edits should be thrown away after a successful pull. If stash restore conflicts or the pull fails, the stash is left in place for manual recovery.