Skip to content

The agent that grows with you

fix(review): a named profile's `restart --all` never runs the root gateway in-process

teknium14cb2c8ae7687
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 2e75b922345..ac028811533 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -3656,7 +3656,10 @@ def systemd_install(
# ever enabling, so even the migration's install path was no enablement guarantee
# (#124922).
if enable_on_startup:
- _run_systemctl(["enable", get_service_name()], system=system, check=False, timeout=30)
+ enabled = _run_systemctl(["enable", get_service_name()], system=system, check=False, timeout=30)
+ if getattr(enabled, "returncode", 0) != 0:
+ print_warning(f"could not enable {get_service_name()} at boot "
+ f"(systemctl enable exited {enabled.returncode}); a reboot may come up with no gateway")
# Same post-install guarantee as a fresh install: a repaired user unit must survive logout too.
configured_user = _read_systemd_user_from_unit(unit_path) if system else None
if configured_user:
@@ -5449,12 +5452,23 @@ def _restart_all_as_host(owner, system: bool) -> None:
print("Starting gateway...")
# Even without a registered task, gateway_windows.start() uses the detached launcher.
kind = _installed_service_kind_for(is_windows)
- if kind is None:
- # replace=True: if the old owner is still draining (a long drain, an ineffective SIGKILL, a
- # foreign-home owner the scan never saw), take the host over instead of attaching to it.
- run_gateway(verbose=0, replace=True)
- else:
+ if kind is not None:
_service_call(kind, "start", system)
+ return
+ from hermes_constants import get_routing_process_hermes_home, named_profile_home
+ if named_profile_home(get_routing_process_hermes_home()) is not None:
+ # A named profile's CLI never runs the root IN this process: os.environ holds that profile's
+ # .env and the root's dotenv load does not clear inherited keys, so the host served the
+ # default profile with the named profile's credentials. The detached child starts from the
+ # scrubbed host env (the root's own secrets only); `--replace` is part of its argv.
+ if not _spawn_detached_gateway():
+ print_error("Failed to start the host gateway as a background process.")
+ sys.exit(1)
+ print("✓ Started the host gateway as a background process")
+ return
+ # replace=True: if the old owner is still draining (a long drain, an ineffective SIGKILL, a
+ # foreign-home owner the scan never saw), take the host over instead of attaching to it.
+ run_gateway(verbose=0, replace=True)
def _cmd_restart(args):
diff --git a/hermes_cli/gateway_migrate.py b/hermes_cli/gateway_migrate.py
index 45358686208..4a3d1631b99 100644
--- a/hermes_cli/gateway_migrate.py
+++ b/hermes_cli/gateway_migrate.py
@@ -204,16 +204,30 @@ class MigrationPlan:
def _home_env(home: Path) -> Iterator[None]:
"""Run service-manager helpers as if ``home`` were the active HERMES_HOME. Both the contextvar
override (``get_hermes_home``) and ``os.environ`` (``gateway.status`` identity files, unit
- generation) are switched, then restored."""
- from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ generation) are switched, then restored.
+
+ The process keeps its LAUNCH identity while swapped (``pin_process_hermes_home``): ``os.environ``
+ still holds the launch profile's ``.env``, so a child spawned in here for ``home`` must see it as
+ a routed home and take only ``home``'s own secrets — with the env var swapped, the routed-home
+ checks read ``home`` as the launch profile and handed the launch profile's credentials to the
+ default gateway."""
+ from hermes_constants import (
+ get_routing_process_hermes_home, pin_process_hermes_home, process_hermes_home_is_pinned,
+ reset_hermes_home_override, set_hermes_home_override,
+ )
import hermes_constants
previous = os.environ.get("HERMES_HOME")
+ pinned_here = not process_hermes_home_is_pinned()
+ if pinned_here:
+ pin_process_hermes_home(get_routing_process_hermes_home())
token = set_hermes_home_override(str(home))
os.environ["HERMES_HOME"] = str(home)
hermes_constants._default_hermes_root_memo = None
try:
yield
finally:
+ if pinned_here:
+ pin_process_hermes_home(None)
reset_hermes_home_override(token)
if previous is None:
os.environ.pop("HERMES_HOME", None)
@@ -352,14 +366,13 @@ def _service_op(kind: str, system: bool, verb: str, home: Path, *, run_as_user:
# load-bearing for the whole host — and `restart` on a disabled unit succeeds, so a
# reboot came up with no gateway while the migration reported success (#124922).
# launchd (RunAtLoad plist) and the Windows logon task are their own enablement and the
- # migration never removes the survivor's. Best-effort with a loud line: failing here
- # would trigger a rollback that cannot do any better.
+ # migration never removes the survivor's.
if kind != "systemd":
return
enabled = gw._run_systemctl(["enable", gw.get_service_name()], system=system, check=False, timeout=30)
if getattr(enabled, "returncode", 0) != 0:
- print(f"⚠ could not enable {gw.get_service_name()} at boot "
- f"(systemctl enable exited {enabled.returncode}); a reboot may come up with no gateway")
+ raise RuntimeError(f"could not enable {gw.get_service_name()} at boot (systemctl enable "
+ f"exited {enabled.returncode}); a reboot would come up with no gateway")
return
gw._service_call(kind, verb, system)
@@ -906,17 +919,24 @@ def _restart_default(
return f"{verb} the default gateway (detached; no service manager was in use)"
-def _enable_default_at_boot(plan: MigrationPlan) -> None:
+def _enable_default_at_boot(plan: MigrationPlan) -> Optional[str]:
"""Make the survivor boot-startable BEFORE anything is removed. Every secondary unit the fold
uninstalls takes its boot enablement with it, and the pre-existing default unit may have been
disabled all along; ``restart`` on a disabled unit succeeds, so the old order (remove, then
restart) turned N boot-startable gateways into 0 and reported success (#124922). ``enable``
never starts the unit, so doing it first cannot double-bind a platform while secondaries run,
and an apply interrupted anywhere after it still leaves a host that comes back after a reboot.
+ Returns the failure line, or None: a fresh apply refuses on it (nothing has been removed yet),
+ a resume reports it and converges anyway (rollback could do no better).
"""
- if plan.default.service is not None:
- kind, system = plan.default.service
+ if plan.default.service is None:
+ return None
+ kind, system = plan.default.service
+ try:
_service_op(kind, system, "enable", plan.default_home)
+ except RuntimeError as exc:
+ return f"default: {exc}"
+ return None
def _remove_secondary_gateways(plan: MigrationPlan) -> None:
@@ -1023,11 +1043,14 @@ def apply_migration(plan: MigrationPlan, *, served_wait: float = _SERVED_WAIT_SE
# Re-running this command IS the recovery.
print(f" ↻ resuming the migration recorded in {_manifest_path(plan.default_home)}")
_print(_resume_findings(plan, target, run_as_user))
+ enable_failure = _enable_default_at_boot(plan)
+ if enable_failure is not None:
+ print(f" ⚠ {enable_failure} — resuming anyway")
else:
if plan.blocked:
_print(["✗ Migration refused:", *[f" • {b}" for b in plan.blockers]])
return False
- blocker = _preflight_apply(plan, target, run_as_user)
+ blocker = _preflight_apply(plan, target, run_as_user) or _enable_default_at_boot(plan)
if blocker is not None:
_print(["✗ Migration refused before changing anything:", f" • {blocker}"])
return False
@@ -1043,7 +1066,6 @@ def apply_migration(plan: MigrationPlan, *, served_wait: float = _SERVED_WAIT_SE
try:
_write_multiplex_flag(plan.default_home, True)
print(f" ✓ default: gateway.multiplex_profiles: true ({plan.default_home / 'config.yaml'})")
- _enable_default_at_boot(plan)
_remove_secondary_gateways(plan) # on resume: whatever an apply killed mid-removal left installed
print(f" ✓ {_restart_default(plan.default, target, plan.default_home, run_as_user=run_as_user)}")
except Exception as exc:
diff --git a/hermes_cli/profiles_service_cleanup.py b/hermes_cli/profiles_service_cleanup.py
index ce7c3fd9b8a..74a0a5b4723 100644
--- a/hermes_cli/profiles_service_cleanup.py
+++ b/hermes_cli/profiles_service_cleanup.py
@@ -26,10 +26,16 @@ def remove_system_systemd_unit() -> bool:
print(f"⚠ System service {svc_name} remains at {unit}; it will restart the removed profile at boot.")
print(f" Remove it with: sudo systemctl disable --now {svc_name} && sudo rm {unit} && sudo systemctl daemon-reload")
return False
- for cmd in (["disable", svc_name], ["stop", svc_name]):
- subprocess.run(["systemctl", *cmd], capture_output=True, check=False, timeout=30)
+ subprocess.run(["systemctl", "disable", svc_name], capture_output=True, check=False, timeout=30)
+ stopped = subprocess.run(["systemctl", "stop", svc_name], capture_output=True, check=False, timeout=30)
unit.unlink(missing_ok=True)
subprocess.run(["systemctl", "daemon-reload"], capture_output=True, check=False, timeout=30)
+ if getattr(stopped, "returncode", 0) != 0:
+ # The unit file is gone (it must not resurrect the removed profile at boot), but the
+ # gateway it supervised may still be running under the old name.
+ print(f"⚠ System service {svc_name} unit removed, but `systemctl stop` exited {stopped.returncode}; "
+ f"its gateway may still be running. Stop it with: sudo systemctl stop {svc_name}")
+ return True
print(f"✓ System service {svc_name} removed")
return True
diff --git a/tests/hermes_cli/test_gateway_host_verbs.py b/tests/hermes_cli/test_gateway_host_verbs.py
index a4c244a5020..1fe5c9135c9 100644
--- a/tests/hermes_cli/test_gateway_host_verbs.py
+++ b/tests/hermes_cli/test_gateway_host_verbs.py
@@ -167,6 +167,10 @@ def test_named_profile_restart_all_with_host_down_restarts_the_default_root(monk
Post-update the host is down, so the ownership refusal cannot fire; the sweep-and-relaunch
then ran as X, whose own gateway the run-side named-profile guard refuses (exit 78).
+
+ And it must relaunch the root as a DETACHED child carrying only the root's own secrets: X's
+ CLI already loaded X's ``.env`` into ``os.environ``, and an in-process ``run_gateway`` served the
+ default profile with X's credentials.
"""
import hermes_constants
@@ -175,6 +179,12 @@ def test_named_profile_restart_all_with_host_down_restarts_the_default_root(monk
named.mkdir(parents=True)
(root / "config.yaml").write_text("{}\n", encoding="utf-8")
(named / "config.yaml").write_text("{}\n", encoding="utf-8")
+ (root / ".env").write_text("DISCORD_BOT_TOKEN=root-discord\n", encoding="utf-8")
+ (named / ".env").write_text("TELEGRAM_BOT_TOKEN=leinad-telegram\nOPENAI_API_KEY=leinad-openai\n",
+ encoding="utf-8")
+ # The CLI startup already loaded leinad's .env into this process.
+ monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "leinad-telegram")
+ monkeypatch.setenv("OPENAI_API_KEY", "leinad-openai")
monkeypatch.setenv("HERMES_HOME", str(named))
hermes_constants._default_hermes_root_memo = None
@@ -185,17 +195,27 @@ def test_named_profile_restart_all_with_host_down_restarts_the_default_root(monk
monkeypatch.setattr(gw, "_wait_for_api_server_port_free", lambda **k: True)
monkeypatch.setattr(gw, "_discard_dead_host_record", lambda: False)
monkeypatch.setattr(gw, "_installed_service_kind_for", lambda windows: None)
+ monkeypatch.setattr(gw, "run_gateway",
+ lambda **k: pytest.fail("the root ran IN the named profile's process"))
+ monkeypatch.setattr(gw, "get_python_path", lambda: sys.executable)
- started_as = []
- monkeypatch.setattr(
- gw, "run_gateway",
- lambda **k: started_as.append((Path(hermes_constants.get_hermes_home()), k.get("replace"))),
- )
+ spawned: list[tuple[list[str], dict]] = []
+ monkeypatch.setattr(gw.subprocess, "Popen",
+ lambda cmd, **kw: spawned.append((cmd, kw)) or SimpleNamespace())
gw._restart_all(system=False)
- assert started_as == [(root, True)]
+ assert len(spawned) == 1
+ cmd, kwargs = spawned[0]
+ assert cmd[-3:] == ["gateway", "run", "--replace"]
+ assert "--profile" not in cmd
+ env = kwargs["env"]
+ assert Path(env["HERMES_HOME"]) == root
+ assert env.get("DISCORD_BOT_TOKEN") == "root-discord"
+ assert "TELEGRAM_BOT_TOKEN" not in env and "OPENAI_API_KEY" not in env, \
+ "the host child inherited the named profile's credentials"
assert hermes_constants.get_hermes_home() == named
+ assert not hermes_constants.process_hermes_home_is_pinned()
def test_restart_all_refuses_to_sweep_a_host_multiplexer_owned_by_another_profile(
diff --git a/tests/hermes_cli/test_gateway_migrate_multiplex.py b/tests/hermes_cli/test_gateway_migrate_multiplex.py
index cfadf680e75..90869e4213b 100644
--- a/tests/hermes_cli/test_gateway_migrate_multiplex.py
+++ b/tests/hermes_cli/test_gateway_migrate_multiplex.py
@@ -18,6 +18,9 @@ import pytest
import hermes_constants
from hermes_cli import gateway_migrate as gm
+# Captured before any fixture fakes the seam: the one test that drives the real service leg.
+_REAL_SERVICE_OP = gm._service_op
+
@pytest.fixture
def fleet(tmp_path, monkeypatch):
@@ -908,6 +911,31 @@ def test_migrate_enables_the_survivor_before_it_removes_anything(fleet, capsys):
assert fleet.ops[-1] == ("default", "restart") and "serves 3 profiles" in capsys.readouterr().out
+def test_migrate_refuses_when_the_survivor_cannot_be_enabled(fleet, monkeypatch, capsys):
+ """A failed `systemctl enable` is a preflight refusal, not a ⚠ line: continuing removed every
+ boot-startable secondary and reported ✓ Migrated over a host that comes back with no gateway."""
+ from hermes_cli import gateway as gw
+ fleet.services["default"] = ("systemd", False)
+ fake_op = gm._service_op
+ monkeypatch.setattr(gw, "_run_systemctl", lambda args, **kw: SimpleNamespace(returncode=1))
+
+ def _op(kind, system, verb, home, *, run_as_user=None):
+ if verb == "enable": # the real leg, over a systemctl that fails
+ return _REAL_SERVICE_OP(kind, system, verb, home, run_as_user=run_as_user)
+ fake_op(kind, system, verb, home, run_as_user=run_as_user)
+
+ monkeypatch.setattr(gm, "_service_op", _op)
+
+ with pytest.raises(SystemExit) as exc:
+ gm.cmd_migrate(SimpleNamespace(multiplex=True, dry_run=False, yes=True))
+
+ assert exc.value.code == 1
+ assert not any(op[1] in ("stop", "uninstall") for op in fleet.ops), "refusal must precede every removal"
+ assert fleet.pids == {"coder": 4101, "ops": 4102} and _config_flag(fleet.root) is None
+ assert not gm._manifest_path(fleet.root).exists()
+ assert "refused before changing anything" in capsys.readouterr().out
+
+
def test_plan_names_every_process_it_will_sigterm_before_it_signals_anything(fleet, capsys):
"""A running gateway is never stopped silently: the dry run names the pids and changes nothing."""
gm.cmd_migrate(SimpleNamespace(multiplex=True, dry_run=True, yes=True))
diff --git a/tools/environments/local.py b/tools/environments/local.py
index 346d22da2ea..42791325ff9 100644
--- a/tools/environments/local.py
+++ b/tools/environments/local.py
@@ -450,11 +450,11 @@ def strip_launch_profile_env(env: dict, target_home: "str | Path | None" = None)
gateway-wide multiplex flag on": the Desktop/dashboard backend serves ``?profile=B`` by
installing a HERMES_HOME override without that flag."""
from agent.secret_scope import _is_global_env, load_env_file
- from hermes_constants import get_hermes_home_override, get_process_hermes_home
+ from hermes_constants import get_hermes_home_override, get_routing_process_hermes_home
target = target_home or get_hermes_home_override()
if not target or not _is_routed_home(target):
return env
- launch_home = get_process_hermes_home()
+ launch_home = get_routing_process_hermes_home()
from hermes_cli.config import TERMINAL_CONFIG_ENV_MAP
# Folded strip: on Windows the env block is case-insensitive, so residue
# stored under a variant casing is the same variable and must go too. The