Skip to content

The agent that grows with you

gateway: lifecycle verbs mean "the one host multiplexer"

teknium1a20a88398f8e
diff --git a/gateway/host_attach.py b/gateway/host_attach.py
new file mode 100644
index 00000000000..4a3d7215ac6
--- /dev/null
+++ b/gateway/host_attach.py
@@ -0,0 +1,215 @@
+"""Is there ONE live host gateway, and does it already serve this profile?
+
+Multiplex-only (Teknium ruling): exactly one ``hermes gateway run`` per host, multiplexing every
+profile. The lifecycle verbs therefore answer a different question than they used to — not "does
+THIS home hold a ``gateway.pid``?" but "is the host process live, and is this profile in its served
+set?" — and when it is not, they ask that process to serve the profile instead of starting a second
+one. Four outcomes, in order:
+
+* ``ATTACH`` — a live host gateway already serves this profile. Nothing to start; exit 0.
+* ``RESCAN``→ATTACH — it does not serve it yet: ask it to reconcile ``profiles/`` now (control
+ socket ``rescan-profiles``) and attach once the answer includes us.
+* ``REPLACE_HOST`` — ``--replace`` names the host process as the target, whichever home launched it.
+* ``REFUSE`` — a live host gateway exists and cannot be made to serve this profile. Never
+ start a second one silently.
+
+**The attach channel is the OWNER's control socket, never ours.** Ordering matters: the owner
+publishes its rendezvous record when it claims its PID file and binds its control socket a moment
+later (``gateway/run.py``: claim → socket), so for a short window the record exists and the channel
+does not. A reader that took "no socket" for "no owner" would start exactly the second gateway this
+module prevents. Hence: the record's own ``profiles`` list answers ATTACH with no channel at all,
+and only the RESCAN path needs the channel — it waits a bounded :data:`ATTACH_CHANNEL_WAIT_S` for it
+to appear. Nothing here depends on the *calling* process having started anything.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import time
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Optional
+
+logger = logging.getLogger(__name__)
+
+#: How long a caller waits for the owner's control socket after seeing its record (see module doc).
+ATTACH_CHANNEL_WAIT_S = 5.0
+_CHANNEL_POLL_S = 0.25
+
+START = "start"
+ATTACH = "attach"
+REFUSE = "refuse"
+REPLACE_HOST = "replace-host"
+
+
+def _normalize(name: str) -> str:
+ try:
+ from hermes_cli.profiles import normalize_profile_name
+
+ return normalize_profile_name(name or "default")
+ except Exception:
+ return (name or "default").strip().lower()
+
+
+def profile_name_for_home(home: Path | str) -> str:
+ """Profile a home belongs to; the root/default home is ``'default'`` (not ``None``)."""
+ from gateway.status import _profile_name_for_home
+
+ return _profile_name_for_home(Path(home)) or "default"
+
+
+@dataclass(frozen=True)
+class HostGateway:
+ """The one live host gateway: who it is, where it was launched from, what it serves."""
+
+ pid: int
+ home: Path
+ profiles: tuple[str, ...]
+
+ def serves(self, profile: str) -> bool:
+ wanted = _normalize(profile)
+ return any(_normalize(p) == wanted for p in self.profiles)
+
+ @property
+ def profile_label(self) -> str:
+ return profile_name_for_home(self.home)
+
+ def describe(self) -> str:
+ served = ", ".join(self.profiles) if self.profiles else "unknown"
+ return f"PID {self.pid} (launched by profile '{self.profile_label}'; serves: {served})"
+
+
+def _record_home(record) -> Path:
+ """Home the owner was launched from. Records written before the field existed fall back to the
+ default root — the home every pre-record multiplexer ran under."""
+ from hermes_constants import get_default_hermes_root
+
+ return Path(record.home) if getattr(record, "home", "") else Path(get_default_hermes_root())
+
+
+def _identify(home: Path) -> Optional[dict]:
+ try:
+ from gateway.control_socket import identify_gateway
+
+ return identify_gateway(home)
+ except Exception:
+ logger.debug("host gateway identify failed for %s", home, exc_info=True)
+ return None
+
+
+def _served_from_identity(identity: dict) -> tuple[str, ...]:
+ """Served set from a live ``identify``. A STANDALONE gateway publishes no ``served_profiles``;
+ it serves its own profile and nothing else, which is not the same as "unknown"."""
+ served = identity.get("served_profiles")
+ if isinstance(served, list) and served:
+ return tuple(str(p) for p in served)
+ return (str(identity.get("profile") or "default"),)
+
+
+def host_gateway(*, wait_for_channel: float = 0.0) -> Optional[HostGateway]:
+ """The one live host gateway, or ``None``.
+
+ The served set comes from the owner's control socket when it answers (live and authoritative),
+ else from the record it published (available from the PID claim onward).
+ """
+ from gateway import host_rendezvous as hr
+
+ record = hr.read_record(hr.ROLE_GATEWAY)
+ if record is None:
+ return None
+ home = _record_home(record)
+ deadline = time.monotonic() + max(0.0, wait_for_channel)
+ while True:
+ identity = _identify(home)
+ if isinstance(identity, dict) and identity.get("pid") == record.pid:
+ return HostGateway(record.pid, home, _served_from_identity(identity))
+ if time.monotonic() >= deadline:
+ break
+ time.sleep(_CHANNEL_POLL_S)
+ # No channel yet (or ever): the record still proves an owner when PID + createTime match.
+ if not hr.liveness_is_proven(record):
+ return None
+ return HostGateway(record.pid, home, tuple(record.profiles))
+
+
+def host_gateway_serving(profile: str, *, wait_for_channel: float = 0.0) -> Optional[HostGateway]:
+ """The host gateway when it is live AND serves ``profile`` — true for ``default`` too."""
+ gateway = host_gateway(wait_for_channel=wait_for_channel)
+ return gateway if gateway is not None and gateway.serves(profile) else None
+
+
+def request_serve_profile(profile: str, *, timeout: float = 8.0) -> Optional[HostGateway]:
+ """Ask the live host gateway to reconcile ``profiles/`` now; return it once it serves
+ ``profile``. ``None`` when nobody answered or the answer still excludes the profile."""
+ gateway = host_gateway(wait_for_channel=ATTACH_CHANNEL_WAIT_S)
+ if gateway is None or gateway.serves(profile):
+ return gateway
+ try:
+ from gateway.control_socket import rescan_gateway_profiles
+
+ answer = rescan_gateway_profiles(gateway.home, timeout=timeout)
+ except Exception:
+ logger.debug("host gateway rescan failed", exc_info=True)
+ return None
+ if not isinstance(answer, dict) or answer.get("multiplex") is False:
+ return None
+ served = answer.get("served_profiles")
+ rescanned = HostGateway(
+ gateway.pid, gateway.home,
+ tuple(str(p) for p in served) if isinstance(served, list) else ())
+ return rescanned if rescanned.serves(profile) else None
+
+
+@dataclass(frozen=True)
+class HostAttachDecision:
+ outcome: str
+ message: str
+ owner: Optional[HostGateway] = None
+
+
+def attach_message(gateway: HostGateway, profile: str) -> str:
+ return (
+ f"✓ The host gateway already serves profile '{profile}' — nothing to start.\n"
+ f" {gateway.describe()}\n"
+ f" One gateway per host serves every profile; manage it with "
+ f"`hermes -p {gateway.profile_label} gateway restart`.")
+
+
+def _refuse_message(gateway: HostGateway, profile: str) -> str:
+ return (
+ f"❌ A gateway already owns this host and will not serve profile '{profile}'.\n"
+ f" {gateway.describe()}\n"
+ f" Exactly one gateway per host serves every profile, so starting a second one\n"
+ f" would double-bind this profile's platforms.\n"
+ f" Fold this profile into it: hermes gateway migrate --multiplex\n"
+ f" Or take the host over: hermes gateway run --replace")
+
+
+def decide(our_home: Path, *, replace: bool = False) -> HostAttachDecision:
+ """Attach, rescan-then-attach, replace or refuse — never a second gateway.
+
+ Never raises: a broken probe degrades to ``START``, i.e. exactly the pre-rendezvous behaviour.
+ """
+ profile = profile_name_for_home(our_home)
+ try:
+ gateway = host_gateway()
+ except Exception:
+ logger.debug("host gateway probe failed; starting as before", exc_info=True)
+ return HostAttachDecision(START, "")
+ if gateway is None or gateway.pid == os.getpid():
+ return HostAttachDecision(START, "")
+ if replace:
+ # --replace is explicit authority over the host role; the target is the host process,
+ # whichever home launched it.
+ return HostAttachDecision(REPLACE_HOST, "", gateway)
+ if gateway.serves(profile):
+ return HostAttachDecision(ATTACH, attach_message(gateway, profile), gateway)
+ try:
+ attached = request_serve_profile(profile)
+ except Exception:
+ logger.debug("host gateway rescan request failed", exc_info=True)
+ attached = None
+ if attached is not None:
+ return HostAttachDecision(ATTACH, attach_message(attached, profile), attached)
+ return HostAttachDecision(REFUSE, _refuse_message(gateway, profile), gateway)
diff --git a/gateway/host_rendezvous.py b/gateway/host_rendezvous.py
index 1e96d358da2..a4aea74aa9e 100644
--- a/gateway/host_rendezvous.py
+++ b/gateway/host_rendezvous.py
@@ -84,10 +84,17 @@ class HostRecord:
token_fingerprint: str
profiles: tuple[str, ...]
updated_at: str
+ #: HERMES_HOME the owner was launched from. The attach channel (``gateway.control_socket``) is
+ #: keyed by home, so without it a client can only guess the default root — wrong as soon as a
+ #: named profile launches the host process. Absent in records written before this field; added
+ #: WITHOUT a protocol bump on purpose, because a bump would make every live owner's record read
+ #: as stale and a second gateway would start.
+ home: str = ""
def to_json(self) -> dict[str, Any]:
return {
"role": self.role,
+ "home": self.home,
"pid": self.pid,
"createTime": self.create_time,
"host": self.host,
@@ -120,6 +127,7 @@ class HostRecord:
token_fingerprint=str(payload.get("tokenFingerprint") or ""),
profiles=tuple(str(p) for p in profiles if isinstance(p, str)) if isinstance(profiles, list) else (),
updated_at=str(payload.get("updatedAt") or ""),
+ home=str(payload.get("home") or ""),
)
@@ -379,10 +387,13 @@ def publish_record(
port: Optional[int] = None,
profiles: Sequence[str] = (),
token: Optional[str] = None,
+ home: str = "",
) -> Optional[HostRecord]:
"""Publish this process as the host owner of ``role``. ``None`` when the write failed.
``token`` (serve) is persisted 0600 next to the record and only its fingerprint is published.
+ ``home`` is the launch HERMES_HOME — the key an attaching client needs to reach this owner's
+ control socket.
"""
role = _validated_role(role)
record = HostRecord(
@@ -395,6 +406,7 @@ def publish_record(
token_fingerprint=token_fingerprint(token or ""),
profiles=tuple(str(p) for p in profiles),
updated_at=datetime.now(timezone.utc).isoformat(),
+ home=str(home or ""),
)
try:
record_path(role).parent.mkdir(parents=True, exist_ok=True)
diff --git a/gateway/run.py b/gateway/run.py
index b7c9c25d0fc..5541c8de588 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -4913,6 +4913,24 @@ def _replace_target_belongs_to_other_profile(existing_pid: int) -> bool:
restart loop). Ownership is decided by the persisted identity record ALONE, bound to the live target
by exact PID + start-time; live argv can never PROVE ownership (no HERMES_HOME), it is only a
consistency check. Missing, legacy, conflicting or unprovable identity → refuse (fail closed)."""
+ # Multiplex-only: the ONE host gateway serving this profile IS this profile's gateway, whatever
+ # home launched it — `hermes -p X gateway run --replace` means "replace the process serving X".
+ # Argv and HERMES_HOME can never prove that (the host singleton runs one home's argv while
+ # serving every profile), so the live served set answers first; everything below stays the
+ # fail-closed rule for a host with no usable record.
+ try:
+ from gateway.host_attach import host_gateway, profile_name_for_home
+
+ owner = host_gateway()
+ if owner is not None and owner.pid == existing_pid and owner.serves(
+ profile_name_for_home(get_hermes_home())):
+ logger.warning(
+ "--replace target PID %s is the host gateway serving %d profile(s) (%s); "
+ "replacing it restarts the host process for all of them.",
+ existing_pid, len(owner.profiles), ", ".join(owner.profiles) or "unknown")
+ return False
+ except Exception:
+ logger.debug("host served-set ownership probe failed for PID %s", existing_pid, exc_info=True)
# On Windows there is no systemd/launchd service query at all (_get_service_pids() returns an empty
# set), so a gateway supervised by a Scheduled Task / Startup VBS looks like an unsupervised orphan to
# the process scan (#86098). The same holds on every platform for a healthy gateway launched standalone
@@ -5050,14 +5068,16 @@ async def _start_gateway_replace_existing_instance(existing_pid: int, replace: b
if not replace:
hermes_home = str(get_hermes_home())
logger.error(
- "Another gateway instance is already running (PID %d, HERMES_HOME=%s). "
- "Use 'hermes gateway restart' to replace it, or 'hermes gateway stop' first.",
+ "Another gateway instance is already running (PID %d, HERMES_HOME=%s) and did not "
+ "publish a host record this process could attach to.",
existing_pid, hermes_home)
print(
- f"\n❌ Gateway already running (PID {existing_pid}).\n"
- f" Use 'hermes gateway restart' to replace it,\n"
- f" or 'hermes gateway stop' to kill it first.\n"
- f" Or use 'hermes gateway run --replace' to auto-replace.\n")
+ f"\n❌ A gateway already owns this host (PID {existing_pid}).\n"
+ f" One gateway per host serves every profile, so there is nothing to start here.\n"
+ f" Attach is impossible: PID {existing_pid} published no usable host record\n"
+ f" (an older build, or an unwritable lock directory).\n"
+ f" Take the host over: hermes gateway run --replace\n"
+ f" Or stop it first: hermes gateway stop\n")
return False
# Never signal a process not provably ours (a poisoned PID record → cross-profile restart loop).
@@ -5277,7 +5297,8 @@ def _claim_host_gateway_role() -> None:
try:
outcome, error = hr.claim_host_lock(hr.ROLE_GATEWAY)
if outcome is hr.HostLockOutcome.ACQUIRED:
- hr.publish_record(hr.ROLE_GATEWAY, profiles=hr.served_profiles())
+ hr.publish_record(
+ hr.ROLE_GATEWAY, profiles=hr.served_profiles(), home=str(get_hermes_home()))
# SIGTERM (systemd stop, docker stop, the update relaunch) does not run atexit.
hr.cleanup_on_exit(hr.ROLE_GATEWAY)
return
@@ -5296,6 +5317,56 @@ def _claim_host_gateway_role() -> None:
logger.debug("host gateway rendezvous failed", exc_info=True)
+def _refresh_host_gateway_record(runner) -> None:
+ """Republish the host record once the attach channel is bound and multiplex is settled.
+
+ The claim-time publish can only guess the served set from config — the runner settles the
+ implicit default itself. Republishing here also means a record that names a served profile is
+ backed by a control socket that is already answering.
+ """
+ from gateway import host_rendezvous as hr
+
+ try:
+ if not hr.owns_host_lock(hr.ROLE_GATEWAY):
+ return
+ served = runner.served_profile_names() if getattr(
+ runner.config, "multiplex_profiles", False) else []
+ hr.publish_record(
+ hr.ROLE_GATEWAY,
+ profiles=tuple(served) or hr.served_profiles(),
+ home=str(get_hermes_home()))
+ except Exception:
+ logger.debug("host gateway record refresh failed", exc_info=True)
+
+
+async def _host_attach_or_none(replace: bool) -> Optional[bool]:
+ """Attach / rescan / refuse against the ONE host gateway; ``None`` = start normally.
+
+ Returns ``True`` when this invocation is satisfied by the running host process (exit 0, nothing
+ spawned) and ``False`` when it must refuse. The per-home duplicate guard below cannot answer
+ this at all: another profile's gateway lives in another home, so it sees no PID and starts a
+ second process — the shape multiplex-only forbids.
+ """
+ from gateway.host_attach import ATTACH, REFUSE, REPLACE_HOST, decide
+
+ decision = decide(get_hermes_home(), replace=replace)
+ if decision.outcome == ATTACH:
+ logger.info("Attaching to the host gateway instead of starting a second one: %s",
+ decision.owner.describe() if decision.owner else "unknown")
+ print(decision.message)
+ return True
+ if decision.outcome == REFUSE:
+ logger.error("Refusing to start a second gateway on this host: %s",
+ decision.owner.describe() if decision.owner else "unknown")
+ print(decision.message)
+ return False
+ if decision.outcome == REPLACE_HOST and decision.owner is not None:
+ # --replace names the HOST process, whichever home launched it.
+ if not await _start_gateway_replace_existing_instance(decision.owner.pid, True):
+ return False
+ return None
+
+
async def _start_gateway_start_control_socket(runner):
"""Start the gateway control socket (identify/status/pause-for-update); None when unavailable."""
import atexit
@@ -5508,7 +5579,13 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =
from gateway.code_skew import record_boot_fingerprint
record_boot_fingerprint()
- # Duplicate-instance guard scoped to HERMES_HOME; distinct-home multi-profile setups coexist.
+ # Multiplex-only: the ONE host gateway decides first. Attach to it, make it serve this profile,
+ # replace it (--replace) or refuse — before anything below binds a port or claims a PID file.
+ _host_decision = await _host_attach_or_none(replace)
+ if _host_decision is not None:
+ return _host_decision
+
+ # Duplicate-instance guard scoped to HERMES_HOME (the host record is absent or unusable here).
from gateway.status import get_running_pid
existing_pid = get_running_pid()
if (existing_pid is not None and existing_pid != os.getpid()
@@ -5579,6 +5656,8 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =
# Right after the PID claim (which makes us authoritative); non-fatal — consumers fall back to scan.
_control_server = await _start_gateway_start_control_socket(runner)
+ # Now the attach channel answers: republish the host record with the settled served set.
+ _refresh_host_gateway_record(runner)
def _lifecycle_record_startup() -> None:
# Report if the previous life died uncleanly (SIGKILL / OOM / VM death), then claim the
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.py
index e338370630b..f8acf8a2805 100644
--- a/gateway/run_adapters.py
+++ b/gateway/run_adapters.py
@@ -931,6 +931,12 @@ class GatewayAdapterLifecycleMixin:
self.pairing_store if name == active else PairingStore(profile=name)
)
publish_runtime_status(served_profiles=served)
+ # The host record is what a second `gateway run` reads to decide attach-vs-start; keep
+ # its served set in step with the live one (it is republished, never re-claimed).
+ from gateway.host_rendezvous import ROLE_GATEWAY, owns_host_lock, publish_record
+ if owns_host_lock(ROLE_GATEWAY):
+ from hermes_constants import get_hermes_home
+ publish_record(ROLE_GATEWAY, profiles=tuple(served), home=str(get_hermes_home()))
async def _load_secondary_profile_config(self, profile_name: str, profile_home: "Path"):
"""Hydrate + enter ``profile_home``'s scope once; return its gateway config. Raises
diff --git a/gateway/status.py b/gateway/status.py
index 5e986dc08f6..5adf97c2e11 100644
--- a/gateway/status.py
+++ b/gateway/status.py
@@ -640,17 +640,37 @@ def _command_line_belongs_to_profile(command: str, profile_home: Path) -> bool:
return not hermes_home_assignments(command_lc) or command_line_names_hermes_home(command_lc, home_lc)
+def _host_gateway_serves_home(pid: int, profile_home: Path) -> bool:
+ """Does the ONE host gateway — PID ``pid`` — serve ``profile_home``'s profile?
+
+ Argv cannot answer this: the host singleton runs ONE home's (usually bare/default) command line
+ while multiplexing every profile, so :func:`_command_line_belongs_to_profile` rejects every
+ secondary and the profile reads as "not running" while its messages are being served. The live
+ served set is the only proof; the argv rule stays as the fallback when no record exists.
+ """
+ try:
+ from gateway.host_attach import host_gateway, profile_name_for_home
+
+ owner = host_gateway()
+ except Exception:
+ return False
+ return owner is not None and owner.pid == pid and owner.serves(profile_name_for_home(profile_home))
+
+
def _record_matches_live_gateway_pid(
record: dict[str, Any], pid: int, *, expected_home: Optional[Path] = None
) -> bool:
"""True when a live PID still identifies as this gateway record. The live command line wins (a
stale record's argv must not make a recycled PID count as a gateway; with ``expected_home`` it
- must also belong to that profile); unreadable cmdline (Windows/EACCES) -> persisted record."""
+ must also belong to that profile — or serve it as the host multiplexer); unreadable cmdline
+ (Windows/EACCES) -> persisted record."""
live_cmdline = _read_process_cmdline(pid)
if not live_cmdline:
return _record_looks_like_gateway(record)
if not looks_like_gateway_runtime_command_line(live_cmdline):
return False
+ if expected_home is not None and _host_gateway_serves_home(pid, expected_home):
+ return True
return expected_home is None or _command_line_belongs_to_profile(live_cmdline, expected_home)
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index f2dd0040267..02f4c3494ff 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -3591,6 +3591,43 @@ def _running_under_gateway_supervisor() -> bool:
return is_gateway_supervisor_process()
+def host_multiplexer_serving(profile_name: str | None = None):
+ """The ONE live host gateway when it serves ``profile_name`` (default: the current profile).
+
+ Companion to :func:`named_profile_served_by_running_multiplexer`, which answers the narrower
+ "is this a SATELLITE of the default's multiplexer" and is hard-False for ``default`` — the
+ profile that usually owns the shared process. Every lifecycle guard built on it was therefore
+ blind to the host process itself. This one is true for ``default`` too, and it reports WHICH
+ profiles the host process serves. Returns a ``gateway.host_attach.HostGateway`` or None.
+ """
+ try:
+ from gateway.host_attach import host_gateway_serving
+ name = profile_name if profile_name is not None else _current_profile_name()
+ return host_gateway_serving(name or "default")
+ except Exception:
+ logger.debug("Host multiplexer probe failed", exc_info=True)
+ return None
+
+
+def _served_by_another_host_gateway(profile_name: str | None = None):
+ """The host gateway serving ``profile_name`` when it is NOT this home's own process.
+
+ The owner must never be guarded out of restarting itself: a refusal keyed on "something serves
+ you" would make `hermes gateway restart` impossible for the profile that launched the host
+ process. Guards want "ANOTHER process already serves you", which is this.
+ """
+ gateway = host_multiplexer_serving(profile_name)
+ if gateway is None:
+ return None
+ try:
+ from gateway.status import _get_process_hermes_home, _same_hermes_home
+ if _same_hermes_home(gateway.home, _get_process_hermes_home()):
+ return None
+ except Exception:
+ logger.debug("Host multiplexer home comparison failed", exc_info=True)
+ return gateway
+
+
def named_profile_served_by_running_multiplexer(profile_name: str | None = None) -> bool:
"""True when a live default multiplexer already ticks this named profile (a satellite profile has no
gateway.pid; the multiplexer fires its jobs and serves its platforms). Defaults to the current profile.
@@ -3604,6 +3641,11 @@ def named_profile_served_by_running_multiplexer(profile_name: str | None = None)
if not suffix or suffix == "default":
return False
+ # The host record answers first: it names the live host process whatever home launched it, so a
+ # multiplexer started by a named profile is visible here too.
+ if host_multiplexer_serving(suffix) is not None:
+ return True
+
try:
from hermes_constants import get_default_hermes_root
default_root = get_default_hermes_root()
@@ -3660,25 +3702,27 @@ def _named_profile_refused_under_multiplexer(force: bool = False) -> bool:
suffix = _current_profile_name()
except Exception:
return False
- if not named_profile_served_by_running_multiplexer():
+ owner = _served_by_another_host_gateway()
+ if owner is None and not named_profile_served_by_running_multiplexer():
return False
print_error(
- f"The default gateway is running as a profile multiplexer and already "
- f"serves profile '{suffix}'."
+ f"The host gateway already serves profile '{suffix}'."
)
+ if owner is not None:
+ print(f" {owner.describe()}")
print(
- " When gateway.multiplex_profiles is on, the default gateway is the\n"
- " single inbound process for every profile. Starting a separate\n"
- " gateway for this profile would double-bind its platforms (two\n"
- " pollers on one bot token, port conflicts).\n"
+ " Exactly one gateway per host is the inbound process for every\n"
+ " profile. Starting a separate gateway for this profile would\n"
+ " double-bind its platforms (two pollers on one bot token, port\n"
+ " conflicts).\n"
)
- print(" Manage the multiplexer instead (from the default profile):")
+ print(" Manage the host gateway instead:")
print()
- print(" hermes gateway restart")
+ print(f" hermes -p {owner.profile_label if owner is not None else 'default'} gateway restart")
print()
print(" Pass --force to start a separate profile gateway anyway (not")
- print(" recommended while the multiplexer is running).")
+ print(" recommended while the host gateway is running).")
return True
@@ -3701,6 +3745,31 @@ def _guard_named_profile_under_multiplexer(force: bool = False) -> None:
sys.exit(GATEWAY_FATAL_CONFIG_EXIT_CODE)
+def _attach_to_host_gateway_or_guard(force: bool = False) -> None:
+ """``gateway run`` against the ONE host gateway: attach, rescan-then-attach, or refuse.
+
+ A profile the host process already serves has nothing to run: print who serves it and exit 0
+ without spawning anything. Under a service supervisor the SAME situation exits 78 (EX_CONFIG)
+ instead — systemd (Restart=always, RestartPreventExitStatus=78) and launchd would restart-loop
+ an exit-0 unit forever, which is why the refusal used 78 in the first place.
+ """
+ if force:
+ return
+ try:
+ from gateway.host_attach import ATTACH, REFUSE, decide
+ decision = decide(get_hermes_home())
+ except Exception:
+ logger.debug("Host gateway attach probe failed", exc_info=True)
+ decision = None
+ if decision is not None and decision.outcome in (ATTACH, REFUSE):
+ print(decision.message)
+ if decision.outcome == REFUSE or _running_under_gateway_supervisor():
+ sys.exit(GATEWAY_FATAL_CONFIG_EXIT_CODE)
+ sys.exit(0)
+ # No host record (older gateway, unwritable lock dir): the config-derived refusal still applies.
+ _guard_named_profile_under_multiplexer(force=force)
+
+
def _guard_supervised_gateway_conflict(force: bool = False) -> None:
"""Refuse a foreground gateway when a service manager already supervises one: a shell-launched run
becomes a second dispatcher that escapes the cgroup, survives ``systemctl restart``, and writes the
@@ -3913,7 +3982,7 @@ def run_gateway(verbose: int = 0, quiet: bool = False, replace: bool = False, fo
"""Run the gateway in foreground. verbose 1=INFO/2+=DEBUG on stderr; quiet: no stderr logs; replace:
kill an existing instance first (avoids systemd restart loops); force: skip the supervised guard."""
_guard_official_docker_root_gateway()
- _guard_named_profile_under_multiplexer(force=force)
+ _attach_to_host_gateway_or_guard(force=force)
_guard_supervised_gateway_conflict(force=force)
_guard_existing_gateway_process_conflict(replace=replace)
sys.path.insert(0, str(PROJECT_ROOT))
@@ -4561,13 +4630,58 @@ def _cmd_uninstall(args):
_handle_no_backend("uninstall", wsl=False, s6=True)
+def _host_multiplexer_for_all_verb():
+ """The live host gateway a ``--all`` verb must target instead of sweeping every profile.
+
+ ``--all`` means "the ONE host multiplexer", not "every gateway process on this box": sweeping
+ killed a multiplexer serving N profiles and started a single gateway in its place, so a
+ per-profile command caused a host-wide outage and left exactly one profile served.
+ """
+ try:
+ from gateway.host_attach import host_gateway
+ return host_gateway()
+ except Exception:
+ logger.debug("Host gateway probe failed", exc_info=True)
+ return None
+
+
+def _host_multiplexer_is_ours(owner) -> bool:
+ try:
+ from gateway.status import _get_process_hermes_home, _same_hermes_home
+ return bool(_same_hermes_home(owner.home, _get_process_hermes_home()))
+ except Exception:
+ return False
+
+
+def _print_unfolded_gateway_note(owner) -> None:
+ """Detect-and-converge: name the per-profile gateways `--all` no longer sweeps, never kill them."""
+ try:
+ others = [pid for pid in find_gateway_pids(all_profiles=True) if pid != owner.pid]
+ except Exception:
+ return
+ if not others:
+ return
+ print(f" {len(others)} per-profile gateway process(es) still run beside it "
+ f"(PIDs: {', '.join(str(p) for p in others)}).")
+ print(" They were left running; fold them in with: hermes gateway migrate --multiplex")
+
+
def _cmd_start(args):
system = getattr(args, "system", False)
start_all = getattr(args, "all", False)
- _guard_named_profile_under_multiplexer(force=getattr(args, "force", False))
+ force = getattr(args, "force", False)
+ _guard_named_profile_under_multiplexer(force=force)
if not start_all and _dispatch_via_service_manager_if_s6("start"):
return
if start_all:
+ owner = None if force else _host_multiplexer_for_all_verb()
+ if owner is not None:
+ # Already up: `--all` has nothing to start, and the old sweep here SIGTERMed this very
+ # process before starting a single-profile replacement.
+ print(f"✓ The host gateway is already running — {owner.describe()}")
+ print(" One gateway per host serves every profile; nothing to start.")
+ _print_unfolded_gateway_note(owner)
+ return
killed = kill_gateway_processes(all_profiles=True)
if killed:
print(f"✓ Killed {killed} stale gateway process(es) across all profiles")
@@ -4587,18 +4701,23 @@ def _cmd_stop(args):
_refuse_from_inside_gateway("stop", "restart loops")
stop_all = getattr(args, "all", False)
system = getattr(args, "system", False)
- if not stop_all and not find_gateway_pids() and named_profile_served_by_running_multiplexer():
+ if not stop_all and not find_gateway_pids() and (
+ _served_by_another_host_gateway() or named_profile_served_by_running_multiplexer()):
# A served profile owns no gateway to stop; "No gateway running for this profile" (exit 0) would
- # contradict `gateway status` ("running via the default-profile multiplexer") on the same profile.
+ # contradict `gateway status` ("running via the host multiplexer") on the same profile.
# A `--force`-started separate gateway HAS a pid of its own and is stopped normally.
+ owner = _served_by_another_host_gateway()
print_error(
- f"The default gateway is running as a profile multiplexer and serves profile "
- f"'{_current_profile_name()}' — there is no separate gateway for this profile to stop."
+ f"The host gateway serves profile '{_current_profile_name()}' — there is no separate "
+ f"gateway for this profile to stop."
)
- print(" Stop or restart the multiplexer from the default profile instead:")
+ if owner is not None:
+ print(f" {owner.describe()}")
+ print(" Stop or restart the host gateway instead:")
print()
- print(" hermes gateway stop # takes every served profile offline")
- print(" hermes gateway restart")
+ owner_flag = f"-p {owner.profile_label} " if owner is not None else ""
+ 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)
# 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"):
@@ -4622,11 +4741,45 @@ def _cmd_stop(args):
print(f"✓ Stopped {get_service_name()} service")
+def _stop_host_multiplexer(owner) -> int:
+ """SIGTERM the host gateway and nothing else; returns how many processes were signalled."""
+ stopped = kill_gateway_processes()
+ if stopped:
+ return stopped
+ try:
+ terminate_pid(owner.pid, force=False)
+ return 1
+ except (ProcessLookupError, PermissionError, OSError):
+ return 0
+
+
def _restart_all(system: bool) -> None:
+ owner = _host_multiplexer_for_all_verb()
+ if owner is not None and not _host_multiplexer_is_ours(owner):
+ # `--all` means "restart the ONE host multiplexer" — and this profile does not own it.
+ # Sweeping every profile here took the host process down and replaced it with a gateway
+ # serving only this profile.
+ print_error(f"The host gateway runs under profile '{owner.profile_label}'.")
+ print(f" {owner.describe()}")
+ print(" `--all` restarts the one host multiplexer, and this profile is not its owner.")
+ print()
+ print(f" hermes -p {owner.profile_label} gateway restart --all")
+ sys.exit(GATEWAY_FATAL_CONFIG_EXIT_CODE)
+
service_stopped = _stop_installed_service(system)
- total = kill_gateway_processes(all_profiles=True) + (1 if service_stopped else 0)
- if total:
- print(f"✓ Stopped {total} gateway process(es) across all profiles")
+ if owner is not None:
+ # Stop ONLY the host process: its served set comes back with it, and any per-profile
+ # gateway a pre-migration host still runs is left alone (never auto-SIGTERMed).
+ stopped = _stop_host_multiplexer(owner)
+ total = stopped + (1 if service_stopped else 0)
+ if total:
+ print(f"✓ Stopped the host gateway (PID {owner.pid}; serves "
+ f"{', '.join(owner.profiles) or 'unknown'})")
+ _print_unfolded_gateway_note(owner)
+ else:
+ total = kill_gateway_processes(all_profiles=True) + (1 if service_stopped else 0)
+ if total:
+ print(f"✓ Stopped {total} gateway process(es) across all profiles")
_wait_for_gateway_exit(timeout=10.0, force_after=5.0)
_wait_for_api_server_port_free()
diff --git a/hermes_cli/gateway_multiplex_mode.py b/hermes_cli/gateway_multiplex_mode.py
index 0c7133bb883..7d6eb549053 100644
--- a/hermes_cli/gateway_multiplex_mode.py
+++ b/hermes_cli/gateway_multiplex_mode.py
@@ -76,16 +76,17 @@ def implicit_multiplex_blocker() -> Optional[str]:
"""Why THIS process must not multiplex on the implicit default, or None when it may.
Mirrors what makes ``hermes gateway migrate --multiplex`` refuse or leave a per-profile gateway
- in place: a named-profile gateway serves only itself; hosts whose per-profile gateways the
- preflight cannot see (s6 slots, Windows scheduled tasks) stay standalone; a secondary that still
- runs its own gateway (live process or installed service) or a preflight blocker (duplicate bot
- credential, port binder without a ``/p/<profile>/`` ingress) keeps the default standalone.
+ in place: hosts whose per-profile gateways the preflight cannot see (s6 slots, Windows
+ scheduled tasks) stay standalone; a secondary that still runs its own gateway (live process or
+ installed service) or a preflight blocker (duplicate bot credential, port binder without a
+ ``/p/<profile>/`` ingress) keeps this gateway standalone.
+
+ The launching profile's IDENTITY is deliberately not a blocker: multiplex-only means "the one
+ host process", whichever profile started it. Gating on ``active == 'default'`` made a host
+ whose only gateway runs under a named profile permanently standalone — and every lifecycle
+ verb built on "the default's multiplexer" blind to the process actually serving the host.
"""
- from hermes_cli.profiles import get_active_profile_name, profiles_to_serve
- active = get_active_profile_name() or "default"
- if active != "default":
- return (f"this is profile '{active}'s own gateway; only the default profile's gateway "
- f"multiplexes (hermes gateway migrate --multiplex folds the fleet onto it)")
+ from hermes_cli.profiles import profiles_to_serve
# Cheap and first: a single-profile install has nothing to multiplex, and the fail-closed secret
# scope the multiplexer arms buys it nothing. (Also keeps every embedded/test runner off the
# service-manager probes below.) Create a second profile and restart to start serving it.
diff --git a/tests/conftest.py b/tests/conftest.py
index d081ea2b513..4c11007e4db 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -120,6 +120,20 @@ os.environ["HERMES_TEST_ISOLATION"] = os.environ.get("HERMES_HOME", "") or "1"
#: even with this block removed.
HERMES_HOME_AT_CONFTEST_IMPORT = os.environ.get("HERMES_HOME", "")
+# ── Host-rendezvous isolation ───────────────────────────────────────────────
+# ``gateway/host_rendezvous.py`` publishes ONE record per role per OS USER, in
+# ``$HERMES_GATEWAY_LOCK_DIR`` else ``$XDG_STATE_HOME/hermes/gateway-locks`` —
+# deliberately outside HERMES_HOME, because the host singleton spans profiles.
+# Under the per-file parallel runner that directory is shared by ~40 pytest
+# subprocesses: one test that boots a real gateway publishes a record, and every
+# other file's lifecycle code then correctly attaches to a gateway that has
+# nothing to do with it. Give each pytest PROCESS its own rendezvous dir; tests
+# that want a specific record still set the variable themselves.
+if not os.environ.get("HERMES_GATEWAY_LOCK_DIR"):
+ _SESSION_LOCK_DIR = tempfile.mkdtemp(prefix="hermes-test-gateway-locks-")
+ os.environ["HERMES_GATEWAY_LOCK_DIR"] = _SESSION_LOCK_DIR
+ atexit.register(shutil.rmtree, _SESSION_LOCK_DIR, True)
+
# ── Per-file process isolation ──────────────────────────────────────────────
# Tests run via ``scripts/run_tests_parallel.py``, which spawns a fresh
@@ -499,6 +513,10 @@ def _hermetic_environment(tmp_path, monkeypatch):
(fake_hermes_home / "memories").mkdir()
(fake_hermes_home / "skills").mkdir()
monkeypatch.setenv("HERMES_HOME", str(fake_hermes_home))
+ # Per-TEST host-rendezvous dir (see the session-level block at the top): the
+ # host gateway/serve record is shared per OS user by design, so without this
+ # one test's published owner makes the next test's lifecycle code attach to it.
+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "gateway-locks"))
# Keep the subprocess-surviving isolation marker pointed at THIS test's
# home (#82770): children spawned by the test inherit it by default, so
# hermes_state's live-DB guard stays armed in them even when the test
diff --git a/tests/gateway/test_host_attach_lifecycle.py b/tests/gateway/test_host_attach_lifecycle.py
new file mode 100644
index 00000000000..3701351ff7f
--- /dev/null
+++ b/tests/gateway/test_host_attach_lifecycle.py
@@ -0,0 +1,87 @@
+"""The gateway lifecycle verbs mean "the ONE host process", not "this profile's gateway".
+
+Invariants: a second ``gateway run`` for a profile the host process already serves ATTACHES (exit 0,
+nothing spawned); one it does not serve yet triggers a rescan and then attaches; and the DEFAULT
+profile is reported as served by the host multiplexer (the predicate every lifecycle guard used to
+be hard-False on).
+"""
+
+import asyncio
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+from gateway import host_attach, host_rendezvous as hr
+from gateway import run as gateway_run
+
+
+def owner_pid(tmp_path, monkeypatch):
+ """A REAL live process standing in for the host gateway (liveness is proved, not stubbed)."""
+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "locks"))
+ child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
+ try:
+ yield child.pid
+ finally:
+ child.terminate()
+ child.wait(timeout=10)
+
+
+def _publish(pid: int, home: Path, profiles: tuple[str, ...]) -> None:
+ record = hr.HostRecord(
+ role=hr.ROLE_GATEWAY, pid=pid, create_time=hr.process_create_time(pid), host="",
+ port=None, protocol_version=hr.HOST_PROTOCOL_VERSION, token_fingerprint="",
+ profiles=profiles, updated_at="", home=str(home))
+ path = hr.record_path(hr.ROLE_GATEWAY)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(record.to_json()), encoding="utf-8")
+
+
+def test_run_for_a_served_profile_attaches_and_spawns_nothing(tmp_path, monkeypatch, owner_pid):
+ owner_home = tmp_path / "root"
+ ours = tmp_path / "root" / "profiles" / "other"
+ _publish(owner_pid, owner_home, ("default", "other"))
+ monkeypatch.setattr(gateway_run, "get_hermes_home", lambda: ours)
+
+ def _never(*a, **k):
+ raise AssertionError("a second gateway was started for an already-served profile")
+
+ monkeypatch.setattr(gateway_run, "_start_gateway_replace_existing_instance", _never)
+
+ assert asyncio.run(gateway_run._host_attach_or_none(replace=False)) is True
+
+
+def test_run_for_an_unserved_profile_rescans_then_attaches(tmp_path, monkeypatch, owner_pid):
+ owner_home = tmp_path / "root"
+ ours = tmp_path / "root" / "profiles" / "other"
+ _publish(owner_pid, owner_home, ("default",))
+ monkeypatch.setattr(gateway_run, "get_hermes_home", lambda: ours)
+ monkeypatch.setattr(host_attach, "ATTACH_CHANNEL_WAIT_S", 0.0)
+ asked: list[Path] = []
+
+ def _rescan(home, *, timeout=8.0):
+ asked.append(Path(home))
+ return {"multiplex": True, "served_profiles": ["default", "other"]}
+
+ monkeypatch.setattr("gateway.control_socket.rescan_gateway_profiles", _rescan)
+
+ assert asyncio.run(gateway_run._host_attach_or_none(replace=False)) is True
+ assert asked == [owner_home], "the rescan must reach the OWNER's home, not ours"
+
+
+def test_host_gateway_refuses_when_it_will_not_serve_the_profile(tmp_path, monkeypatch, owner_pid):
+ _publish(owner_pid, tmp_path / "root", ("default",))
+ monkeypatch.setattr(gateway_run, "get_hermes_home", lambda: tmp_path / "root" / "profiles" / "other")
+ monkeypatch.setattr(host_attach, "ATTACH_CHANNEL_WAIT_S", 0.0)
+ monkeypatch.setattr("gateway.control_socket.rescan_gateway_profiles",
+ lambda home, timeout=8.0: {"multiplex": False})
+
+ assert asyncio.run(gateway_run._host_attach_or_none(replace=False)) is False
+
+
+def test_default_profile_is_served_by_the_host_multiplexer(tmp_path, owner_pid):
+ _publish(owner_pid, tmp_path / "root", ("default", "other"))
+ assert host_attach.host_gateway_serving("default") is not None
diff --git a/tests/hermes_cli/test_gateway_host_verbs.py b/tests/hermes_cli/test_gateway_host_verbs.py
new file mode 100644
index 00000000000..568c5652a07
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_host_verbs.py
@@ -0,0 +1,70 @@
+"""``gateway start --all`` / ``restart --all`` mean "the ONE host multiplexer", not "every gateway".
+
+Base behaviour: ``--all`` SIGTERMed every gateway process on the host — including a multiplexer
+serving other profiles — and started a single gateway in its place, so a per-profile command caused
+a host-wide outage that left exactly one profile served.
+"""
+
+import json
+import subprocess
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from gateway import host_rendezvous as hr
+from hermes_cli import gateway as gw
+
+
+def host_owner(tmp_path, monkeypatch):
+ """A REAL live process published as the host gateway serving three profiles."""
+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "locks"))
+ child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
+ record = hr.HostRecord(
+ role=hr.ROLE_GATEWAY, pid=child.pid, create_time=hr.process_create_time(child.pid),
+ host="", port=None, protocol_version=hr.HOST_PROTOCOL_VERSION, token_fingerprint="",
+ profiles=("default", "ops", "coder"), updated_at="", home=str(tmp_path / "root"))
+ path = hr.record_path(hr.ROLE_GATEWAY)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(record.to_json()), encoding="utf-8")
+ try:
+ yield SimpleNamespace(pid=child.pid, home=tmp_path / "root")
+ finally:
+ child.terminate()
+ child.wait(timeout=10)
+
+
+def test_start_all_never_sweeps_a_live_host_multiplexer(host_owner, monkeypatch, capsys):
+ def _never(*a, **k):
+ raise AssertionError("start --all SIGTERMed the host multiplexer")
+
+ monkeypatch.setattr(gw, "kill_gateway_processes", _never)
+ monkeypatch.setattr(gw, "_guard_named_profile_under_multiplexer", lambda **k: None)
+ monkeypatch.setattr(gw, "_dispatch_via_service_manager_if_s6", lambda verb: False)
+ monkeypatch.setattr(gw, "_service_backend", lambda: None)
+ monkeypatch.setattr(gw, "find_gateway_pids", lambda **k: [])
+
+ gw._cmd_start(SimpleNamespace(system=False, all=True, force=False))
+
+ out = capsys.readouterr().out
+ assert "already running" in out
+ # The served set survives the verb: all three profiles are still reported as served.
+ for profile in ("default", "ops", "coder"):
+ assert profile in out
+
+
+def test_restart_all_refuses_to_sweep_a_host_multiplexer_owned_by_another_profile(
+ host_owner, monkeypatch, tmp_path):
+ def _never(*a, **k):
+ raise AssertionError("restart --all SIGTERMed another profile's host multiplexer")
+
+ monkeypatch.setattr(gw, "kill_gateway_processes", _never)
+ monkeypatch.setattr(gw, "_stop_installed_service", lambda system: False)
+ monkeypatch.setattr("gateway.status._get_process_hermes_home",
+ lambda: Path(tmp_path / "root" / "profiles" / "ops"))
+
+ with pytest.raises(SystemExit) as exc:
+ gw._restart_all(system=False)
+ assert exc.value.code == gw.GATEWAY_FATAL_CONFIG_EXIT_CODE
diff --git a/tests/hermes_cli/test_gateway_run_hard_exit.py b/tests/hermes_cli/test_gateway_run_hard_exit.py
index 7936a5b0b54..eb1e7c5eb5a 100644
--- a/tests/hermes_cli/test_gateway_run_hard_exit.py
+++ b/tests/hermes_cli/test_gateway_run_hard_exit.py
@@ -25,6 +25,7 @@ def _prepare(monkeypatch):
monkeypatch.setattr(gateway_cli, "_guard_official_docker_root_gateway", lambda: None)
monkeypatch.setattr(gateway_cli, "_guard_named_profile_under_multiplexer", lambda force=False: None)
+ monkeypatch.setattr(gateway_cli, "_attach_to_host_gateway_or_guard", lambda force=False: None)
monkeypatch.setattr(gateway_cli, "_guard_supervised_gateway_conflict", lambda force=False: None)
monkeypatch.setattr(gateway_cli, "_guard_existing_gateway_process_conflict", lambda replace=False: None)
monkeypatch.setattr(gateway_cli, "supports_systemd_services", lambda: False)
diff --git a/website/docs/developer-guide/gateway-internals.md b/website/docs/developer-guide/gateway-internals.md
index 078de91b7df..bf6c76eadbf 100644
--- a/website/docs/developer-guide/gateway-internals.md
+++ b/website/docs/developer-guide/gateway-internals.md
@@ -270,7 +270,7 @@ The gateway runs as a long-lived process, managed via:
- `systemctl` (Linux) or `launchctl` (macOS) — service management
- PID file at `~/.hermes/gateway.pid` — profile-scoped process tracking
-**Profile-scoped vs global**: `start_gateway()` uses profile-scoped PID files. Standalone (one gateway per profile), `hermes -p x gateway stop` stops only that profile's gateway. Under multiplexing there is ONE gateway process, owned by the default profile: `hermes gateway stop` on the default takes every served profile down, and `hermes -p x gateway stop` for a served secondary refuses with exit 78 (it has no gateway of its own). `hermes gateway stop --all` uses global `ps aux` scanning to kill all gateway processes (used during updates). Liveness is decided by `gateway.status.live_gateway_pid_for_home` (PID + start-time fingerprint), never bare PID existence.
+**Profile-scoped vs global**: `start_gateway()` uses profile-scoped PID files. Standalone (one gateway per profile), `hermes -p x gateway stop` stops only that profile's gateway. Under multiplexing there is ONE gateway process per host, owned by whichever profile launched it (`gateway/host_rendezvous.py` publishes its PID, home and served set; `gateway/host_attach.py` is the attach/rescan/refuse decision every lifecycle verb goes through): `hermes gateway stop` on the owner takes every served profile down, and `hermes -p x gateway stop` for a served secondary refuses with exit 78 (it has no gateway of its own). A second `gateway run` for a served profile attaches and exits 0 — under a service supervisor it exits 78 instead, so the redundant unit is parked rather than restart-looped. `hermes gateway stop --all` uses global `ps aux` scanning to kill all gateway processes (used during updates). Liveness is decided by `gateway.status.live_gateway_pid_for_home` (PID + start-time fingerprint), never bare PID existence.
## Multiplexed profiles
diff --git a/website/docs/user-guide/multi-profile-gateways.md b/website/docs/user-guide/multi-profile-gateways.md
index 654f869d6a5..e29d28b1547 100644
--- a/website/docs/user-guide/multi-profile-gateways.md
+++ b/website/docs/user-guide/multi-profile-gateways.md
@@ -64,14 +64,30 @@ automatically on crash and on user login.
## Alternative: one gateway for all profiles (multiplexing)
The model above runs **one process per profile**. The alternative is a
-**single multiplexing gateway**: the default profile's gateway becomes the sole
-inbound process and serves messages for *every* profile on the box.
+**single multiplexing gateway**: one gateway process — whichever profile
+launched it — becomes the sole inbound process and serves messages for *every*
+profile on the box.
+
+Because there is only ever one of them, the lifecycle verbs target that process
+rather than "this profile's gateway":
+
+- `hermes -p <name> gateway run` while it is live **attaches** instead of
+ starting a second process: it prints the host gateway's PID and served set and
+ exits 0. If `<name>` is not served yet, it asks the host gateway to re-scan
+ `profiles/` and attaches once the answer includes it; it refuses (non-zero)
+ only when the host gateway cannot be made to serve it.
+- `hermes gateway start --all` / `restart --all` mean *the one host
+ multiplexer*. They never sweep every gateway process on the box; a profile
+ that still runs its own gateway is reported, never killed, with the
+ `hermes gateway migrate --multiplex` one-liner.
+- `hermes gateway run --replace` takes the host role over, whichever profile
+ launched the running process.
Multiplexing is **on by default** (`gateway.multiplex_profiles` defaults to
`true`), with one safety rule: an *unset* flag is a request the default gateway
settles at boot, never a verdict. Each start it runs the same preflight as
[`hermes gateway migrate --multiplex`](#migrating-from-per-profile-gateways) and
-multiplexes only when the fold would have been safe — the default profile, two
+multiplexes only when the fold would have been safe — two
or more profiles, no secondary still running its own gateway (live process or
installed service), no duplicate bot credential, no port-binding platform
without a `/p/<profile>/` ingress, and a host the migration understands (not an
@@ -107,8 +123,8 @@ ability to restart one profile without touching the others).
### Pinning the flag
With the flag unset, the default gateway decides at each boot (above). To pin
-it, set it on the **default profile** (it owns the multiplexer) and restart its
-gateway — `true` forces multiplexing even where the boot preflight would have
+it, set it on the profile whose gateway runs as the host process (usually the
+**default profile**) and restart its gateway — `true` forces multiplexing even where the boot preflight would have
held back, `false` opts out durably:
```bash