The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): lifecycle verbs never act on another home's unit and refuse while sessions are live
Teknium9248d847d094
diff --git a/gateway/run_active_work_verb.py b/gateway/run_active_work_verb.pynew file mode 100644index 00000000000..5ba939ad932--- /dev/null+++ b/gateway/run_active_work_verb.py@@ -0,0 +1,51 @@+"""``active-work`` control verb: what a stop/restart of this gateway would interrupt, answered live.++``gateway_state.json`` names each unit only while draining and its ``active_agents`` total leaves out+async delegations, so a CLI asking "may I stop this gateway?" could not see a background subagent+that ``stop()`` interrupts (``tools.async_delegation.interrupt_all``). The verb answers from the+running process instead: the same units the drain report publishes plus every live delegation.+"""++from __future__ import annotations++import os+import threading+import time+from typing import Any, Callable+++def _delegation_units(now: float) -> list[dict[str, Any]]:+ from tools.async_delegation import _LIVE_STATES, list_async_delegations++ units = []+ for record in list_async_delegations():+ if record.get("status") not in _LIVE_STATES:+ continue+ unit: dict[str, Any] = {"kind": "delegation", "delegation_id": record.get("delegation_id"),+ "goal": str(record.get("goal") or "")[:80], "pid": os.getpid()}+ if record.get("dispatched_at"):+ unit["elapsed_s"] = round(now - float(record["dispatched_at"]), 1)+ units.append(unit)+ return units+++def active_work_verb(runner, loop) -> Callable[[], dict[str, Any]]:+ """Handler for the control socket: runs on its executor thread, reads the runner on the loop."""++ def _handler() -> dict[str, Any]:+ box: list[list] = []+ done = threading.Event()++ def _collect() -> None:+ try:+ box.append(runner._describe_active_work())+ finally:+ done.set()++ loop.call_soon_threadsafe(_collect)+ done.wait(timeout=5.0)+ units = list(box[0]) if box else []+ units += _delegation_units(time.time())+ return {"active_agents": runner._active_work_count(), "active_work": units, "pid": os.getpid()}++ return _handlerdiff --git a/gateway/run_bootstrap.py b/gateway/run_bootstrap.pyindex 3b5314a9d84..af6b92fce6d 100644--- a/gateway/run_bootstrap.py+++ b/gateway/run_bootstrap.py@@ -270,6 +270,7 @@ async def _start_gateway_start_control_socket(runner):unserve_profile_verb, serve_profile_verb,)from gateway.run_plugin_rewire import reload_plugins_verb+ from gateway.run_active_work_verb import active_work_verbfrom gateway.drain_control import RESTART_WAIT_REASONdescriptor = runner.session_runtime_descriptor@@ -341,6 +342,8 @@ async def _start_gateway_start_control_socket(runner):"unserve-profile": unserve_profile_verb(runner),"serve-profile": serve_profile_verb(runner),"purge-profile-identity": purge_profile_identity_verb(runner),+ # `hermes gateway stop/restart` refuse while this names live work.+ "active-work": active_work_verb(runner, _main_loop),# A plugin installed/enabled by another process loads now and re-wires the# live adapters' handlers (#87770); tools/prompt still wait for the next session."reload-plugins": reload_plugins_verb(runner, _main_loop)})diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex 3608069b373..05cc9c1938e 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -1253,62 +1253,6 @@ def _hermes_home_from_systemd_unit_file(system: bool = False) -> str | None:return _hermes_home_pinned_by_unit(get_systemd_unit_path(system=system))-def _account_default_hermes_home() -> Path | None:- """``<account home>/.hermes`` from the passwd database — NOT ``$HOME``, which test harnesses and- profile isolation repoint. None where the account is unknown."""- try:- import pwd- return Path(pwd.getpwuid(os.geteuid()).pw_dir) / ".hermes"- except (ImportError, KeyError, OSError):- return None---def _foreign_systemd_unit_home(system: bool) -> str | None:- """``HERMES_HOME`` of the unit at this scope when it belongs to ANOTHER install, else None.-- The service name only encodes the home relative to the process's own ``$HOME``, so a process whose- ``HERMES_HOME`` is ``$HOME/.hermes`` under a throwaway ``HOME`` (test harnesses, CI sandboxes,- scripted installs) resolves the bare ``hermes-gateway`` name — and a system unit is global, so it- resolves the PRODUCTION unit. ``_sync_hermes_home_from_systemd_unit`` would then adopt that unit's- home and ``stop``/``restart`` would take the live gateway down. Must be evaluated BEFORE that sync.-- Foreign means: the unit pins a home, it differs from this process's home, and this process's home- is not the account's own default root. The last clause keeps the ``sudo`` remap (#108674): root's- default home operating a unit that pins the invoking user's home is the operator, not a stranger.- """- unit_home = _hermes_home_pinned_by_unit(get_systemd_unit_path(system=system))- if not unit_home:- return None- try:- unit = Path(unit_home).expanduser().resolve()- mine = get_hermes_home().resolve()- except OSError:- return None- if unit == mine:- return None- account_default = _account_default_hermes_home()- if account_default is not None:- try:- if mine == account_default.resolve():- return None- except OSError:- pass- return unit_home---def _refuse_foreign_systemd_unit(action: str, system: bool) -> None:- """Exit non-zero instead of operating another install's unit (see ``_foreign_systemd_unit_home``)."""- unit_home = _foreign_systemd_unit_home(system)- if unit_home is None:- return- print_error(- f"Refusing to {action} {get_service_name()}: that {_service_scope_label(system)} unit runs "- f"HERMES_HOME={unit_home}, but this process has HERMES_HOME={get_hermes_home()}.\n"- f"It belongs to another Hermes install. Run this from that install's HERMES_HOME."- )- sys.exit(1)--def _sync_hermes_home_from_systemd_unit(system: bool) -> None:"""Adopt a system-scope unit's ``HERMES_HOME``: under ``sudo`` it is stripped and HOME=/root, soget_hermes_home() would pick the wrong profile for runtime-status/PID reads."""@@ -1779,9 +1723,17 @@ def _gateway_list() -> None:def kill_gateway_processes(force: bool = False, exclude_pids: set | None = None, all_profiles: bool = False) -> int:"""Kill running gateway processes (force-kill if ``force``); ``exclude_pids`` skips e.g. just-- restarted service PIDs. Returns count killed."""+ restarted service PIDs. Returns count killed. ``all_profiles`` sweeps only gateways whose live home+ is this install's root or one of its profiles: the process scan is account-wide, and a scratch-home+ ``gateway stop --all`` would otherwise SIGTERM the account's real gateway."""killed = 0- for pid in find_gateway_pids(exclude_pids=exclude_pids, all_profiles=all_profiles):+ pids = find_gateway_pids(exclude_pids=exclude_pids, all_profiles=all_profiles)+ if all_profiles:+ from hermes_cli.update_fleet_scope import partition_gateway_pids_by_scope+ pids, foreign = partition_gateway_pids_by_scope(pids)+ for pid, home in foreign:+ print(f"↷ PID {pid}: gateway of {'another Hermes home (' + home + ')' if home else 'an unreadable home'} — left alone")+ for pid in pids:try:expected_start_time = Noneif force:@@ -2261,11 +2213,13 @@ def _profile_name_from_home(home: Path, default: Path) -> str | None:def _native_service_homes() -> set[Path]:- """This process's native default home plus, when root under sudo, the invoking user's (see- ``_profile_suffix`` for why sudo matters)."""- from hermes_constants import _get_platform_default_hermes_home, sudo_invoker_default_home+ """The account's native default home plus, when root under sudo, the invoking user's (see+ ``_profile_suffix`` for why sudo matters). The ACCOUNT home, not the process HOME: the unit dir+ follows the account (``user_systemd_unit_dir``), so a scratch ``HOME`` that called its own+ ``.hermes`` native resolved the bare name onto the account's real unit."""+ from hermes_constants import account_default_hermes_home, sudo_invoker_default_home- homes = {_get_platform_default_hermes_home().resolve()}+ homes = {account_default_hermes_home().resolve()}sudo_home = sudo_invoker_default_home()if sudo_home is not None:homes.add(sudo_home.resolve())@@ -3708,7 +3662,7 @@ def _systemd_scope_preamble(def _systemd_unit_belongs_to_current_home(system: bool = False) -> bool:"""False (with a warning) when the installed unit pins a HERMES_HOME other than this process's: theservice name then resolved to ANOTHER install's gateway, and stop/disable/unlink would take it down."""- foreign = _foreign_systemd_unit_home(system) # before the sync below rewrites this process's home+ foreign = gateway_service_owner.foreign_systemd_unit_home(system) # before the sync below rewrites this process's homeif foreign is not None:print_warning(f"Refusing to remove {get_systemd_unit_path(system=system)}: it runs HERMES_HOME={foreign}, "@@ -3756,7 +3710,7 @@ def _require_service_installed(action: str, system: bool = False) -> None:def systemd_start(system: bool = False):system = _systemd_scope_preamble("start", system, preflight_user=True)- _refuse_foreign_systemd_unit("start", system)+ gateway_service_owner.refuse_foreign_systemd_unit("start", system)# HERMES_HOME sync happens in refresh's systemd_unit_is_current gate; the unit is guaranteed to exist here.refresh_systemd_unit_if_needed(system=system)_run_systemctl(["start", get_service_name()], system=system, check=True, timeout=30)@@ -3765,7 +3719,7 @@ def systemd_start(system: bool = False):def systemd_stop(system: bool = False):system = _systemd_scope_preamble("stop", system)- _refuse_foreign_systemd_unit("stop", system)+ gateway_service_owner.refuse_foreign_systemd_unit("stop", system)_sync_hermes_home_from_systemd_unit(system=system)_mark_planned_stop()try:@@ -3781,7 +3735,7 @@ def systemd_stop(system: bool = False):def systemd_restart(system: bool = False):system = _systemd_scope_preamble("restart", system, preflight_user=True)- _refuse_foreign_systemd_unit("restart", system)+ gateway_service_owner.refuse_foreign_systemd_unit("restart", system)# HERMES_HOME sync happens in refresh's systemd_unit_is_current gate; its os.environ mutation# persists for the get_running_pid / drain-timeout reads below.refresh_systemd_unit_if_needed(system=system)@@ -4821,7 +4775,7 @@ def _systemd_unit_installed() -> bool:operating the other install's service."""if not supports_systemd_services():return False- return any(get_systemd_unit_path(system=s).exists() and _foreign_systemd_unit_home(s) is None+ return any(get_systemd_unit_path(system=s).exists() and gateway_service_owner.foreign_systemd_unit_home(s) is Nonefor s in (False, True))@@ -4862,7 +4816,8 @@ def _service_backend(*, windows: bool = True) -> str | None:def _service_call(backend: str, verb: str, system: bool | None = False) -> None:"""Run ``verb`` (start/stop/restart/uninstall) on ``backend``. Names resolve at call time so tests- can monkeypatch them; only systemd takes a scope, and ``system=None`` omits it (wizard restart)."""+ can monkeypatch them; only systemd takes a scope, and ``system=None`` omits it (wizard restart).+ Each systemd/launchd verb refuses a definition pinning another HERMES_HOME itself."""if backend == "windows":return getattr(_gw_windows(), verb)()if backend == "launchd":@@ -5393,6 +5348,8 @@ def _cmd_stop(args):print(f" hermes {owner_flag}gateway stop # takes every served profile offline")print(f" hermes {owner_flag}gateway restart")sys.exit(GATEWAY_FATAL_CONFIG_EXIT_CODE)+ from hermes_cli.gateway_lifecycle_guards import refuse_while_sessions_live+ refuse_while_sessions_live("stop", args)# Under s6 a bare pkill is seen as a crash and restarted; go through the supervisor.if stop_all and _dispatch_all_via_service_manager_if_s6("stop"):return@@ -5494,38 +5451,6 @@ def _restart_all_as_host(owner, system: bool) -> None:run_gateway(verbose=0, replace=True)-def _refuse_restart_of_service_managed_gateway(pid: int | None) -> None:- """Refuse the manual restart fallback when systemd owns the gateway under ANY unit name.-- Canonical-unit checks miss pre-convention installs (``hermes.service``), so the fallback's- stop + in-process ``run_gateway`` SIGKILLed a live service-managed gateway and spawned an- unsupervised orphan in the caller's cgroup while the unit flapped against the stolen lock- (#126474). Reuses the dashboard's MainPID-verified lookup: a bare ``.service`` cgroup alone- (the caller itself started under some unit) never proves ownership.- """- if not pid or pid <= 1:- return- from hermes_cli import main_dashboard as _dash-- owner = _dash._systemd_owner_for_pid(pid)- if owner is None:- return- unit, scope = owner- cmds = _dash._systemd_restart_commands(unit, scope)- _print_lines(- "",- f"✗ Gateway (PID {pid}) is managed by systemd unit {unit}.",- " `hermes gateway restart` cannot restart it from here: the fallback would",- " kill a live gateway and spawn an unsupervised replacement in this shell's",- " cgroup while the unit keeps failing against the stolen lock.",- " Restart it through its unit instead:",- *(f" {c}" for c in cmds),- " (Pre-convention `hermes.service` installs: `hermes gateway migrate-legacy`",- " removes the legacy unit so the canonical one can own the gateway.)",- )- sys.exit(1)--def _cmd_restart(args):_refuse_from_inside_gateway("restart", "restart loops")from hermes_cli.gateway_profile_lifecycle import profile_lifecycle@@ -5539,6 +5464,8 @@ def _cmd_restart(args):# unreachable for `-p X gateway restart --all` (it printed a bare `gateway restart` instead).if not restart_all:_guard_named_profile_under_multiplexer(force=force)+ from hermes_cli.gateway_lifecycle_guards import refuse_while_sessions_live+ refuse_while_sessions_live("restart", args)if restart_all and _dispatch_all_via_service_manager_if_s6("restart"):returnif not restart_all and _dispatch_via_service_manager_if_s6("restart"):@@ -5595,13 +5522,14 @@ def _cmd_restart(args):# run below would stamp this CLI's PID as the gateway and wedge every respawn (#110637).from gateway.status import get_running_pidfrom hermes_cli.gateway_supervised_restart import (- gateway_declares_external_supervisor, restart_externally_supervised_gateway,+ gateway_declares_external_supervisor, refuse_restart_of_service_managed_gateway,+ restart_externally_supervised_gateway,)supervised_pid = get_running_pid()if supervised_pid and gateway_declares_external_supervisor(supervised_pid):restart_externally_supervised_gateway(supervised_pid)return- _refuse_restart_of_service_managed_gateway(supervised_pid)+ refuse_restart_of_service_managed_gateway(supervised_pid)if stop_profile_gateway():print("✓ Stopped gateway for this profile")diff --git a/hermes_cli/gateway_launchd.py b/hermes_cli/gateway_launchd.pyindex 0617ef2d56f..de8a8a1decd 100644--- a/hermes_cli/gateway_launchd.py+++ b/hermes_cli/gateway_launchd.py@@ -676,6 +676,7 @@ def launchd_install(force: bool = False, *, start_now: bool = True, force_unit_pdef launchd_uninstall():+ gateway_service_owner.refuse_foreign_launchd_plist("uninstall")plist_path = _gw().get_launchd_plist_path()# Captured: uninstalling an already-unloaded job is fine — don't print Boot-out failed: 3.subprocess.run(@@ -688,6 +689,7 @@ def launchd_uninstall():def launchd_start():+ gateway_service_owner.refuse_foreign_launchd_plist("start")plist_path = _gw().get_launchd_plist_path()label = _gw().get_launchd_label()@@ -739,6 +741,7 @@ def _launchd_ok(message: str) -> None:def launchd_stop():+ gateway_service_owner.refuse_foreign_launchd_plist("stop")target = f"{_launchd_domain()}/{get_launchd_label()}"_gw()._mark_planned_stop()# bootout unloads the definition so KeepAlive doesn't respawn; `hermes gateway start` re-bootstraps.@@ -777,6 +780,7 @@ def _wait_for_launchd_service_pid(def launchd_restart():+ gateway_service_owner.refuse_foreign_launchd_plist("restart")label = _gw().get_launchd_label()domain = _gw()._launchd_domain()target = f"{domain}/{label}"diff --git a/hermes_cli/gateway_lifecycle_guards.py b/hermes_cli/gateway_lifecycle_guards.pynew file mode 100644index 00000000000..dd24a96f0f5--- /dev/null+++ b/hermes_cli/gateway_lifecycle_guards.py@@ -0,0 +1,100 @@+"""Refusals that keep ``hermes gateway`` lifecycle verbs off gateways they must not take down.++Two rules, one per failure that took a production gateway down:++* **Foreign service definition.** A systemd unit / launchd plist pins the ``HERMES_HOME`` its gateway+ runs on. A lifecycle verb (start/stop/restart/uninstall) on a definition pinning ANOTHER home acts on+ another install's gateway: a ``HOME=<scratch>`` probe resolved the bare ``hermes-gateway`` name and ran+ ``systemctl --user stop`` on the account's real unit. Install/refresh already refused to WRITE such a+ definition (``gateway_service_owner``); the same module now refuses to OPERATE one:+ ``refuse_foreign_systemd_unit`` (salvaged from #141908, checked before any home sync) and+ ``refuse_foreign_launchd_plist``.+* **Live sessions.** ``gateway stop``/``restart`` refuse while the gateway is running turns, cron jobs or+ background delegations, naming each, unless the caller passes ``--interrupt``. The in-band restart+ drains turns, but its stop still interrupts every async delegation (``interrupt_all``), and a stop+ ends the sessions outright.+"""++from __future__ import annotations++import sys+from pathlib import Path+from typing import Any, Optional++INTERRUPT_FLAG = "--interrupt"+++def _live_work_from_state(home: Path) -> Optional[dict[str, Any]]:+ """``active_agents`` from a fresh ``gateway_state.json`` whose writer is alive (older gateways)."""+ from gateway.status import parse_active_agents, read_runtime_status, runtime_status_is_stale, runtime_status_pid_is_live++ record = read_runtime_status(home / "gateway_state.json")+ if not record or runtime_status_is_stale(record) or not runtime_status_pid_is_live(record):+ return None+ work = record.get("active_work")+ return {"active_agents": parse_active_agents(record.get("active_agents")),+ "active_work": work if isinstance(work, list) else []}+++def live_work(home: Path) -> Optional[dict[str, Any]]:+ """What the gateway serving ``home`` is running now: ``{"active_agents", "active_work"}``, or None+ when no gateway answers. The control socket answers live; the state file covers older gateways."""+ from gateway.control_socket import query_gateway_control++ answer = query_gateway_control(home, "active-work")+ if isinstance(answer, dict) and isinstance(answer.get("active_work"), list):+ return answer+ return _live_work_from_state(home)+++def _candidate_homes() -> list[Path]:+ """Homes whose gateway a stop/restart from here takes down, in order: this home's own gateway (a+ ``--force`` standalone one included), then the live host owner that serves it."""+ from hermes_cli import gateway as gw++ homes = [gw.get_hermes_home()]+ owner = gw._host_multiplexer_for_all_verb()+ if owner is not None and Path(owner.home) not in homes:+ homes.append(Path(owner.home))+ return homes+++def refusal_lines(verb: str, homes: list[Path], *, flag_hint: str = f"hermes gateway {{verb}} {INTERRUPT_FLAG}") -> list[str]:+ """Refusal text for ``verb`` while the first answering gateway among ``homes`` has live work, else []."""+ from hermes_cli.update_cmd_drain_report import describe_active_work_unit++ for home in homes:+ work = live_work(home)+ if work is not None:+ break+ else:+ return []+ units = [u for u in work.get("active_work") or [] if isinstance(u, dict)]+ count = max(len(units), int(work.get("active_agents") or 0))+ if not count:+ return []+ lines = [f"Refusing to {verb} the gateway: {count} live session(s) would be interrupted."]+ lines += [f" • {describe_active_work_unit(u, home)}" for u in units]+ if not units:+ lines.append(f" • {count} active agent run(s) (this gateway does not name them)")+ lines += [" Let them finish, or interrupt them deliberately:",+ f" {flag_hint.format(verb=verb)} # interrupts {count} live session(s)"]+ return lines+++def refuse_while_sessions_live(verb: str, args) -> None:+ """Exit 1 naming the live work unless ``--interrupt`` was passed; with it, say what is interrupted."""+ lines = refusal_lines(verb, _candidate_homes())+ if not lines:+ return+ from hermes_cli.gateway import print_error, print_warning++ if getattr(args, "interrupt", False):+ print_warning(lines[0].replace(f"Refusing to {verb} the gateway", f"--interrupt: {verb} proceeds"))+ for line in lines[1:-2]:+ print(line)+ return+ print_error(lines[0])+ for line in lines[1:]:+ print(line)+ sys.exit(1)diff --git a/hermes_cli/gateway_runtime_service.py b/hermes_cli/gateway_runtime_service.pyindex cec8c49910e..2066940aff4 100644--- a/hermes_cli/gateway_runtime_service.py+++ b/hermes_cli/gateway_runtime_service.py@@ -42,9 +42,9 @@ def service_suffix(home: Path) -> str:profile name; any other root (Docker, a temp harness) yields a path hash so acustom root can never resolve to the production ``hermes-gateway`` unit."""- from hermes_constants import _get_platform_default_hermes_home+ from hermes_constants import account_default_hermes_homefrom hermes_cli.gateway import _profile_name_from_home- default = _get_platform_default_hermes_home().resolve()+ default = account_default_hermes_home().resolve()home = home.resolve()if home == default:return ""diff --git a/hermes_cli/gateway_service_owner.py b/hermes_cli/gateway_service_owner.pyindex 29b35f9c38c..4586a0d8665 100644--- a/hermes_cli/gateway_service_owner.py+++ b/hermes_cli/gateway_service_owner.py@@ -15,6 +15,7 @@ from __future__ import annotationsimport osimport plistlib+import sysfrom pathlib import Pathfrom xml.parsers.expat import ExpatError@@ -97,6 +98,59 @@ def unit_belongs_to_caller(unit_path: Path, system: bool, action: str, run_as_usreturn definition_belongs_to_home(unit_path, home, action)+def foreign_systemd_unit_home(system: bool) -> str | None:+ """``HERMES_HOME`` of the unit at this scope when it belongs to ANOTHER install, else None.++ A throwaway ``HOME`` used to resolve the bare ``hermes-gateway`` name (its ``.hermes`` looked native) and+ reach the account's real unit — user scope through the account-anchored unit dir, system scope+ because system units are global. Naming now follows the account home, but two homes can still share+ a name (a custom root's ``profiles/<name>``, a pre-pinning unit), so every systemd verb asks this.+ ``_sync_hermes_home_from_systemd_unit`` would adopt the unit's home and ``stop``/``restart`` would take+ the live gateway down, so it must be evaluated BEFORE that sync.++ Foreign means: the unit pins a home, it differs from this process's home, and this process's home+ is not the account's own default root. The last clause keeps the ``sudo`` remap (#108674): root's+ default home operating a unit that pins the invoking user's home is the operator, not a stranger.+ """+ from hermes_cli import gateway as gw+ unit_home = gw._hermes_home_pinned_by_unit(gw.get_systemd_unit_path(system=system))+ if not unit_home:+ return None+ try:+ unit = Path(unit_home).expanduser().resolve()+ mine = gw.get_hermes_home().resolve()+ except OSError:+ return None+ if unit == mine:+ return None+ from hermes_constants import account_default_hermes_home+ if mine == account_default_hermes_home().resolve():+ return None+ return unit_home+++def refuse_foreign_systemd_unit(action: str, system: bool) -> None:+ """Exit non-zero instead of operating another install's unit (see ``foreign_systemd_unit_home``)."""+ from hermes_cli import gateway as gw+ unit_home = foreign_systemd_unit_home(system)+ if unit_home is None:+ return+ gw.print_error(+ f"Refusing to {action} {gw.get_service_name()}: that {gw._service_scope_label(system)} unit runs "+ f"HERMES_HOME={unit_home}, but this process has HERMES_HOME={gw.get_hermes_home()}.\n"+ f"It belongs to another Hermes install. Run this from that install's HERMES_HOME."+ )+ sys.exit(1)+++def refuse_foreign_launchd_plist(verb: str) -> None:+ """The launchd half of ``refuse_foreign_systemd_unit``: exit 1 rather than start/stop/restart/remove a+ LaunchAgent pinning another HERMES_HOME. (Windows task names derive from LOCALAPPDATA, not HOME.)"""+ from hermes_cli import gateway as gw+ if not definition_belongs_to_home(gw.get_launchd_plist_path(), gw.get_hermes_home(), verb):+ sys.exit(1)++def service_definition_homes(definition: str) -> list[str]:"""Every HERMES_HOME a gateway service definition sets: systemd ``Environment=``, launchd``EnvironmentVariables``, the Windows ``gateway.cmd`` ``set`` line and the ``gateway.vbs`` env item."""diff --git a/hermes_cli/gateway_supervised_restart.py b/hermes_cli/gateway_supervised_restart.pyindex 27fbbc5bf32..f110aac19eb 100644--- a/hermes_cli/gateway_supervised_restart.py+++ b/hermes_cli/gateway_supervised_restart.py@@ -102,3 +102,36 @@ def restart_externally_supervised_gateway(supervised_pid: int) -> None:" then rerun once it is healthy: hermes gateway restart",)sys.exit(1)+++def refuse_restart_of_service_managed_gateway(pid: int | None) -> None:+ """Refuse the manual restart fallback when systemd owns the gateway under ANY unit name.++ Canonical-unit checks miss pre-convention installs (``hermes.service``), so the fallback's+ stop + in-process ``run_gateway`` SIGKILLed a live service-managed gateway and spawned an+ unsupervised orphan in the caller's cgroup while the unit flapped against the stolen lock+ (#126474). Reuses the dashboard's MainPID-verified lookup: a bare ``.service`` cgroup alone+ (the caller itself started under some unit) never proves ownership.+ """+ if not pid or pid <= 1:+ return+ from hermes_cli import main_dashboard as _dash++ owner = _dash._systemd_owner_for_pid(pid)+ if owner is None:+ return+ unit, scope = owner+ cmds = _dash._systemd_restart_commands(unit, scope)+ from hermes_cli.gateway import _print_lines+ _print_lines(+ "",+ f"✗ Gateway (PID {pid}) is managed by systemd unit {unit}.",+ " `hermes gateway restart` cannot restart it from here: the fallback would",+ " kill a live gateway and spawn an unsupervised replacement in this shell's",+ " cgroup while the unit keeps failing against the stolen lock.",+ " Restart it through its unit instead:",+ *(f" {c}" for c in cmds),+ " (Pre-convention `hermes.service` installs: `hermes gateway migrate-legacy`",+ " removes the legacy unit so the canonical one can own the gateway.)",+ )+ sys.exit(1)diff --git a/hermes_cli/subcommands/gateway.py b/hermes_cli/subcommands/gateway.pyindex 67c659ca363..0fdc551fa55 100644--- a/hermes_cli/subcommands/gateway.py+++ b/hermes_cli/subcommands/gateway.py@@ -14,6 +14,11 @@ _FORCE_SERVED_PROFILE_HELP = ("Start a separate gateway for this profile even when the default multiplexer already serves it ""(not recommended: two pollers on one bot token, port conflicts)")+# `stop`/`restart` refuse while the gateway runs turns, cron jobs or background delegations.+_INTERRUPT_HELP = (+ "{verb} even while sessions are live (turns, cron jobs, background delegations): they are "+ "interrupted. Without it the command names the live work and refuses")+class _GatewayCommandParser(argparse.ArgumentParser):"""Ensure's parser errors share its machine-readable command boundary."""@@ -135,12 +140,14 @@ def build_gateway_parser(gateway_stop = gateway_subparsers.add_parser("stop", help="Stop gateway service")_add_system_flag(gateway_stop)_flag(gateway_stop, "--all", help="Stop ALL gateway processes across all profiles")+ _flag(gateway_stop, "--interrupt", help=_INTERRUPT_HELP.format(verb="stop"))gateway_restart = gateway_subparsers.add_parser("restart", help="Restart gateway service")_add_system_flag(gateway_restart)_flag(gateway_restart, "--all",help="Kill ALL gateway processes across all profiles before restarting")_flag(gateway_restart, "--force", help=_FORCE_SERVED_PROFILE_HELP)+ _flag(gateway_restart, "--interrupt", help=_INTERRUPT_HELP.format(verb="restart"))_add_compat_platform_flag(gateway_restart)gateway_status = gateway_subparsers.add_parser("status", help="Show gateway status")diff --git a/hermes_cli/update_cmd_drain_report.py b/hermes_cli/update_cmd_drain_report.pyindex 24696cca1c5..d465b7e29e5 100644--- a/hermes_cli/update_cmd_drain_report.py+++ b/hermes_cli/update_cmd_drain_report.py@@ -64,6 +64,10 @@ def describe_active_work_unit(unit: dict, home: Optional[Path] = None) -> str:tool = unit.get("current_tool")detail = ", ".join(p for p in (f"model {model}" if model else "", f"tool {tool}" if tool else "") if p)return f"chat turn {session}{pid_part}{elapsed_part}" + (f" [{detail}]" if detail else "")+ if kind == "delegation":+ goal = str(unit.get("goal") or "").strip()+ return (f"background delegation {unit.get('delegation_id') or '?'}{pid_part}{elapsed_part}"+ + (f" [{goal}]" if goal else ""))return f"{kind} run{pid_part}{elapsed_part}"diff --git a/hermes_cli/update_restart_recovery.py b/hermes_cli/update_restart_recovery.pyindex 0f357351cf4..5304ea87ffe 100644--- a/hermes_cli/update_restart_recovery.py+++ b/hermes_cli/update_restart_recovery.py@@ -137,7 +137,9 @@ def _run_profile_restart(profile: str, *, run: Callable[..., Any]) -> bool:kwargs["creationflags"] = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0) | getattr(subprocess, "DETACHED_PROCESS", 0)else:kwargs["start_new_session"] = True- argv = [sys.executable, "-m", "hermes_cli.main", "-p", profile, "gateway", "restart"]+ # `--interrupt`: the update owns this restart (drain-first, 31637312899); a live session must not+ # strand the profile on pre-update code the way a refusal would.+ argv = [sys.executable, "-m", "hermes_cli.main", "-p", profile, "gateway", "restart", "--interrupt"]return _succeeded(_run_quiet(run, argv, timeout=_PROFILE_RESTART_TIMEOUT, **kwargs))diff --git a/hermes_cli/web_routers/actions.py b/hermes_cli/web_routers/actions.pyindex dcf345602f9..8265e90f96e 100644--- a/hermes_cli/web_routers/actions.py+++ b/hermes_cli/web_routers/actions.py@@ -159,9 +159,10 @@ def _persisted_action_id(log_dir: Path, name: str) -> Optional[str]:@router.post("/api/gateway/restart")async def restart_gateway(profile: Optional[str] = None):- """Kick off a ``hermes gateway restart`` in the background."""+ """Kick off a ``hermes gateway restart --interrupt`` in the background: the user-commanded force+ path that supersedes a drain (D6, 19b26244046), so live sessions do not refuse it."""with http_failure("Failed to spawn gateway restart", 500, "Failed to restart gateway"):- proc, _reused = _spawn_gateway_restart(profile)+ proc, _reused = _spawn_gateway_restart(profile, interrupt=True)return {"ok": True, "pid": proc.pid, "name": "gateway-restart"}diff --git a/hermes_cli/web_routers/ops.py b/hermes_cli/web_routers/ops.pyindex 5f9b7b6a4aa..0df948a5db7 100644--- a/hermes_cli/web_routers/ops.py+++ b/hermes_cli/web_routers/ops.py@@ -307,15 +307,18 @@ async def start_gateway(profile: Optional[str] = None):@router.post("/api/gateway/stop")-async def stop_gateway(profile: Optional[str] = None):- from hermes_cli.web_server_gateway import multiplexed_profile_refusal+async def stop_gateway(profile: Optional[str] = None, interrupt: bool = False):+ from hermes_cli.web_server_gateway import live_session_refusal, multiplexed_profile_refusal# A served profile has no gateway of its own to stop: the child prints "No gateway running for this# profile" (exit 0) while the multiplexer keeps serving it and the UI flips to "stopped".refusal = await asyncio.to_thread(multiplexed_profile_refusal, profile, "stop")if refusal:raise HTTPException(status_code=409, detail=refusal)+ # Live sessions refuse a stop unless the caller interrupts them deliberately (`?interrupt=true`).+ if not interrupt and (refusal := await asyncio.to_thread(live_session_refusal, profile, "stop")):+ raise HTTPException(status_code=409, detail=refusal)with http_failure("Failed to spawn gateway stop", 500, "Failed to stop gateway"):- proc = _spawn_hermes_action(_gateway_subcommand(profile, "stop"), "gateway-stop")+ proc = _spawn_hermes_action(_gateway_subcommand(profile, "stop") + ["--interrupt"] * interrupt, "gateway-stop")return {"ok": True, "pid": proc.pid, "name": "gateway-stop"}diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex 4f21bfdc665..52847313c0c 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -686,7 +686,7 @@ GATEWAY_RESTART_COOLDOWN_SECONDS = 10.0_LAST_GATEWAY_RESTART: Optional[tuple[float, subprocess.Popen, tuple[str, ...]]] = None-def _spawn_gateway_restart(profile: Optional[str] = None) -> tuple[subprocess.Popen, bool]:+def _spawn_gateway_restart(profile: Optional[str] = None, *, interrupt: bool = False) -> tuple[subprocess.Popen, bool]:"""Spawn ``hermes gateway restart``, reusing an in-flight or recent restart.Concurrent children race each other on the kill-and-start path, so a live@@ -699,7 +699,10 @@ def _spawn_gateway_restart(profile: Optional[str] = None) -> tuple[subprocess.Po"""global _LAST_GATEWAY_RESTART- subcommand = _gateway_mod._gateway_subcommand(profile, "restart")+ # ``interrupt``: ``POST /api/gateway/restart`` is the user-commanded force path that supersedes a+ # drain (D6 of the safe-shutdown plan, 19b26244046); a config-save auto-restart is not, and its+ # child refuses while sessions are live.+ subcommand = _gateway_mod._gateway_subcommand(profile, "restart") + ["--interrupt"] * interruptexisting = _gateway_mod._ACTION_PROCS.get("gateway-restart")if existing is not None and existing.poll() is None:existing_command = _gateway_mod._ACTION_COMMANDS.get("gateway-restart")diff --git a/hermes_cli/web_server_gateway.py b/hermes_cli/web_server_gateway.pyindex 6bc413f19c7..ec7595dfcaf 100644--- a/hermes_cli/web_server_gateway.py+++ b/hermes_cli/web_server_gateway.py@@ -657,11 +657,28 @@ def multiplexed_profile_refusal(profile: Optional[str], verb: str) -> Optional[sf"`hermes -p {requested} gateway install --force` starts a separate one anyway.")+def live_session_refusal(profile: Optional[str], verb: str) -> Optional[str]:+ """Refusal text when the gateway ``verb`` would act on has live sessions, else None. Asked before+ spawning: the child refuses the same way, but into an action log the UI never reads."""+ from hermes_cli.gateway_lifecycle_guards import refusal_lines+ from hermes_cli.web_server_profiles import _resolve_profile_dir+ homes = [_resolve_profile_dir(_own_profile_selector(profile) or "default")]+ from gateway.host_attach import host_gateway+ owner = host_gateway()+ if owner is not None:+ homes.append(Path(owner.home))+ lines = refusal_lines(verb, homes, flag_hint=f"POST /api/gateway/{verb}?interrupt=true")+ return "\n".join(lines) or None++def _restart_gateway_after(profile: Optional[str], *, what: str, label: str) -> dict[str, Any]:"""Best-effort gateway restart after a config change. The save stays authoritative: a failedspawn is reported (``restart_started: False`` + ``restart_error``) so the UI can fall back to- its manual restart banner instead of failing the request."""+ its manual restart banner instead of failing the request. Live sessions refuse it the same way."""from hermes_cli.web_server import _spawn_gateway_restart+ refusal = live_session_refusal(profile, "restart")+ if refusal:+ return {"restart_started": False, "restart_error": refusal}try:proc, reused = _spawn_gateway_restart(profile)except Exception as exc:diff --git a/hermes_constants.py b/hermes_constants.pyindex 30252854c2e..f9897c96cc4 100644--- a/hermes_constants.py+++ b/hermes_constants.py@@ -63,6 +63,33 @@ def _get_platform_default_hermes_home() -> Path:return _platform_default_hermes_home(os.environ, Path.home)+def _account_home() -> Path:+ """The OS account's home from the password database, never ``$HOME``: harnesses and profile isolation+ repoint HOME (root under ``sudo`` has uid 0 too, which keeps the #108674 remap). Falls back to the+ shared real-home resolver where pwd cannot answer."""+ try:+ import pwd+ return Path(pwd.getpwuid(os.getuid()).pw_dir) # windows-footgun: ok — POSIX-only module inside try/except+ except (ImportError, KeyError, OSError, AttributeError):+ return Path(get_real_home())+++def account_default_hermes_home() -> Path:+ """The platform default of the OS ACCOUNT, never of a foreign process ``HOME``.++ Host service identities (``systemctl --user`` units, LaunchAgents) belong to the account, and their+ definitions are found under the account home. A process started with ``HOME=<scratch>`` used to call+ ``<scratch>/.hermes`` native, name the bare ``hermes-gateway`` unit, and stop the account's real+ gateway through it. When the process HOME is the account home the two answers are the same home.+ """+ account = _account_home()+ try:+ same = Path.home().resolve() == account.resolve()+ except (OSError, RuntimeError):+ same = False+ return _get_platform_default_hermes_home() if same else _platform_default_hermes_home(os.environ, lambda: account)++def _hermes_root_of(native_home: Path, env_path: Path | None) -> Path:"""The root that holds *env_path*: the native home, a custom root, or *env_path* itself."""if env_path is None:diff --git a/tests/hermes_cli/test_gateway_foreign_unit_guard.py b/tests/hermes_cli/test_gateway_foreign_unit_guard.pyindex c2d162f4193..4067c60c857 100644--- a/tests/hermes_cli/test_gateway_foreign_unit_guard.py+++ b/tests/hermes_cli/test_gateway_foreign_unit_guard.py@@ -13,6 +13,7 @@ from pathlib import Pathimport pytestimport hermes_cli.gateway as gateway_cli+from hermes_cli import gateway_service_owner@pytest.fixture@@ -30,7 +31,8 @@ def host(tmp_path, monkeypatch):monkeypatch.setattr(gateway_cli, "_SYSTEM_UNIT_DIR", unit_dir)monkeypatch.setattr(gateway_cli, "user_systemd_unit_dir", lambda: tmp_path / "no-user-units")monkeypatch.setattr(gateway_cli, "supports_systemd_services", lambda: True)- monkeypatch.setattr(gateway_cli, "_account_default_hermes_home", lambda: account, raising=False)+ import hermes_constants+ monkeypatch.setattr(hermes_constants, "_account_home", lambda: account.parent)monkeypatch.setattr(os, "geteuid", lambda: 0)# Never reach a real systemd: preamble/privilege checks are not under test, systemctl is recorded.monkeypatch.setattr(gateway_cli, "_systemd_scope_preamble", lambda action, system, **_k: system)@@ -43,15 +45,20 @@ def host(tmp_path, monkeypatch):def _sandbox(monkeypatch, host):+ """A sandbox home whose resolved unit name collides with a unit pinning the production home. The+ naming root no longer gives a throwaway HOME the bare name, but names still collide (a custom root's+ ``profiles/<name>``, a pre-pinning unit), so the guard is what keeps the verb off that unit."""monkeypatch.setenv("HOME", str(host["sandbox_home"]))monkeypatch.setenv("HERMES_HOME", str(host["sandbox_home"] / ".hermes"))+ collided = gateway_cli._SYSTEM_UNIT_DIR / f"{gateway_cli.get_service_name()}.service"+ collided.write_text(f'[Service]\nEnvironment="HERMES_HOME={host["prod"]}"\nExecStart=/bin/true\n', encoding="utf-8")@pytest.mark.platforms("linux")-def test_sandbox_home_resolves_the_bare_name_but_the_unit_is_not_installed_for_it(host, monkeypatch):+def test_sandbox_home_does_not_name_the_bare_unit_and_a_colliding_unit_is_not_installed_for_it(host, monkeypatch):_sandbox(monkeypatch, host)- assert gateway_cli.get_service_name() == gateway_cli._SERVICE_BASE # the hazard's precondition- assert gateway_cli._foreign_systemd_unit_home(True) == str(host["prod"])+ assert gateway_cli.get_service_name() != gateway_cli._SERVICE_BASE # naming root: account, not $HOME+ assert gateway_service_owner.foreign_systemd_unit_home(True) == str(host["prod"])assert gateway_cli._systemd_unit_installed() is False # `gateway stop` -> PID pathassert gateway_cli._installed_service_kind_for(lambda: False) is None@@ -79,7 +86,7 @@ def test_sudo_from_the_account_default_home_still_operates_the_unit(host, monkey"""#108674: root's default home driving a unit that pins the invoking user's home is the operator."""monkeypatch.setenv("HOME", str(host["account"].parent))monkeypatch.setenv("HERMES_HOME", str(host["account"]))- assert gateway_cli._foreign_systemd_unit_home(True) is None+ assert gateway_service_owner.foreign_systemd_unit_home(True) is Nonegateway_cli.systemd_stop(system=True)assert host["calls"] == [["stop", gateway_cli.get_service_name()]]assert Path(os.environ["HERMES_HOME"]) == host["prod"] # adopted, as beforediff --git a/tests/hermes_cli/test_gateway_lifecycle_guards.py b/tests/hermes_cli/test_gateway_lifecycle_guards.pynew file mode 100644index 00000000000..7a8bb6d00a7--- /dev/null+++ b/tests/hermes_cli/test_gateway_lifecycle_guards.py@@ -0,0 +1,192 @@+"""Gateway lifecycle verbs never take down a gateway they must not touch.++Two P0 invariants:++* A lifecycle call never acts on a service definition pinning another HERMES_HOME. A probe run with+ ``HOME=<scratch>`` resolved the bare ``hermes-gateway`` name (its scratch ``.hermes`` looked native),+ found the ACCOUNT's real unit through the account-anchored unit dir, and ``systemctl --user stop``+ took the production gateway down.+* ``gateway stop``/``restart`` refuse while the gateway runs live sessions, naming them, unless the+ caller passes ``--interrupt``.++Every ``systemctl``/``launchctl``/kill seam is replaced by a recorder; nothing here executes one.+"""++from __future__ import annotations++import os+from types import SimpleNamespace++import pytest++from hermes_cli import gateway as gw+++def _unit(path, home) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(f'[Service]\nEnvironment="HERMES_HOME={home}"\nExecStart=/usr/bin/hermes gateway run\n',+ encoding="utf-8")+++def recorded(monkeypatch):+ """Record every service-manager and process-kill call instead of running it."""+ calls: list = []+ monkeypatch.setattr(gw, "_run_systemctl", lambda argv, **kw: calls.append(("systemctl", list(argv))))+ monkeypatch.setattr(gw.subprocess, "run", lambda argv, *a, **kw: calls.append(("run", list(argv))))+ monkeypatch.setattr(gw, "terminate_pid", lambda pid, **kw: calls.append(("kill", pid)))+ monkeypatch.setattr(gw, "supports_systemd_services", lambda: True)+ monkeypatch.setattr(gw, "_preflight_user_systemd", lambda: None)+ monkeypatch.setattr(gw, "refresh_systemd_unit_if_needed", lambda system=False: False)+ return calls+++# ── Invariant 1: never act on another home's service ─────────────────────────────────────────────++[email protected]("linux")+def test_scratch_home_does_not_resolve_the_accounts_bare_gateway_unit(tmp_path, monkeypatch):+ """The incident's resolution: HOME=<scratch>, HERMES_HOME unset, the account's real bare unit+ pinning the account home. The scratch home must not name that unit."""+ account, scratch = tmp_path / "account", tmp_path / "scratch"+ (scratch / ".hermes").mkdir(parents=True)+ real_unit = account / ".config" / "systemd" / "user" / "hermes-gateway.service"+ _unit(real_unit, account / ".hermes")+ monkeypatch.delenv("HERMES_HOME", raising=False)+ monkeypatch.delenv("XDG_CONFIG_HOME", raising=False)+ monkeypatch.setenv("HOME", str(scratch))+ monkeypatch.setenv("HERMES_REAL_HOME", str(account))+ monkeypatch.setattr(os, "geteuid", lambda: 1000)++ assert gw.get_hermes_home() == scratch / ".hermes"+ assert gw.get_service_name() != "hermes-gateway"+ assert gw.get_systemd_unit_path() != real_unit+ assert not gw.get_systemd_unit_path().exists()++[email protected]("linux")[email protected]("verb", ["stop", "restart", "start", "uninstall"])+def test_lifecycle_verb_refuses_a_user_unit_pinning_another_home(tmp_path, monkeypatch, recorded, capsys, verb):+ """The incident's scope (USER unit; #141908's tests cover the system unit). Two homes can still share+ a unit name (a custom root's ``profiles/coder`` and the account's): the verb refuses the unit that+ pins the other one, with no systemctl call at all and without adopting its home."""+ account = tmp_path / "account"+ custom_profile = tmp_path / "custom" / "profiles" / "coder"+ custom_profile.mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(custom_profile))+ monkeypatch.setenv("XDG_CONFIG_HOME", str(account / ".config"))+ monkeypatch.setattr(os, "geteuid", lambda: 1000)+ unit = gw.get_systemd_unit_path()+ assert unit.name == "hermes-gateway-coder.service"+ _unit(unit, account / ".hermes" / "profiles" / "coder")++ if verb == "uninstall":+ gw._service_call("systemd", verb, False)+ else:+ with pytest.raises(SystemExit) as exc:+ gw._service_call("systemd", verb, False)+ assert exc.value.code == 1++ assert recorded == []+ captured = capsys.readouterr()+ assert "Refusing to" in captured.out + captured.err+ assert unit.exists()+ assert os.environ["HERMES_HOME"] == str(custom_profile)+++# ── Invariant 2: stop/restart refuse while sessions are live ─────────────────────────────────────+++def _live_gateway(monkeypatch, work):+ """A gateway answering the ``active-work`` control verb with *work*."""+ from gateway import control_socket+ monkeypatch.setattr(control_socket, "query_gateway_control",+ lambda home, verb, **kw: work if verb == "active-work" else None)+ monkeypatch.setattr(gw, "_host_multiplexer_for_all_verb", lambda: None)+ monkeypatch.setattr(gw, "_dispatch_via_service_manager_if_s6", lambda *a, **k: False)+ monkeypatch.setattr(gw, "find_gateway_pids", lambda *a, **k: [4242])+++_WORK = {"active_agents": 2, "active_work": [+ {"kind": "chat", "session": "agent:main:telegram:dm:7", "pid": 4242, "elapsed_s": 75.0},+ {"kind": "delegation", "delegation_id": "deleg_ab12cd34", "goal": "review the PR", "pid": 4242},+]}+++def test_stop_refuses_while_sessions_are_live_and_names_them(monkeypatch, recorded, capsys):+ _live_gateway(monkeypatch, _WORK)+ stopped: list = []+ monkeypatch.setattr(gw, "_stop_installed_service", lambda system: stopped.append(system) or True)+ monkeypatch.setattr(gw, "stop_profile_gateway", lambda: stopped.append("process") or True)++ with pytest.raises(SystemExit) as exc:+ gw._cmd_stop(SimpleNamespace(all=False, system=False, interrupt=False))++ out = capsys.readouterr().out+ assert exc.value.code == 1+ assert stopped == [] and recorded == []+ assert "2 live session(s)" in out+ assert "chat turn agent:main:telegram:dm:7" in out+ assert "background delegation deleg_ab12cd34" in out+ assert "hermes gateway stop --interrupt" in out++ gw._cmd_stop(SimpleNamespace(all=False, system=False, interrupt=True))+ assert stopped == [False]+ assert "--interrupt: stop proceeds: 2 live session(s) would be interrupted" in capsys.readouterr().out+++def test_restart_refuses_on_the_published_active_agents_of_an_older_gateway(monkeypatch, recorded, capsys):+ """A gateway without the control verb still publishes ``active_agents`` in gateway_state.json."""+ from gateway import control_socket+ from gateway.status import write_runtime_status+ write_runtime_status(gateway_state="running", active_agents=1)+ monkeypatch.setattr(control_socket, "query_gateway_control", lambda *a, **k: None)+ monkeypatch.setattr(gw, "_host_multiplexer_for_all_verb", lambda: None)+ monkeypatch.setattr(gw, "_guard_named_profile_under_multiplexer", lambda force=False: None)+ monkeypatch.setattr(gw, "_dispatch_via_service_manager_if_s6", lambda *a, **k: False)+ monkeypatch.setattr(gw, "_installed_service_kind_for", lambda probe: "systemd")+ service: list = []+ monkeypatch.setattr(gw, "_service_call", lambda *a: service.append(a))+ monkeypatch.setattr(gw, "_reap_unsupervised_gateway_orphans", lambda: None)++ with pytest.raises(SystemExit):+ gw._cmd_restart(SimpleNamespace(all=False, system=False, force=False, interrupt=False))++ assert service == [] and recorded == []+ assert "1 active agent run(s)" in capsys.readouterr().out+++def test_stop_all_leaves_another_homes_gateway_process_alone(monkeypatch, recorded, tmp_path):+ """``kill_gateway_processes(all_profiles=True)`` scans every gateway of this account; a scratch-home+ ``stop --all`` must not SIGTERM a gateway running on another Hermes home."""+ from hermes_cli import dashboard_procs+ own, other = str(gw.get_hermes_home()), str(tmp_path / "account" / ".hermes")+ monkeypatch.setattr(gw, "find_gateway_pids", lambda *a, **k: [111, 222])+ monkeypatch.setattr(dashboard_procs, "_hermes_home_for_pid", {111: own, 222: other}.get)++ assert gw.kill_gateway_processes(all_profiles=True) == 1+ assert recorded == [("kill", 111)]+++def test_dashboard_stop_refuses_while_sessions_are_live(monkeypatch):+ pytest.importorskip("fastapi")+ from fastapi.testclient import TestClient+ from gateway import host_attach+ from hermes_cli import web_server, web_server_gateway++ _live_gateway(monkeypatch, _WORK)+ monkeypatch.setattr(host_attach, "host_gateway", lambda **kw: None)+ monkeypatch.setattr(web_server_gateway, "multiplexed_profile_refusal", lambda *a: None)+ spawned: list = []+ monkeypatch.setattr(web_server_gateway, "_spawn_hermes_action",+ lambda argv, name: spawned.append(argv) or SimpleNamespace(pid=1))+ client = TestClient(web_server.app)+ client.headers[web_server._SESSION_HEADER_NAME] = web_server._SESSION_TOKEN++ refused = client.post("/api/gateway/stop")+ assert refused.status_code == 409+ assert "chat turn agent:main:telegram:dm:7" in refused.json()["detail"]+ assert spawned == []++ assert client.post("/api/gateway/stop?interrupt=true").status_code == 200+ assert spawned and spawned[0][-1] == "--interrupt"diff --git a/tests/hermes_cli/test_gateway_service.py b/tests/hermes_cli/test_gateway_service.pyindex ded5b696fd5..4041fd49620 100644--- a/tests/hermes_cli/test_gateway_service.py+++ b/tests/hermes_cli/test_gateway_service.py@@ -187,8 +187,8 @@ class TestServiceIdentityForForeignHome:home = tmp_path / "home"home.mkdir()monkeypatch.setattr(Path, "home", lambda: home)- # The user unit dir follows the ACCOUNT home (#98699), which is read from the environment.- monkeypatch.setenv("HOME", str(home))+ monkeypatch.setattr(hermes_constants, "_account_home", lambda: home) # names services+ monkeypatch.setenv("HOME", str(home)) # the user unit dir follows it (#98699)monkeypatch.delenv("HERMES_REAL_HOME", raising=False)monkeypatch.delenv("XDG_CONFIG_HOME", raising=False)return homediff --git a/tests/hermes_cli/test_update_restart_recovery.py b/tests/hermes_cli/test_update_restart_recovery.pyindex e32f4b66b7b..4fe4db8e1c7 100644--- a/tests/hermes_cli/test_update_restart_recovery.py+++ b/tests/hermes_cli/test_update_restart_recovery.py@@ -277,8 +277,8 @@ def test_recovery_child_restarts_each_profile_with_a_fresh_main(monkeypatch):"covered": {},}assert [call[0] for call in calls] == [- [sys.executable, "-m", "hermes_cli.main", "-p", "coder", "gateway", "restart"],- [sys.executable, "-m", "hermes_cli.main", "-p", "default", "gateway", "restart"],+ [sys.executable, "-m", "hermes_cli.main", "-p", "coder", "gateway", "restart", "--interrupt"],+ [sys.executable, "-m", "hermes_cli.main", "-p", "default", "gateway", "restart", "--interrupt"],]for _, kwargs in calls:assert kwargs["stdin"] is subprocess.DEVNULL@@ -466,4 +466,4 @@ def test_recovery_module_end_to_end_in_a_real_fresh_process(tmp_path):restarts = [json.loads(line) for line in ledger.read_text().splitlines()]assert [argv[argv.index("-p") + 1] for argv in restarts] == ["coder", "default"]for argv in restarts:- assert argv[-2:] == ["gateway", "restart"]+ assert argv[-3:] == ["gateway", "restart", "--interrupt"]