Skip to content

The agent that grows with you

fix(gateway): prove gateway ownership, not just liveness; stop trapping a mid-migration host

teknium1583864c39806
diff --git a/gateway/host_rendezvous.py b/gateway/host_rendezvous.py
index 64d9bca9890..86963033b3c 100644
--- a/gateway/host_rendezvous.py
+++ b/gateway/host_rendezvous.py
@@ -571,16 +571,15 @@ def cleanup_on_exit(role: str) -> None:
def _multiplex_profiles_enabled() -> bool:
- """Will THIS process multiplex? Explicit config wins; unset means the default (on)."""
- try:
- from hermes_cli.gateway_multiplex_mode import explicit_multiplex_flag
- from hermes_constants import get_hermes_home
-
- flag = explicit_multiplex_flag(get_hermes_home())
- except Exception:
- logger.debug("multiplex flag unreadable; assuming the default (on)", exc_info=True)
- return True
- return True if flag is None else bool(flag)
+ """Will THIS process multiplex? An explicit ``true`` and an unset key both say yes, and an
+ explicit ``false`` is RETIRED (``hermes_cli.gateway_multiplex_mode``) — it is warned about and
+ ignored at boot, so it must not make the claim-time record advertise a narrower roster than
+ the process actually serves. Reading it here was the last place the retired flag still decided
+ topology, and it made CLI/dashboard report "standalone, serving default" while the runtime
+ multiplexed. The RUNTIME verdict (a boot-time guard refusal) narrows the record afterwards, in
+ ``gateway.run._refresh_host_gateway_record``, which republishes the SETTLED set.
+ """
+ return True
def served_profiles(*, multiplex: Optional[bool] = None) -> tuple[str, ...]:
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 5f82c5d3d92..7c916e57ac6 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -2102,6 +2102,18 @@ DEFAULT_CONFIG = {
# An UNSET key is a request, not a verdict: at boot the gateway runs the migration
# preflight and stays standalone (logging why) while a secondary still runs its own
# gateway or a blocker exists, then converges once that is resolved.
+ # TWO things DO change on a host that had pinned `false`, and neither is a process:
+ # • INGRESS — `/p/<profile>/` on the default listener goes 404 -> served
+ # (gateway/api_server.py::_resolve_request_profile, gateway/webhook.py). A host that
+ # opted out GAINS that HTTP surface; it is authenticated exactly like the default
+ # profile's, but it is new reachable surface, so audit any reverse proxy that assumed
+ # /p/ was dead.
+ # • SECRET SCOPE — eager multi-profile activation no longer consults the flag
+ # (tui_gateway/launch_profile_policy.py), so a host with a leftover servable profile
+ # dir flips eager=false/reads-open -> eager=true/fail-closed: an UNSCOPED `get_secret`
+ # now raises UnscopedSecretError, and a key that lives ONLY in the unit's
+ # `Environment=` (no .env) disappears from file-built scopes. A genuinely
+ # single-profile host never activates and is byte-identical.
# Two profiles configuring the same bot token cannot be served together — the duplicate
# adapter is parked; `hermes profile create --clone` therefore leaves messaging channels
# behind unless --clone-channels is passed.
diff --git a/hermes_cli/container_boot.py b/hermes_cli/container_boot.py
index 3604efc6b0b..3a2eea9abfe 100644
--- a/hermes_cli/container_boot.py
+++ b/hermes_cli/container_boot.py
@@ -54,13 +54,35 @@ class ReconcileAction:
# "clean" / "unclean" (sentinel still says running — SIGKILL/OOM/VM death) / "unknown". Boot
# is the one place that can stamp a violent death into the volume-persisted log.
prior_exit: str = "unknown"
+ #: A named slot whose autostart intent was inherited by the root slot (multiplex-only), or —
+ #: on the root slot — True when it is starting because of one.
+ folded_into_root: bool = False
-def _slot_action(
- profile: str, profile_dir: Path, prior_state: str | None, start: bool) -> ReconcileAction:
+def _slot_action(profile: str, profile_dir: Path, prior_state: str | None, start: bool,
+ *, folded_into_root: bool = False) -> ReconcileAction:
return ReconcileAction(profile=profile, prior_state=prior_state,
action="started" if start else "registered",
- prior_exit=_read_prior_exit_label(profile_dir))
+ prior_exit=_read_prior_exit_label(profile_dir),
+ folded_into_root=folded_into_root)
+
+
+def _named_profile_dirs(hermes_home: Path) -> list[tuple[str, Path]]:
+ """Every real named profile under ``$HERMES_HOME/profiles`` (``SOUL.md`` is the marker)."""
+ profiles_root = hermes_home / "profiles"
+ if not profiles_root.is_dir():
+ return []
+ found: list[tuple[str, Path]] = []
+ for entry in sorted(profiles_root.iterdir()):
+ if not entry.is_dir() or not (entry / "SOUL.md").exists():
+ continue
+ # "default" is reserved for the root profile slot.
+ if entry.name == "default":
+ log.warning("profiles/default/ exists — skipping to avoid colliding with the "
+ "reserved root-profile s6 slot")
+ continue
+ found.append((entry.name, entry))
+ return found
def reconcile_profile_gateways(
@@ -86,41 +108,47 @@ def reconcile_profile_gateways(
# It used to be gated on `gateway.multiplex_profiles`, which made the UNSET default (on) boot
# the slots anyway — the container shipped the opt-out topology by accident. The key is retired
# as a topology switch (hermes_cli/gateway_multiplex_mode.py), so there is nothing to read.
+ named = [(name, entry, _read_desired_state(entry)) for name, entry in _named_profile_dirs(hermes_home)]
# A legacy `gateway run` container with no state yet seeds `running` (pre-s6 behavior).
legacy_default_state = _maybe_migrate_legacy_gateway_run_state(
hermes_home, container_argv=container_argv, dry_run=dry_run)
default_prior_state = legacy_default_state or _read_desired_state(hermes_home)
- default_should_start = default_prior_state in _AUTOSTART_STATES
+ # The root slot INHERITS every named slot's autostart intent, because it is the one process
+ # that serves them. Without this an image only ever driven as `hermes -p coder gateway start`
+ # booted with ZERO gateways: it has no root state (or "stopped"), every named slot is now
+ # registered down unconditionally, and every action reported "registered" — a container that
+ # looks healthy while nothing is listening.
+ folded = [name for name, _dir, prior in named if prior in _AUTOSTART_STATES]
+ default_should_start = default_prior_state in _AUTOSTART_STATES or bool(folded)
+ if folded and default_prior_state not in _AUTOSTART_STATES:
+ log.warning("%s", boot_notice(folded))
if not dry_run:
_cleanup_stale_runtime_files(hermes_home)
_register_service(scandir, "default", start=default_should_start)
- actions.append(_slot_action("default", hermes_home, default_prior_state, default_should_start))
-
- profiles_root = hermes_home / "profiles"
- if profiles_root.is_dir():
- for entry in sorted(profiles_root.iterdir()):
- # SOUL.md (seeded by `hermes profile create`) is the "real profile" marker.
- if not entry.is_dir() or not (entry / "SOUL.md").exists():
- continue
- # "default" is reserved for the root profile slot above.
- if entry.name == "default":
- log.warning("profiles/default/ exists — skipping to avoid colliding with the "
- "reserved root-profile s6 slot")
- continue
-
- prior_state = _read_desired_state(entry)
- # Registered down, always: a started named slot IS a second gateway on this host.
- should_start = False
- if not dry_run:
- _cleanup_stale_runtime_files(entry)
- _register_service(scandir, entry.name, start=should_start)
- actions.append(_slot_action(entry.name, entry, prior_state, should_start))
+ actions.append(_slot_action("default", hermes_home, default_prior_state, default_should_start,
+ folded_into_root=bool(folded)))
+
+ for name, entry, prior_state in named:
+ # Registered down, always: a started named slot IS a second gateway on this host.
+ should_start = False
+ if not dry_run:
+ _cleanup_stale_runtime_files(entry)
+ _register_service(scandir, name, start=should_start)
+ actions.append(_slot_action(name, entry, prior_state, should_start,
+ folded_into_root=name in folded))
if not dry_run:
_write_reconcile_log(hermes_home, actions)
return actions
+def boot_notice(folded: Sequence[str]) -> str:
+ """One line naming the profiles whose autostart intent the root slot took over."""
+ return ("reconcile: profile gateway(s) " + ", ".join(sorted(folded)) +
+ " asked to autostart; one gateway per container serves every profile, so the ROOT "
+ "slot (gateway-default) was started instead and multiplexes them.")
+
+
def _maybe_migrate_legacy_gateway_run_state(
hermes_home: Path, *, container_argv: Sequence[str] | None, dry_run: bool) -> str | None:
"""Seed root gateway_state for pre-s6 `gateway run` containers (the tini image let users run
@@ -315,7 +343,8 @@ def _write_reconcile_log(hermes_home: Path, actions: list[ReconcileAction]) -> N
with log_path.open("a", encoding="utf-8") as f:
for a in actions:
f.write(f"{ts} profile={a.profile} prior_state={a.prior_state} "
- f"action={a.action} prior_exit={a.prior_exit}\n")
+ f"action={a.action} prior_exit={a.prior_exit} "
+ f"folded_into_root={a.folded_into_root}\n")
def main() -> int:
@@ -330,6 +359,9 @@ def main() -> int:
hermes_home = Path(os.environ.get("HERMES_HOME", "/opt/data"))
scandir = Path(os.environ.get("S6_PROFILE_GATEWAY_SCANDIR", "/run/service"))
actions = reconcile_profile_gateways(hermes_home=hermes_home, scandir=scandir)
+ folded = [a.profile for a in actions if a.profile != "default" and a.folded_into_root]
+ if folded:
+ print(boot_notice(folded))
for a in actions:
print(f"reconcile: profile={a.profile} prior_state={a.prior_state} action={a.action}")
return 0
diff --git a/hermes_cli/gateway_migrate.py b/hermes_cli/gateway_migrate.py
index 09589cfafb8..b4f511e7293 100644
--- a/hermes_cli/gateway_migrate.py
+++ b/hermes_cli/gateway_migrate.py
@@ -9,8 +9,10 @@ crash between the two) converges on the next run instead of being reported "alre
There is no ``--standalone`` rollback command: reinstalling per-profile services is no longer a
supported topology. The rollback machinery survives as the COMPENSATOR inside a single failed
-apply (:func:`rollback_migration`) — a failed apply must never leave profiles with no gateway at
-all — and the recorded manifest is what the next re-run resumes from.
+apply (:func:`rollback_migration`) — which restores exactly ONE gateway, the default's, because
+the host gateway lock now refuses the fleet it used to rebuild — and the recorded manifest is what
+the next re-run resumes from. A manifest on disk outranks every preflight gate: a resume
+compensates an already-destructive state instead of initiating one.
The preflight reuses the gateway's own conflict logic (``GatewayRunner._adapter_credential_fingerprint``,
``platform_binds_port``, the adapters' ``serves_profile_prefix`` declaration) so its verdict matches
@@ -100,6 +102,11 @@ class MigrationPlan:
profiles: list[ProfileGateway]
multiplex_flag_on: bool
live_served: Optional[list[str]] # served_profiles the live default gateway recorded, if any
+ # The migration manifest on disk, when one exists. Its PRESENCE is the "this host is already
+ # mid-migration, with units removed" signal that turns every later gate from a refusal into a
+ # finding (see :func:`apply_migration`): a resume compensates a destructive state, it never
+ # initiates one.
+ manifest: Optional[dict] = None
# A manifest with the flag on and no LIVE default gateway: an earlier apply died between flipping
# the flag and the multiplexer confirming it is up (#110850). An installed unit is not proof of
# anything — `systemd_install` writes the unit before the start that can still fail or be killed.
@@ -209,14 +216,47 @@ def _profile_homes() -> list[tuple[str, Path]]:
def _live_gateway_pid(home: Path) -> Optional[int]:
- """Verified PID of a standalone gateway owned by ``home``, else None (never raises: a probe
- failure must not abort a migration plan)."""
+ """Verified PID of a gateway SERVING ``home``, else None (never raises: a probe failure must
+ not abort a migration plan).
+
+ Topology REPORTING, not ownership: ``live_gateway_pid_for_home`` deliberately answers with the
+ host multiplexer's PID for every home it serves (``gateway.status._host_gateway_serves_home``),
+ so "this profile is being served" reads as a live PID. Use :func:`_own_gateway_pid` for the
+ question this command acts on.
+ """
from gateway.status import live_gateway_pid_for_home
with contextlib.suppress(Exception):
return live_gateway_pid_for_home(home)
return None
+def _host_gateway_owner():
+ """The ONE live host gateway (``gateway.host_attach.HostGateway``) or None. Never raises."""
+ with contextlib.suppress(Exception):
+ from gateway.host_attach import host_gateway
+ return host_gateway()
+ return None
+
+
+def _own_gateway_pid(home: Path, owner) -> Optional[int]:
+ """PID of a gateway ``home`` OWNS, else None.
+
+ Ownership is what this command may stop, and the host multiplexer is not owned by the profiles
+ it serves: it is one process, launched from one home. Deriving ownership from
+ :func:`_live_gateway_pid` made every secondary on a CONVERGED host report the host gateway's
+ PID, so the plan called the host half-migrated and each `hermes update` SIGTERMed the only
+ gateway it had. The host process counts only for the home it was actually launched from; every
+ other profile it serves owns nothing.
+ """
+ pid = _live_gateway_pid(home)
+ if pid is None or owner is None or pid != owner.pid:
+ return pid
+ with contextlib.suppress(Exception):
+ from gateway.status import _same_hermes_home
+ return pid if _same_hermes_home(Path(owner.home), Path(home)) else None
+ return None
+
+
def _gateway_identity(home: Path, pid: Optional[int], services: list[tuple[str, bool]]) -> tuple[Optional[int], Path]:
from hermes_cli.gateway_migrate_guards import gateway_identity
return gateway_identity(home, pid, services)
@@ -469,12 +509,14 @@ def _load_profile_configs(plan: MigrationPlan) -> dict[str, object]:
def build_migration_plan() -> MigrationPlan:
- """Enumerate profiles + their gateway footprint, then run every preflight check."""
+ """Enumerate profiles + their OWN gateway footprint, then run every preflight check."""
from hermes_cli.gateway_multiplex_served import recorded_served_profiles
default_home = _default_home()
+ # Probed ONCE: every profile's ownership verdict is relative to the same host process.
+ owner = _host_gateway_owner()
profiles = []
for name, home in _profile_homes():
- pid, services = _live_gateway_pid(home), _installed_services(home)
+ pid, services = _own_gateway_pid(home, owner), _installed_services(home)
uid, runtime_home = _gateway_identity(home, pid, services)
profiles.append(ProfileGateway(name=name, home=home, pid=pid, services=services,
run_as_user=_systemd_service_user(home, services), uid=uid,
@@ -483,8 +525,9 @@ def build_migration_plan() -> MigrationPlan:
default_home=default_home, profiles=profiles,
multiplex_flag_on=_read_multiplex_flag(default_home),
live_served=recorded_served_profiles(default_home),
+ manifest=_read_manifest(default_home),
)
- plan.interrupted = plan.multiplex_flag_on and _manifest_not_yet_served(_read_manifest(default_home), plan.live_served)
+ plan.interrupted = plan.multiplex_flag_on and _manifest_not_yet_served(plan.manifest, plan.live_served)
if len(plan.profiles) < 2:
plan.notices.append("Only one profile exists: nothing to multiplex.")
return plan
@@ -510,6 +553,27 @@ def _print(lines: list[str]) -> None:
print(line)
+def _signalled_gateways(plan: MigrationPlan) -> list[str]:
+ """Every RUNNING gateway process ``apply_migration`` will signal, in apply order.
+
+ Derived from the steps the apply actually takes, not from "secondaries that happen to expose a
+ PID". Two classes were silently missing and both killed live processes: a secondary with an
+ installed unit and no readable PID is stopped through ``_service_op`` (which SIGTERMs whatever
+ the supervisor is running), and the DEFAULT's own live gateway is replaced by
+ :func:`_restart_default`. A dry run that promises nothing will be stopped and then stops the
+ host's only gateway breaks the contract this block exists to keep.
+ """
+ def _who(p: ProfileGateway, suffix: str = "") -> str:
+ where = f"pid {p.pid}" if p.pid else f"supervised by {p.service_label()}"
+ return f"{p.name} ({where}{suffix})"
+
+ signalled = [_who(p) for p in plan.standalone_secondaries if p.pid or p.services]
+ default = plan.default
+ if default.services or default.pid:
+ signalled.append(_who(default, ", restarted onto the new flag"))
+ return signalled
+
+
def format_plan(plan: MigrationPlan, *, dry_run: bool) -> list[str]:
head = "Migration plan (dry run — nothing changed)" if dry_run else "Migration plan"
lines = [head, f" default home: {plan.default_home}", "", " profile gateway pid service"]
@@ -527,7 +591,7 @@ def format_plan(plan: MigrationPlan, *, dry_run: bool) -> list[str]:
lines.append(" ↻ Half-migrated host: the flag is on, but the profile(s) below still own a "
"gateway. This run converges them.")
steps = []
- signalled = [p for p in plan.standalone_secondaries if p.pid]
+ signalled = _signalled_gateways(plan)
for p in plan.standalone_secondaries:
what = " + ".join(x for x in (f"stop pid {p.pid}" if p.pid else "", f"uninstall {p.service_label()}" if p.services else "") if x)
steps.append(f" - {p.name}: {what}")
@@ -538,7 +602,9 @@ def format_plan(plan: MigrationPlan, *, dry_run: bool) -> list[str]:
else:
lines += [" Steps:", *steps]
lines.append(f" - default: set gateway.multiplex_profiles: true in {plan.default_home / 'config.yaml'}")
- target = plan.target_service_kind()
+ # A resume installs through the units the MANIFEST recorded (the live ones are already gone),
+ # which is the mechanism ``apply_migration`` picks — printing this plan's guess contradicted it.
+ target = _resume_target(plan)[0] if plan.manifest is not None else plan.target_service_kind()
lines.append(f" - default: {'restart' if plan.default.has_gateway else 'start'} the gateway"
+ (f" via {target[0]}" if target else " (detached)") + f", verify it serves {len(plan.profiles)} profiles")
lines.append(f" - record the previous state in {plan.default_home / MANIFEST_NAME} "
@@ -547,8 +613,7 @@ def format_plan(plan: MigrationPlan, *, dry_run: bool) -> list[str]:
# Never stop a running gateway without saying so first, and say it in the imperative
# tense the operator can still act on: this block prints BEFORE anything is signalled.
lines += ["",
- " ⚠ This SIGTERMs running gateway process(es): "
- + ", ".join(f"{p.name} (pid {p.pid})" for p in signalled) + ".",
+ " ⚠ This SIGTERMs running gateway process(es): " + ", ".join(signalled) + ".",
" They drain in-flight turns and exit; their profiles are served by the host "
"gateway afterwards."]
return lines + _plan_tail(plan)
@@ -557,7 +622,17 @@ def format_plan(plan: MigrationPlan, *, dry_run: bool) -> list[str]:
def _plan_tail(plan: MigrationPlan) -> list[str]:
lines: list[str] = []
if plan.blockers:
- lines += ["", " ✗ Blockers (fix these first, nothing will be changed):"]
+ if plan.manifest is None:
+ lines += ["", " ✗ Blockers (fix these first, nothing will be changed):"]
+ else:
+ # This host is already mid-migration with units removed, so a blocker cannot be a
+ # refusal any more: refusing would leave it with nobody serving and no way forward.
+ lines += ["",
+ f" ⚠ Blockers found, but a migration is already in progress on this host "
+ f"(manifest {_manifest_path(plan.default_home)}).",
+ " This run RESUMES it and converges anyway — refusing would strand the "
+ "profiles whose",
+ " gateways an earlier attempt already removed. Fix these afterwards:"]
lines += [f" • {b}" for b in plan.blockers]
if plan.notices:
lines += ["", " Notices:"]
@@ -755,6 +830,37 @@ def _preflight_apply(plan: MigrationPlan, target: Optional[tuple[str, bool]], ru
return None
+def _resume_target(plan: MigrationPlan) -> tuple[Optional[tuple[str, bool]], Optional[str]]:
+ """Service manager + ``User=`` an apply will use: the manifest's record wins on a resume (the
+ live units it describes are already gone), else what the plan can still see."""
+ target, run_as_user = plan.target_service_kind(), plan.target_run_as_user()
+ if plan.manifest is None:
+ return target, run_as_user
+ m_target, m_user = _target_from_manifest(plan.manifest)
+ return m_target or target, m_user or run_as_user
+
+
+def _resume_findings(plan: MigrationPlan, target, run_as_user) -> list[str]:
+ """Safety checks re-run on a RESUME and reported as findings instead of refusals.
+
+ Both halves matter. Skipping them (the resume branch used to return before ``_preflight_apply``
+ ran at all) let a duplicate bot credential, a ``/p/`` ingress gap or an unresolvable service
+ user reach the multiplexer unannounced. Enforcing them as blockers is worse: a resume runs on
+ a host whose secondary units are ALREADY removed, so refusing does not prevent damage — it
+ makes the damage permanent, which is exactly how a stranded host lost its only documented
+ recovery. So: run every check, name every finding, converge anyway.
+ """
+ findings = [*plan.blockers]
+ apply_blocker = _preflight_apply(plan, target, run_as_user)
+ if apply_blocker is not None:
+ findings.append(apply_blocker)
+ if not findings:
+ return []
+ return [" ⚠ Preflight findings — resuming anyway (this host is mid-migration; refusing would",
+ " leave its profiles with no gateway at all). Fix these once it is converged:",
+ *[f" • {f}" for f in findings]]
+
+
def apply_migration(plan: MigrationPlan, *, served_wait: float = _SERVED_WAIT_SECONDS) -> bool:
"""Flip the flag, stop/uninstall every secondary gateway, bring up the multiplexer, verify.
Returns True when the multiplexer verifiably serves every profile.
@@ -762,28 +868,32 @@ def apply_migration(plan: MigrationPlan, *, served_wait: float = _SERVED_WAIT_SE
Every step after the manifest write is fallible (a config write, a secondary's stop or its
unit's daemon-reload, a system unit that needs ``--run-as-user``, an unreachable user bus) and
runs inside ONE compensating boundary: on failure the manifest written before the first
- destructive step restores the flag and every recorded per-profile gateway (#110850), so the
- fleet never ends half-migrated. The flag goes on first so an apply killed anywhere after it is
- resumable from the manifest (flag on + manifest + no live multiplexer = interrupted)."""
- if plan.blocked:
- _print(["✗ Migration refused:", *[f" • {b}" for b in plan.blockers]])
- return False
+ destructive step brings ONE gateway back (:func:`rollback_migration`), so the host never ends
+ with nobody serving. The flag goes on first so an apply killed anywhere after it is resumable
+ from the manifest (flag on + manifest + no live multiplexer = interrupted).
+
+ **Resume beats preflight.** The manifest is read BEFORE the blocker gate: a manifest means an
+ earlier apply already removed units, so this run is a compensation, not an initiation, and a
+ gate that refuses it traps the host forever (no ``--standalone``, no rollback command). The
+ checks still run — as findings, see :func:`_resume_findings`. With no manifest nothing has been
+ destroyed yet and both gates refuse exactly as before.
+ """
if plan.already_multiplexed:
print("✓ Already multiplexed — nothing to do.")
return True
- target, run_as_user = plan.target_service_kind(), plan.target_run_as_user()
- recorded = _read_manifest(plan.default_home)
- if recorded is not None:
+ target, run_as_user = _resume_target(plan)
+ manifest = plan.manifest
+ if manifest is not None:
# A manifest on disk means an earlier apply got past its first destructive step: it either
- # died mid-way (``interrupted``) or its compensating rollback did not finish. Either way the
- # manifest is the ONLY record of the units that existed, so resume from it and never
- # overwrite it. Re-running this command IS the recovery — there is no rollback command to
- # send the operator to, and refusing here left a half-migrated host with no way forward.
- manifest = recorded
- m_target, m_user = _target_from_manifest(manifest)
- target, run_as_user = m_target or target, m_user or run_as_user
+ # died mid-way (``interrupted``) or its compensator did not finish. Either way the manifest
+ # is the ONLY record of the units that existed, so resume from it and never overwrite it.
+ # 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))
else:
+ if plan.blocked:
+ _print(["✗ Migration refused:", *[f" • {b}" for b in plan.blockers]])
+ return False
blocker = _preflight_apply(plan, target, run_as_user)
if blocker is not None:
_print(["✗ Migration refused before changing anything:", f" • {blocker}"])
@@ -827,19 +937,51 @@ def apply_migration(plan: MigrationPlan, *, served_wait: float = _SERVED_WAIT_SE
return False
-def rollback_migration(default_home: Optional[Path] = None) -> bool:
- """COMPENSATOR for a failed apply: restore the flag and the recorded per-profile gateways.
+_COMPENSATOR_WAIT_SECONDS = 30.0
+
- Not a user-facing rollback — ``--standalone`` is gone and per-profile gateways are no longer a
- supported topology. This runs only inside :func:`apply_migration` when a destructive step
- raised, because the one outcome worse than a per-profile fleet is a profile with NO gateway.
+def _wait_for_live_gateway(home: Path, timeout: float) -> Optional[int]:
+ """Bounded wait for a gateway that is actually UP for ``home``; None on timeout.
+
+ A service-manager ``start`` that returns is not proof: systemd returns after its own start
+ timeout on a unit that keeps failing, and taking that for success is how the compensator
+ printed "✓ Restored" over a unit respawning every 5 s at ``ExecMainStatus=75``.
+ """
+ deadline = time.monotonic() + timeout
+ while True:
+ pid = _live_gateway_pid(home)
+ if pid is not None:
+ return pid
+ if time.monotonic() >= deadline:
+ return None
+ time.sleep(0.5)
+
+
+def rollback_migration(default_home: Optional[Path] = None) -> bool:
+ """COMPENSATOR for a failed apply: put ONE gateway back on this host.
+
+ Not a user-facing rollback and deliberately NOT a fleet restore. It used to reinstall and
+ start every recorded per-profile gateway, which the host gateway lock now forbids by
+ construction: this function clears the multiplex-owned served record first, so
+ ``gateway.host_attach`` tells each secondary to "start normally" and the flock loser exits 75
+ into a supervisor respawn loop (observed live: a secondary won the race while the default's
+ unit sat at ``NRestarts=38, ExecMainStatus=75``, respawning every 5 s — ``StartLimitIntervalSec=0``
+ defeats the limiter). Under multiplex-only a restored fleet is not a state we want to be able
+ to reach, so the compensation is the one gateway the topology allows: the DEFAULT's, on the
+ recorded flag. The secondaries whose units this attempt already removed are named in the
+ output and are served by that gateway as soon as it multiplexes (``flag_was`` is either unset
+ or the retired ``false``; both resolve to multiplex at boot once nothing blocks it).
+
+ Returns True only when a gateway is VERIFIABLY live again; the manifest is kept otherwise so
+ the next ``hermes gateway migrate --multiplex`` resumes.
"""
default_home = default_home or _default_home()
manifest = _read_manifest(default_home)
if manifest is None:
print(f"✗ No migration manifest at {_manifest_path(default_home)}; nothing to restore.")
return False
- incomplete = f"⚠ Rollback incomplete; manifest kept at {_manifest_path(default_home)}."
+ incomplete = (f"⚠ Compensation incomplete; manifest kept at {_manifest_path(default_home)}.\n"
+ f" Re-run {MIGRATE_COMMAND} — it resumes from the manifest.")
secondaries = _manifest_secondaries(manifest)
if secondaries is None:
# Refuse before touching anything: a hand-edited manifest is not a rollback authority.
@@ -855,63 +997,46 @@ def rollback_migration(default_home: Optional[Path] = None) -> bool:
default_rec = manifest.get("default")
default_gw = ProfileGateway(
- "default", default_home, pid=_live_gateway_pid(default_home),
+ "default", default_home, pid=_own_gateway_pid(default_home, _host_gateway_owner()),
services=(_recorded_services(default_rec) if isinstance(default_rec, dict) else []) or _installed_services(default_home),
)
- # The live multiplexer's record still claims every secondary; a per-profile gateway started
- # while it does is refused (exit 78, parked by RestartPreventExitStatus) — clear it FIRST.
+ names = [str(rec["profile"]) for rec in secondaries]
+ # The live multiplexer's record still claims every secondary, and every lifecycle verb reads it;
+ # clear it before the default comes back up on the restored flag.
try:
- _reconcile_standalone_runtime(default_home, {str(rec["profile"]) for rec in secondaries})
+ _reconcile_standalone_runtime(default_home, set(names))
print(" ✓ default: cleared multiplex-owned runtime status")
except Exception as exc:
print(f" ✗ default: could not clear multiplex-owned runtime status ({exc})")
print(incomplete)
return False
- ok = True
- for rec in secondaries:
- name, home = str(rec["profile"]), Path(str(rec["home"]))
- try:
- services = _recorded_services(rec)
- if services:
- for kind, system in services:
- _service_op(kind, system, "install", home, run_as_user=_recorded_run_as_user(rec))
- _service_op(kind, system, "start", home)
- print(f" ✓ {name}: reinstalled and started its {_service_label((kind, system))} service")
- elif rec.get("pid"):
- if _live_gateway_pid(home) is not None: # re-run after a partial rollback
- print(f" ✓ {name}: standalone gateway already running")
- elif _spawn_detached_gateway(home):
- print(f" ✓ {name}: started its standalone gateway (detached)")
- else:
- ok = False
- print(f" ✗ {name}: could not start its standalone gateway")
- else:
- print(f" ✓ {name}: {_NOTHING_RECORDED}")
- except Exception as exc:
- ok = False
- print(f" ✗ {name}: {exc}")
- if ok:
+
+ if not default_gw.has_gateway and not any(rec.get("pid") or _recorded_services(rec) for rec in secondaries):
_manifest_path(default_home).unlink(missing_ok=True)
- # The flag is already off, so the default must come back standalone even when a secondary
- # failed (otherwise config and the live process disagree). The restart is LAST: from inside
- # the gateway's cgroup a service-manager restart kills this process, so nothing after it runs.
- if default_gw.has_gateway:
- try:
- print(f" ✓ {_restart_default(default_gw, None, default_home)}")
- except Exception as exc:
- if ok:
- try:
- _write_manifest(default_home, manifest)
- except Exception as manifest_exc:
- print(f" ✗ default: could not restore rollback manifest ({manifest_exc})")
- ok = False
- print(f" ✗ default: could not restart its standalone gateway ({exc})")
- print(" The default gateway is still multiplexing; stop it by hand (hermes gateway stop) and re-run.")
- if ok:
- print("✓ Restored the per-profile gateways that existed before this attempt.")
- else:
+ print(f"✓ Nothing was running before this attempt ({_NOTHING_RECORDED}); the flag is restored.")
+ return True
+
+ target, run_as_user = _target_from_manifest(manifest)
+ try:
+ print(f" ✓ {_restart_default(default_gw, target, default_home, run_as_user=run_as_user)}")
+ except Exception as exc:
+ print(f" ✗ default: could not bring the host gateway back up ({exc})")
+ print(incomplete)
+ return False
+ live = _wait_for_live_gateway(default_home, _COMPENSATOR_WAIT_SECONDS)
+ if live is None:
+ print(f" ✗ default: no gateway confirmed serving this host within {_COMPENSATOR_WAIT_SECONDS:.0f}s "
+ f"(check `hermes gateway status` and the gateway log)")
print(incomplete)
- return ok
+ return False
+ _manifest_path(default_home).unlink(missing_ok=True)
+ print(f"✓ Compensated: one host gateway is running again (pid {live}) on the recorded flag.")
+ if names:
+ print(f" Per-profile gateways this attempt had already removed: {', '.join(names)}. They are "
+ f"NOT reinstalled — one gateway per host is the only supported topology — and the host "
+ f"gateway serves them as soon as it multiplexes.\n"
+ f" Run {MIGRATE_COMMAND} to finish converging.")
+ return True
# --------------------------------------------------------------------------- CLI + update hook
@@ -947,7 +1072,10 @@ def cmd_migrate(args) -> None:
return
if plan.already_multiplexed:
return
- if plan.blocked or len(plan.profiles) < 2:
+ # A manifest means this host is already mid-migration with units removed: the blocked/too-few-
+ # profiles gates describe a migration that has not started yet, and applying them here is what
+ # left a stranded host refusing its own documented recovery forever.
+ if plan.manifest is None and (plan.blocked or len(plan.profiles) < 2):
sys.exit(1 if plan.blocked else 0)
# Zero standalone secondaries is still a migration when the user asks for it explicitly: the flag
# goes on and the default gateway restarts (the update hook keeps treating that case as a no-op).
@@ -969,11 +1097,17 @@ def maybe_auto_migrate_after_update() -> None:
if _host_supports_migration() is not None or auto_migration_opted_out(_default_home()):
return
plan = build_migration_plan()
- if plan.already_multiplexed or len(plan.profiles) < 2 or not plan.standalone_secondaries:
+ if plan.already_multiplexed or len(plan.profiles) < 2:
+ return
+ # A stranded host (manifest on disk, units already removed, nobody serving) has no standalone
+ # secondaries left to find, so the "nothing to fold" exit skipped the one host that needs this
+ # most. A manifest makes the update hook a RESUME, and a resume is not gated on blockers.
+ resuming = plan.manifest is not None
+ if not plan.standalone_secondaries and not resuming:
return
print()
auto_blockers = auto_migration_blockers(plan)
- if plan.blocked or auto_blockers:
+ if not resuming and (plan.blocked or auto_blockers):
_print(format_update_warning(plan, auto_blockers))
return
print("→ Migrating per-profile gateways onto one multiplexed default gateway...")
diff --git a/hermes_cli/gateway_multiplex_mode.py b/hermes_cli/gateway_multiplex_mode.py
index a133e5edc0c..3c4989c6fa2 100644
--- a/hermes_cli/gateway_multiplex_mode.py
+++ b/hermes_cli/gateway_multiplex_mode.py
@@ -63,15 +63,22 @@ def explicit_multiplex_flag(default_home: Path) -> Optional[bool]:
def default_gateway_multiplexes(default_home: Optional[Path] = None) -> bool:
"""Does the default profile's gateway serve every profile? For CLI/dashboard processes: the LIVE
- gateway's ``served_profiles`` record when one runs (it settled the unset default itself), else the
- explicit flag, else False — an unset flag is decided by the gateway at boot, never guessed here."""
+ gateway's ``served_profiles`` record when one runs (it settled the unset default itself), else
+ the explicit flag, else False — an unset flag is decided by the gateway at boot, never guessed
+ here.
+
+ The one thing that can no longer report "standalone" is an explicit ``false``: it is RETIRED
+ (warned about and ignored at boot, see :func:`resolve_multiplex_mode`), so answering False from
+ it made every CLI surface contradict the gateway that was about to multiplex anyway.
+ """
from hermes_constants import get_default_hermes_root
from hermes_cli.gateway_multiplex_served import recorded_served_profiles
root = Path(default_home) if default_home is not None else get_default_hermes_root()
recorded = recorded_served_profiles(root)
if recorded is not None:
return bool(recorded)
- return bool(explicit_multiplex_flag(root))
+ flag = explicit_multiplex_flag(root)
+ return False if flag is None else True
@dataclass(frozen=True)
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 35f847dbc53..e6d7c8fe700 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -1489,7 +1489,7 @@ def start_server(
# launch profile's credentials, and that snapshot is the only source for launch keys with no
# ``.env`` to rebuild from (systemd ``Environment=``, ``op run``, Compose): anything injected or
# rotated by a later boot step would otherwise be invisible for the process lifetime. No-op on a
- # single-profile host and on one that pinned ``gateway.multiplex_profiles: false``.
+ # single-profile host; `gateway.multiplex_profiles: false` is retired and no longer skips it.
try:
from tui_gateway.launch_profile_policy import activate_multi_profile_hosting_eagerly
diff --git a/tests/gateway/test_host_attach_lifecycle.py b/tests/gateway/test_host_attach_lifecycle.py
index 7c526bdfdfb..933bb08fe49 100644
--- a/tests/gateway/test_host_attach_lifecycle.py
+++ b/tests/gateway/test_host_attach_lifecycle.py
@@ -209,8 +209,12 @@ def test_the_claim_time_record_publishes_no_served_set(tmp_path, monkeypatch):
hr.clear_record(hr.ROLE_GATEWAY)
-def test_served_profiles_honours_a_multiplex_off_setting(monkeypatch):
- """``served_profiles()`` forced ``multiplex=True`` and claimed profiles it would never serve."""
+def test_served_profiles_ignores_the_retired_opt_out_but_honours_an_explicit_argument(monkeypatch):
+ """``served_profiles()`` forced ``multiplex=True`` and claimed profiles it would never serve,
+ so it learned to read ``gateway.multiplex_profiles``. That key is now RETIRED as a topology
+ opt-out: reading it here was the last place an explicit ``false`` still narrowed the record,
+ which is why the CLI reported "standalone, serving default" while the runtime multiplexed.
+ The caller's explicit argument — the RUNTIME verdict — still decides."""
asked: list[bool] = []
def _roster(*, multiplex):
@@ -219,13 +223,12 @@ def test_served_profiles_honours_a_multiplex_off_setting(monkeypatch):
else [("default", Path("/x"))])
monkeypatch.setattr("hermes_cli.profiles.profiles_to_serve", _roster)
- # The operator's explicit `gateway.multiplex_profiles: false` — stubbed at the reader every
- # tree has, so a tree that ignores the setting fails on the OUTCOME below.
monkeypatch.setattr(
"hermes_cli.gateway_multiplex_mode.explicit_multiplex_flag", lambda home: False)
- assert hr.served_profiles() == ("default",)
- assert asked == [False]
+ assert hr.served_profiles() == ("default", "other")
+ assert hr.served_profiles(multiplex=False) == ("default",)
+ assert asked == [True, False]
@pytest.mark.skipif(sys.platform == "win32",
diff --git a/tests/hermes_cli/test_container_boot.py b/tests/hermes_cli/test_container_boot.py
index 6ccbc110a8c..1a38672bdbc 100644
--- a/tests/hermes_cli/test_container_boot.py
+++ b/tests/hermes_cli/test_container_boot.py
@@ -123,7 +123,7 @@ def test_a_named_profile_slot_is_registered_but_never_autostarted(tmp_path: Path
)
assert _named_actions(actions) == [ReconcileAction(
- profile="coder", prior_state="running", action="registered",
+ profile="coder", prior_state="running", action="registered", folded_into_root=True,
)]
svc = scandir / "gateway-coder"
assert (svc / "run").exists()
@@ -158,7 +158,7 @@ def test_the_retired_opt_out_cannot_boot_a_second_gateway_in_the_container(
actions = reconcile_profile_gateways(hermes_home=tmp_path, scandir=scandir, dry_run=False)
assert _named_actions(actions) == [ReconcileAction(
- profile="coder", prior_state="running", action="registered")]
+ profile="coder", prior_state="running", action="registered", folded_into_root=True)]
assert (scandir / "gateway-coder" / "down").exists()
@@ -333,3 +333,42 @@ def _write_lifecycle_sentinel(profile_dir: Path, payload: dict) -> None:
(state_dir / "gateway.lifecycle.json").write_text(json.dumps(payload))
+
+
+# ---------------------------------------------------------------------------
+# Multiplex-only: the root slot inherits every named slot's autostart intent
+# ---------------------------------------------------------------------------
+
+
+def test_a_named_slots_autostart_intent_boots_the_root_slot(tmp_path: Path) -> None:
+ """An image only ever driven as `hermes -p coder gateway start` has no root state at all.
+ Named slots are now registered DOWN unconditionally (one gateway per container), so without
+ the root slot inheriting their intent the container boots with ZERO gateways while every
+ action reports "registered" — healthy-looking and completely dark."""
+ hermes_home = tmp_path / "data"
+ hermes_home.mkdir()
+ _make_profile(hermes_home, "coder", state=None, desired_state="running")
+
+ actions = reconcile_profile_gateways(
+ hermes_home=hermes_home, scandir=tmp_path / "svc", dry_run=True, container_argv=())
+
+ by_profile = {a.profile: a for a in actions}
+ assert by_profile["default"].action == "started", "something must serve this container"
+ assert by_profile["default"].folded_into_root is True
+ assert by_profile["coder"].action == "registered" and by_profile["coder"].folded_into_root is True
+
+
+def test_a_stopped_fleet_still_boots_nothing(tmp_path: Path) -> None:
+ """Control: no autostart intent anywhere means no gateway is started — the crash-loop guard
+ and the operator's `gateway stop` both keep working."""
+ hermes_home = tmp_path / "data"
+ hermes_home.mkdir()
+ _seed_default_root(hermes_home, state="stopped")
+ _make_profile(hermes_home, "coder", state=None, desired_state="stopped")
+ _make_profile(hermes_home, "ops", state=None, desired_state="startup_failed")
+
+ actions = reconcile_profile_gateways(
+ hermes_home=hermes_home, scandir=tmp_path / "svc", dry_run=True, container_argv=())
+
+ assert [a.action for a in actions] == ["registered"] * 3
+ assert not any(a.folded_into_root for a in actions)
diff --git a/tests/hermes_cli/test_cron_fire_dashboard.py b/tests/hermes_cli/test_cron_fire_dashboard.py
index e5736e6ef7c..9294c9ba587 100644
--- a/tests/hermes_cli/test_cron_fire_dashboard.py
+++ b/tests/hermes_cli/test_cron_fire_dashboard.py
@@ -279,11 +279,12 @@ def test_fire_endpoint_multiplex_reads_port_from_default_listener(tmp_path, monk
url = _web_server_cron._gateway_fire_endpoint("worker_alpha", worker_home)
assert url == "http://127.0.0.1:8650/p/worker_alpha/api/cron/fire"
- # The GATEWAY_MULTIPLEX_PROFILES env override is still honored (parity
- # with gateway/config.py): forcing it off restores per-profile routing.
+ # Forcing the retired opt-out off no longer restores per-profile routing: multiplex-only
+ # means the secondary has no listener of its own, so a fire URL aimed at its port would
+ # reach nothing. The /p/<profile>/ mirror on the default listener is the only live target.
monkeypatch.setenv("GATEWAY_MULTIPLEX_PROFILES", "0")
assert _web_server_cron._gateway_fire_endpoint("worker_alpha", worker_home) == (
- "http://127.0.0.1:8702/api/cron/fire"
+ "http://127.0.0.1:8650/p/worker_alpha/api/cron/fire"
)
diff --git a/tests/hermes_cli/test_gateway_enroll_multiplex_warning.py b/tests/hermes_cli/test_gateway_enroll_multiplex_warning.py
index 31a4d539b50..7b404c8a14f 100644
--- a/tests/hermes_cli/test_gateway_enroll_multiplex_warning.py
+++ b/tests/hermes_cli/test_gateway_enroll_multiplex_warning.py
@@ -56,7 +56,10 @@ def test_fires_for_secondary_when_default_root_has_multiplex_on(topology, monkey
assert "SECONDARY profile" in out
-def test_silent_when_multiplex_off_in_default_root(topology, monkeypatch):
+def test_the_retired_opt_out_still_warns_a_secondary(topology, monkeypatch):
+ """``gateway.multiplex_profiles: false`` is retired: the gateway multiplexes anyway, so a
+ secondary IS served by the default listener and must still be told its relay URLs are
+ process-level. Staying silent here made this surface contradict the running gateway."""
(topology / "config.yaml").write_text(
"gateway:\n multiplex_profiles: false\n", encoding="utf-8"
)
@@ -64,8 +67,8 @@ def test_silent_when_multiplex_off_in_default_root(topology, monkeypatch):
fired, out = _run()
- assert fired is False
- assert out == ""
+ assert fired is True
+ assert "SECONDARY profile of a multiplexed gateway" in out
def test_silent_for_default_profile_even_with_multiplex_on(topology, monkeypatch):
@@ -89,7 +92,8 @@ def test_env_override_forces_multiplex_on_without_config_flag(topology, monkeypa
assert fired is True
-def test_env_override_off_wins_over_config_flag(topology, monkeypatch):
+def test_the_env_override_is_retired_too(topology, monkeypatch):
+ """``GATEWAY_MULTIPLEX_PROFILES=false`` is the same retired opt-out by another spelling."""
(topology / "config.yaml").write_text(
"gateway:\n multiplex_profiles: true\n", encoding="utf-8"
)
@@ -98,7 +102,7 @@ def test_env_override_off_wins_over_config_flag(topology, monkeypatch):
fired, _ = _run()
- assert fired is False
+ assert fired is True
def test_silent_for_unrelated_dir_named_profiles(topology, tmp_path, monkeypatch):
diff --git a/tests/hermes_cli/test_gateway_migrate_compensator_resume.py b/tests/hermes_cli/test_gateway_migrate_compensator_resume.py
new file mode 100644
index 00000000000..d5d69d4064e
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_migrate_compensator_resume.py
@@ -0,0 +1,122 @@
+"""The compensator's outcome, and a stranded host's recovery, under the flipped host lock.
+
+Both scenarios are about states the PR itself can create, so the liveness these tests assert is
+the REAL one: a "started" gateway writes the pid file + runtime record a live gateway writes, and
+``gateway.status`` reads them back. Only the service manager is faked (the seam the migration
+suite already fakes).
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+import hermes_constants
+from hermes_cli import gateway_migrate as gm
+
+
+def _write_live_gateway(home: Path, served: list[str] | None = None) -> None:
+ record = {"pid": os.getpid(), "hermes_home": str(home), "gateway_state": "running"}
+ if served is not None:
+ record["served_profiles"] = served
+ (home / "gateway.pid").write_text(json.dumps({"pid": os.getpid(), "hermes_home": str(home)}))
+ (home / "gateway_state.json").write_text(json.dumps(record))
+
+
+def stranded(tmp_path, monkeypatch):
+ """A host mid-migration: manifest on disk, both secondaries' units already uninstalled,
+ nothing serving. Exactly what an apply that died in ``_wait_for_served`` leaves behind."""
+ root = tmp_path / "home" / ".hermes"
+ for sub in ("profiles/coder", "profiles/ops"):
+ (root / sub).mkdir(parents=True)
+ (root / sub / "SOUL.md").write_text("x\n", encoding="utf-8")
+ (root / "config.yaml").write_text("gateway:\n multiplex_profiles: true\n", encoding="utf-8")
+ (root / ".env").write_text("TELEGRAM_BOT_TOKEN=111111:shared\n", encoding="utf-8")
+ monkeypatch.setenv("HOME", str(tmp_path / "home"))
+ monkeypatch.setenv("HERMES_HOME", str(root))
+ monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path / "state"))
+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "locks"))
+ for name in ("TELEGRAM_BOT_TOKEN", "DISCORD_BOT_TOKEN", "GATEWAY_MULTIPLEX_PROFILES"):
+ monkeypatch.delenv(name, raising=False)
+ monkeypatch.setattr(hermes_constants, "_default_hermes_root_memo", None)
+ assert str(hermes_constants.get_default_hermes_root()).startswith(str(tmp_path))
+
+ (root / gm.MANIFEST_NAME).write_text(json.dumps({
+ "version": 1, "flag_was": False,
+ "default": {"profile": "default", "home": str(root), "pid": None, "services": []},
+ "secondaries": [
+ {"profile": "coder", "home": str(root / "profiles/coder"), "pid": 4101,
+ "services": [{"kind": "systemd", "system": False}]},
+ {"profile": "ops", "home": str(root / "profiles/ops"), "pid": 4102,
+ "services": [{"kind": "systemd", "system": False}]},
+ ],
+ }))
+
+ ops: list[tuple[str, str]] = []
+ state = SimpleNamespace(root=root, ops=ops, start_succeeds=True)
+
+ def _service_op(kind, system, verb, home, *, run_as_user=None):
+ name = hermes_constants.profile_name_for_home(home) or "default"
+ ops.append((name, verb))
+ if verb in ("start", "restart") and name == "default" and state.start_succeeds:
+ _write_live_gateway(root, ["default", "coder", "ops"])
+
+ import gateway.status as status
+ monkeypatch.setattr(status, "_read_process_cmdline", lambda pid: "hermes gateway run")
+ monkeypatch.setattr(gm, "_installed_services", lambda home: [])
+ monkeypatch.setattr(gm, "_service_op", _service_op)
+ monkeypatch.setattr(gm, "_host_supports_migration", lambda: None)
+ monkeypatch.setattr(gm, "_preflight_apply", lambda plan, target, run_as_user: None)
+ # raising=False so this same file runs against a tree without the constant (A/B).
+ monkeypatch.setattr(gm, "_COMPENSATOR_WAIT_SECONDS", 1.0, raising=False)
+ return state
+
+
+def test_the_compensator_restores_one_gateway_and_never_rebuilds_the_fleet(stranded, capsys):
+ """Design (a): the flipped host lock forbids N per-profile gateways, and the compensator
+ clears the served record first — so every secondary it used to start would lose the flock
+ race and respawn at exit 75 forever. It restores the ONE gateway the topology allows."""
+ assert gm.rollback_migration(stranded.root) is True
+ out = capsys.readouterr().out
+
+ started = [(name, verb) for name, verb in stranded.ops if verb in ("install", "start", "restart")]
+ assert all(name == "default" for name, _ in started), f"a secondary gateway was rebuilt: {started}"
+ assert "Restored the per-profile gateways" not in out
+ assert "coder, ops" in out and "NOT reinstalled" in out
+ assert not (stranded.root / gm.MANIFEST_NAME).exists()
+
+
+def test_the_compensator_reports_failure_when_no_gateway_comes_up(stranded, capsys):
+ """A service-manager ``start`` that returns is not proof of a live gateway: returning True on
+ it printed '✓ Restored' over a unit respawning every 5s at ExecMainStatus=75."""
+ stranded.start_succeeds = False
+ assert gm.rollback_migration(stranded.root) is False
+ out = capsys.readouterr().out
+ assert "no gateway confirmed serving this host" in out
+ assert "Compensation incomplete" in out
+ assert (stranded.root / gm.MANIFEST_NAME).exists(), "the manifest must survive for the next resume"
+
+
+def test_a_preflight_blocker_can_no_longer_trap_a_host_that_is_mid_migration(stranded, capsys):
+ """BLOCKER 3: the only documented recovery is 're-run, it resumes'. A blocker that appears
+ AFTER the units are gone (here: both profiles ending up on one bot token) used to make that
+ re-run exit 1 forever, with --standalone gone and no rollback command left."""
+ for name in ("coder", "ops"):
+ (stranded.root / "profiles" / name / ".env").write_text(
+ "TELEGRAM_BOT_TOKEN=111111:shared\n", encoding="utf-8")
+ plan = gm.build_migration_plan()
+ assert plan.blocked and plan.manifest is not None, "the premise: blocked AND mid-migration"
+
+ with pytest.raises(SystemExit) as exc:
+ gm.cmd_migrate(SimpleNamespace(multiplex=True, dry_run=False, yes=True))
+ assert exc.value.code == 0, "the blocked gate must not refuse a host that is already mid-migration"
+ out = capsys.readouterr().out
+ assert "resuming the migration recorded in" in out
+ assert "Preflight findings" in out, "the checks still RUN and are reported"
+ assert str(stranded.root / gm.MANIFEST_NAME) in out
+ assert "serves 3 profiles" in out and not (stranded.root / gm.MANIFEST_NAME).exists()
diff --git a/tests/hermes_cli/test_gateway_migrate_converged_host.py b/tests/hermes_cli/test_gateway_migrate_converged_host.py
new file mode 100644
index 00000000000..32f72ef8016
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_migrate_converged_host.py
@@ -0,0 +1,103 @@
+"""A CONVERGED host is a no-op for ``hermes gateway migrate --multiplex``, run after run.
+
+Driven through the REAL topology path, not stubbed per-profile PIDs: a live host rendezvous
+record + the per-profile ``gateway_state.json`` the multiplexer stamps, so
+``gateway.status.live_gateway_pid_for_home`` genuinely answers with the HOST gateway's PID for
+every secondary (that is ``_host_gateway_serves_home`` working as designed). Stubbing PIDs by
+profile NAME is what let the "half-migrated converged host" defect hide behind green CI: the
+fixture simply never produced the value the reporting path produces.
+
+Only the WIRE is faked (the owner's ``identify`` answer over its control socket); every predicate
+under test — ownership, the plan's topology verdict, what the apply signals — is the real one.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+
+import pytest
+
+import hermes_constants
+from hermes_cli import gateway_migrate as gm
+
+
+def converged_host(tmp_path, monkeypatch):
+ """default + coder + ops, all served by ONE live host gateway (this process).
+
+ Returns the root home. ``signals`` on the returned object records every service operation and
+ process stop the migration would perform — a converged host must produce none.
+ """
+ root = tmp_path / "home" / ".hermes"
+ for sub in ("profiles/coder", "profiles/ops"):
+ (root / sub).mkdir(parents=True)
+ (root / sub / "SOUL.md").write_text("x\n", encoding="utf-8")
+ (root / "config.yaml").write_text("model:\n default: x\n", encoding="utf-8")
+ monkeypatch.setenv("HOME", str(tmp_path / "home"))
+ monkeypatch.setenv("HERMES_HOME", str(root))
+ monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path / "state"))
+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "locks"))
+ monkeypatch.delenv("GATEWAY_MULTIPLEX_PROFILES", raising=False)
+ monkeypatch.setattr(hermes_constants, "_default_hermes_root_memo", None)
+ assert str(hermes_constants.get_default_hermes_root()).startswith(str(tmp_path))
+
+ served = ["default", "coder", "ops"]
+ pid = os.getpid()
+ # What a live multiplexer leaves on disk: its own pid file + runtime record in the launch
+ # home, and a runtime record stamped into EVERY served profile's home.
+ (root / "gateway.pid").write_text(json.dumps({"pid": pid, "hermes_home": str(root)}))
+ (root / "gateway_state.json").write_text(json.dumps(
+ {"pid": pid, "hermes_home": str(root), "gateway_state": "running", "served_profiles": served}))
+ for name in ("coder", "ops"):
+ home = root / "profiles" / name
+ (home / "gateway_state.json").write_text(json.dumps(
+ {"pid": pid, "hermes_home": str(home), "gateway_state": "running"}))
+
+ import gateway.status as status
+ from gateway import host_attach, host_rendezvous as hr
+ monkeypatch.setattr(status, "_read_process_cmdline", lambda p: "hermes gateway run")
+ # The WIRE only: the owner's control socket answer. Everything that reads it is real.
+ monkeypatch.setattr("gateway.control_socket.identify_gateway",
+ lambda home: {"pid": pid, "hermes_home": str(root), "served_profiles": served})
+ hr.publish_record(hr.ROLE_GATEWAY, profiles=tuple(served), home=str(root))
+ host_attach.invalidate_host_gateway_cache()
+
+ signals: list[tuple] = []
+ monkeypatch.setattr(gm, "_service_op",
+ lambda kind, system, verb, home, **kw: signals.append(("service", verb, str(home))))
+ monkeypatch.setattr(gm, "_stop_gateway_process", lambda home: signals.append(("stop", str(home))))
+ monkeypatch.setattr(gm, "_spawn_detached_gateway", lambda home: signals.append(("spawn", str(home))) or True)
+ monkeypatch.setattr(gm, "_host_supports_migration", lambda: None)
+ yield type("Fixture", (), {"root": root, "signals": signals, "pid": pid, "served": served})
+ hr.clear_record(hr.ROLE_GATEWAY)
+
+
+def test_the_host_gateway_pid_is_reported_for_every_secondary(converged_host):
+ """Premise of the defect, asserted so the test cannot silently stop exercising it: the
+ topology reporter DOES hand the host gateway's PID to every profile it serves."""
+ root = converged_host.root
+ for name in ("coder", "ops"):
+ assert gm._live_gateway_pid(root / "profiles" / name) == converged_host.pid
+
+
+def test_a_converged_host_is_already_multiplexed_and_owns_nothing(converged_host):
+ plan = gm.build_migration_plan()
+ assert [p.name for p in plan.standalone_secondaries] == []
+ assert all(p.pid is None for p in plan.secondaries), "a served profile does not OWN the host gateway"
+ assert plan.default.pid == converged_host.pid, "the launch home does own it"
+ assert plan.already_multiplexed and not plan.interrupted
+ assert not plan.eligible_for_migration()
+
+
+def test_three_consecutive_runs_signal_nothing(converged_host, capsys):
+ """The update hook and the explicit command, three times over, on an untouched host."""
+ from types import SimpleNamespace
+ for _ in range(3):
+ gm.maybe_auto_migrate_after_update()
+ gm.cmd_migrate(SimpleNamespace(multiplex=True, dry_run=False, yes=True)) # returns, never exits
+ out = capsys.readouterr().out
+ assert converged_host.signals == [], f"a converged host was signalled: {converged_host.signals}"
+ assert "Half-migrated" not in out and "SIGTERM" not in out
+ assert "already multiplexing" in out