The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a record alone never means "attach", and --replace/--force work
teknium1a10620a669a6
diff --git a/gateway/host_attach.py b/gateway/host_attach.pyindex 4a3d7215ac6..8985a1d465f 100644--- a/gateway/host_attach.py+++ b/gateway/host_attach.py@@ -17,9 +17,16 @@ one. Four outcomes, in order:publishes its rendezvous record when it claims its PID file and binds its control socket a momentlater (``gateway/run.py``: claim → socket), so for a short window the record exists and the channeldoes 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.+module prevents — but a reader that took the RECORD's word for the served set is worse: the+claim-time record is published before the process knows what it will serve, so a supervised unit+for a profile nobody serves would stand down forever. Hence the split:++* the record proves an OWNER exists (PID + createTime), and that alone never yields ATTACH;+* the served set comes ONLY from a live ``identify`` answer, waited for a bounded+ :data:`ATTACH_CHANNEL_WAIT_S`;+* owner present + served set unknown is a TRANSIENT verdict — do not start, do not park.++Nothing here depends on the *calling* process having started anything."""from __future__ import annotations@@ -66,8 +73,13 @@ class HostGateway:pid: inthome: Pathprofiles: tuple[str, ...]+ #: False when the owner has not answered ``identify`` yet: an owner exists, but which profiles+ #: it serves is UNKNOWN. Never conflate that with "serves nothing" — see the module doc.+ served_known: bool = Truedef serves(self, profile: str) -> bool:+ if not self.served_known:+ return Falsewanted = _normalize(profile)return any(_normalize(p) == wanted for p in self.profiles)@@ -76,7 +88,10 @@ class HostGateway:return profile_name_for_home(self.home)def describe(self) -> str:- served = ", ".join(self.profiles) if self.profiles else "unknown"+ if not self.served_known:+ served = "not published yet (its control socket has not answered)"+ else:+ served = ", ".join(self.profiles) if self.profiles else "nothing"return f"PID {self.pid} (launched by profile '{self.profile_label}'; serves: {served})"@@ -107,30 +122,74 @@ def _served_from_identity(identity: dict) -> tuple[str, ...]: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``.+def _identity_matches(identity, record, home: Path) -> bool:+ """Is this ``identify`` answer really the record's owner?- 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).+ PID alone is not enough: a record naming an arbitrary home makes us dial whatever listens+ there, so the answer must also agree about the home it was launched from."""+ if not isinstance(identity, dict) or identity.get("pid") != record.pid:+ return False+ reported = identity.get("hermes_home")+ if not reported:+ return True # older gateway: PID + a socket keyed by this home is all it can prove+ try:+ from gateway.status import _same_hermes_home++ return bool(_same_hermes_home(Path(str(reported)), home))+ except Exception:+ return str(reported) == str(home)+++#: A CLI invocation asks this question once per profile (``gateway status`` across N profiles,+#: doctor, the lifecycle guards); a gateway PROCESS asks it for the life of the process, so the+#: memo is time-bounded rather than permanent. Writes invalidate it eagerly.+HOST_GATEWAY_CACHE_TTL_S = 2.0+_cached_probe: Optional[tuple[float, Optional[HostGateway]]] = None+++def invalidate_host_gateway_cache() -> None:+ """Forget the memoized probe (called by ``host_rendezvous`` on every record write)."""+ global _cached_probe+ _cached_probe = None+++def _probe_host_gateway(wait_for_channel: float) -> Optional[HostGateway]:from gateway import host_rendezvous as hrrecord = hr.read_record(hr.ROLE_GATEWAY)if record is None:return None+ # Liveness BEFORE the dial. A record we cannot prove live must not make us open a socket at an+ # address it chose; proving the PID first is also what keeps a stale record from naming a peer.+ if not hr.liveness_is_proven(record):+ return Nonehome = _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:+ if _identity_matches(identity, record, home):return HostGateway(record.pid, home, _served_from_identity(identity))if time.monotonic() >= deadline:breaktime.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))+ # An owner exists and has not answered: the served set is UNKNOWN, never the record's word.+ return HostGateway(record.pid, home, (), served_known=False)+++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 and nowhere else; a record with no live+ answer behind it yields ``served_known=False`` — an owner whose served set nobody knows yet.+ """+ global _cached_probe+ now = time.monotonic()+ if wait_for_channel <= 0 and _cached_probe is not None and now - _cached_probe[0] < HOST_GATEWAY_CACHE_TTL_S:+ return _cached_probe[1]+ result = _probe_host_gateway(wait_for_channel)+ _cached_probe = (time.monotonic(), result)+ return resultdef host_gateway_serving(profile: str, *, wait_for_channel: float = 0.0) -> Optional[HostGateway]:@@ -139,10 +198,11 @@ def host_gateway_serving(profile: str, *, wait_for_channel: float = 0.0) -> Optireturn gateway if gateway is not None and gateway.serves(profile) else None-def request_serve_profile(profile: str, *, timeout: float = 8.0) -> Optional[HostGateway]:+def request_serve_profile(profile: str, *, timeout: float = 8.0,+ owner: Optional[HostGateway] = None) -> 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)+ gateway = owner if owner is not None else host_gateway(wait_for_channel=ATTACH_CHANNEL_WAIT_S)if gateway is None or gateway.serves(profile):return gatewaytry:@@ -166,6 +226,10 @@ class HostAttachDecision:outcome: strmessage: strowner: Optional[HostGateway] = None+ #: True when the verdict is a RUNTIME observation ("someone else serves me right now", "the+ #: owner has not answered yet") rather than a config-derived permanent refusal. A supervisor+ #: must RETRY a transient verdict; parking the unit on one strands the profile forever.+ transient: bool = Falsedef attach_message(gateway: HostGateway, profile: str) -> str:@@ -176,6 +240,17 @@ def attach_message(gateway: HostGateway, profile: str) -> str:f"`hermes -p {gateway.profile_label} gateway restart`.")+def _unknown_served_message(gateway: HostGateway, profile: str) -> str:+ return (+ f"⏳ A gateway already owns this host and has not published its served set yet.\n"+ f" {gateway.describe()}\n"+ f" Whether it will serve profile '{profile}' is unknown, so starting a second gateway\n"+ f" now could double-bind this profile's platforms. Nothing was started; this is a\n"+ f" transient state and a service supervisor will retry.\n"+ f" Take the host over: hermes gateway run --replace\n"+ f" Start anyway: hermes gateway run --force")++def _refuse_message(gateway: HostGateway, profile: str) -> str:return (f"❌ A gateway already owns this host and will not serve profile '{profile}'.\n"@@ -183,7 +258,8 @@ def _refuse_message(gateway: HostGateway, profile: str) -> str: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")+ f" Or take the host over: hermes gateway run --replace\n"+ f" Or start one anyway: hermes gateway run --force")def decide(our_home: Path, *, replace: bool = False) -> HostAttachDecision:@@ -204,12 +280,26 @@ def decide(our_home: Path, *, replace: bool = False) -> HostAttachDecision:# whichever home launched it.return HostAttachDecision(REPLACE_HOST, "", gateway)if gateway.serves(profile):- return HostAttachDecision(ATTACH, attach_message(gateway, profile), gateway)+ return HostAttachDecision(ATTACH, attach_message(gateway, profile), gateway, transient=True)+ if not gateway.served_known:+ # Give the owner its bounded window to answer before judging it: during the boot race the+ # record lands a moment before the control socket binds.+ waited = host_gateway(wait_for_channel=ATTACH_CHANNEL_WAIT_S)+ if waited is None:+ return HostAttachDecision(START, "")+ gateway = waited+ if gateway.serves(profile):+ return HostAttachDecision(ATTACH, attach_message(gateway, profile), gateway, transient=True)try:- attached = request_serve_profile(profile)+ attached = request_serve_profile(profile, owner=gateway)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)+ if attached is not None and attached.serves(profile):+ return HostAttachDecision(ATTACH, attach_message(attached, profile), attached, transient=True)+ if not gateway.served_known:+ # The owner never answered, so we know only that it exists. ATTACH here (on the record's+ # word) parked a supervised unit against a served set nobody had committed to yet.+ return HostAttachDecision(+ REFUSE, _unknown_served_message(gateway, profile), gateway, transient=True)return HostAttachDecision(REFUSE, _refuse_message(gateway, profile), gateway)diff --git a/gateway/host_rendezvous.py b/gateway/host_rendezvous.pyindex a4aea74aa9e..64d9bca9890 100644--- a/gateway/host_rendezvous.py+++ b/gateway/host_rendezvous.py@@ -36,6 +36,7 @@ import hashlibimport jsonimport loggingimport os+import statimport sysfrom dataclasses import dataclassfrom datetime import datetime, timezone@@ -138,6 +139,47 @@ def host_state_dir() -> Path:return _get_lock_dir()+def ensure_host_state_dir() -> Path:+ """The rendezvous dir, created owner-only (``0o700``) and tightened if it is not.++ A bare ``mkdir`` under the common ``umask 002`` leaves the dir group-writable, and the record+ inside it is what every lifecycle verb believes: a same-group process could unlink+replace it+ and choose this host's ATTACH answers (which home to dial, which profiles are "served").+ Ownership of the dir is ours, so widening is repaired rather than refused.+ """+ directory = host_state_dir()+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)+ if sys.platform != "win32":+ with contextlib.suppress(OSError):+ if stat.S_IMODE(directory.stat().st_mode) & 0o077:+ os.chmod(directory, 0o700)+ return directory+++def _record_is_own(path: Path) -> bool:+ """True when ``path`` was written by THIS OS user inside a dir this user owns.++ ``read_record`` hands its result straight to :mod:`gateway.host_attach`, which dials the home+ it names and believes the served set it carries. A hand-written record therefore buys an+ attacker the lifecycle verdict for every profile on the host, so the file's ``st_uid`` — not+ its contents — is what makes it a record at all. Windows sets no ACLs from mode bits; there+ the dir already lives under the user's own state root.+ """+ if sys.platform == "win32":+ return True+ try:+ info = path.stat()+ parent = path.parent.stat()+ except OSError:+ return False+ uid = os.getuid() # windows-footgun: ok — unreachable on Windows (early return above)+ if info.st_uid != uid or parent.st_uid != uid:+ logger.warning(+ "ignoring host record %s: owned by uid %s (expected %s)", path, info.st_uid, uid)+ return False+ return True++def _validated_role(role: str) -> str:if role not in _ROLES:raise ValueError(f"unknown host role: {role!r}")@@ -247,9 +289,12 @@ def probe_owner(record: HostRecord, *, timeout: float = PROBE_TIMEOUT_S) -> Optidef read_record(role: str, *, include_stale: bool = False) -> Optional[HostRecord]:- """Published record for ``role``; ``None`` when absent, corrupt or (by default) stale."""+ """Published record for ``role``; ``None`` when absent, foreign, corrupt or (by default) stale."""+ path = record_path(role)+ if not _record_is_own(path):+ return Nonetry:- raw = record_path(role).read_text(encoding="utf-8")+ raw = path.read_text(encoding="utf-8")except (OSError, UnicodeDecodeError):return Nonetry:@@ -350,7 +395,7 @@ def claim_host_lock(role: str) -> tuple[HostLockOutcome, Optional[OSError]]:path = Path(key[1])try:- path.parent.mkdir(parents=True, exist_ok=True)+ ensure_host_state_dir()handle = open(path, "a+", encoding="utf-8")except OSError as exc:logger.debug("host %s lock could not be opened at %s", role, path, exc_info=True)@@ -409,7 +454,7 @@ def publish_record(home=str(home or ""),)try:- record_path(role).parent.mkdir(parents=True, exist_ok=True)+ ensure_host_state_dir()if token:# No record without its token: publishing one an attaching client cannot# authenticate against would degrade to a silent "attach refused forever".@@ -418,9 +463,38 @@ def publish_record(except OSError:logger.warning("host %s record could not be published; discovery will not find it", role, exc_info=True)return None+ _invalidate_attach_cache()return record+def _invalidate_attach_cache() -> None:+ """Drop :mod:`gateway.host_attach`'s memo: the record it summarises just changed."""+ with contextlib.suppress(Exception):+ from gateway.host_attach import invalidate_host_gateway_cache++ invalidate_host_gateway_cache()+++def discard_dead_record(role: str) -> bool:+ """Retract the record for ``role`` when its owner is provably gone; True when one was removed.++ A confirmed stop must retract the record too. Leaving it made ``gateway restart --all`` a+ silent no-op: the re-entered ``gateway run`` read the corpse's record, decided ATTACH and+ exited 0, so the host ended up with no gateway at all.+ """+ role = _validated_role(role)+ record = read_record(role, include_stale=True)+ if record is None:+ return False+ if record.pid != os.getpid() and _pid_incarnation_matches(record.pid, record.create_time) is not False:+ return False+ for path in (record_path(role), token_path(role)):+ with contextlib.suppress(OSError):+ path.unlink(missing_ok=True)+ _invalidate_attach_cache()+ return True++def clear_record(role: str) -> None:"""Remove this process's record + token on exit (never another owner's)."""role = _validated_role(role)@@ -430,6 +504,7 @@ def clear_record(role: str) -> None:for path in (record_path(role), token_path(role)):with contextlib.suppress(OSError):path.unlink(missing_ok=True)+ _invalidate_attach_cache()# Roles this process must clean up on the way out, and the signal handlers we prepended.@@ -495,12 +570,31 @@ def cleanup_on_exit(role: str) -> None:_prev_signal_handlers[signum] = prev-def served_profiles() -> tuple[str, ...]:- """Profiles this process multiplexes; ``()`` when the roster cannot be read."""+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)+++def served_profiles(*, multiplex: Optional[bool] = None) -> tuple[str, ...]:+ """Profiles this process multiplexes; ``()`` when the roster cannot be read.++ ``multiplex`` defaults to what this process's own config says. Hard-coding ``True`` here+ published a record claiming EVERY profile from a gateway that would only ever serve its own,+ and a second profile's supervised unit then stood down against a set nobody serves.+ """try:from hermes_cli.profiles import profiles_to_serve- return tuple(name for name, _ in profiles_to_serve(multiplex=True))+ enabled = _multiplex_profiles_enabled() if multiplex is None else bool(multiplex)+ return tuple(name for name, _ in profiles_to_serve(multiplex=enabled))except Exception:logger.debug("served profile roster unavailable", exc_info=True)return ()diff --git a/gateway/run.py b/gateway/run.pyindex 5541c8de588..64b9feb9b94 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -5297,8 +5297,12 @@ 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(), home=str(get_hermes_home()))+ # PROVISIONAL: an owner exists, its served set is not decided yet (multiplex is+ # settled by the runner, and the attach channel is not bound for another moment).+ # Publishing a guessed set here parked a second profile's supervised unit against+ # profiles this process may never serve; _refresh_host_gateway_record() fills it in+ # once the control socket answers.+ hr.publish_record(hr.ROLE_GATEWAY, 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@@ -5318,35 +5322,44 @@ def _claim_host_gateway_role() -> None:def _refresh_host_gateway_record(runner) -> None:- """Republish the host record once the attach channel is bound and multiplex is settled.+ """Republish the host record with the SETTLED served set, now that the channel answers.- 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.+ The claim-time publish is deliberately empty: only the runner knows whether multiplex ended up+ on and which profiles it took. A standalone gateway serves exactly its own profile — not the+ whole roster ``served_profiles()`` would have guessed for it."""from gateway import host_rendezvous as hr+ from gateway.host_attach import profile_name_for_hometry: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()))+ home = get_hermes_home()+ if getattr(runner.config, "multiplex_profiles", False):+ served = tuple(runner.served_profile_names())+ else:+ served = (profile_name_for_home(home),)+ hr.publish_record(hr.ROLE_GATEWAY, profiles=served, home=str(home))except Exception:logger.debug("host gateway record refresh failed", exc_info=True)-async def _host_attach_or_none(replace: bool) -> Optional[bool]:+async def _host_attach_or_none(replace: bool, force: bool = False) -> 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, nothingspawned) and ``False`` when it must refuse. The per-home duplicate guard below cannot answerthis at all: another profile's gateway lives in another home, so it sees no PID and starts asecond process — the shape multiplex-only forbids.++ ``force`` is the operator's escape hatch when the owner is wedged or lying: skip the whole+ question and start. Ignoring it here made ``--force`` print the starting banner and then attach+ anyway, leaving no supported way to start a gateway at all."""+ if force:+ logger.warning("--force: starting a gateway without asking the host owner.")+ return None+from gateway.host_attach import ATTACH, REFUSE, REPLACE_HOST, decidedecision = decide(get_hermes_home(), replace=replace)@@ -5566,9 +5579,11 @@ async def _start_gateway_shutdown_tail(return _resolve_gateway_exit_verdict(runner, _signal_initiated_shutdown[0])-async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool = False, verbosity: Optional[int] = 0) -> bool:+async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool = False,+ verbosity: Optional[int] = 0, force: bool = False) -> bool:"""Start the gateway and run until interrupted; False if it failed to start (non-zero exit so- systemd can auto-restart). ``replace`` kills any existing instance first (avoids restart-loop deadlocks)."""+ systemd can auto-restart). ``replace`` kills any existing instance first (avoids restart-loop+ deadlocks); ``force`` starts without consulting the host owner at all."""# Set here (not at import) so incidental gateway.run imports from CLI code don't poison it.os.environ["HERMES_EXEC_ASK"] = "1"@@ -5581,7 +5596,7 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =# 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)+ _host_decision = await _host_attach_or_none(replace, force)if _host_decision is not None:return _host_decisiondiff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex 02f4c3494ff..4c37205078a 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -3745,26 +3745,50 @@ 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.+def _host_decision_exit_code(decision) -> int:+ """Exit code for a host-attach verdict a supervisor may be watching.++ ``GATEWAY_FATAL_CONFIG_EXIT_CODE`` (78) is the PERMANENT refusal: systemd parks the unit on it+ (``RestartPreventExitStatus``), the s6 finish script maps it to 125, launchd maps it to a+ deliberate stop. That is right for a config-derived refusal and wrong for a runtime one — "some+ other process serves me right now" ends the moment that process goes away, and parking the unit+ on it strands the profile until a human notices. Transient verdicts therefore use+ ``GATEWAY_SERVICE_RESTART_EXIT_CODE`` (75, EX_TEMPFAIL), which every supervisor we generate+ already retries: systemd has ``RestartForceExitStatus=75`` with ``RestartSec=5``, the s6 finish+ script passes it through, and launchd relaunches a non-78 failure. Exit 0 would NOT do: s6+ parks a clean exit too.+ """+ if getattr(decision, "transient", False):+ return GATEWAY_SERVICE_RESTART_EXIT_CODE+ return GATEWAY_FATAL_CONFIG_EXIT_CODE+++def _attach_to_host_gateway_or_guard(force: bool = False, replace: bool = False) -> None:+ """``gateway run`` against the ONE host gateway: attach, rescan-then-attach, replace, 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.+ without spawning anything. Under a service supervisor the SAME situation exits 75 instead, so+ the unit is RETRIED rather than parked (see :func:`_host_decision_exit_code`).++ ``--replace`` and ``--force`` are the two escape hatches this guard must not eat: both return+ here so ``start_gateway`` can act on them (it owns the signalling and the PID claim)."""if force:returntry:- from gateway.host_attach import ATTACH, REFUSE, decide- decision = decide(get_hermes_home())+ from gateway.host_attach import ATTACH, REFUSE, REPLACE_HOST, decide+ decision = decide(get_hermes_home(), replace=replace)except Exception:logger.debug("Host gateway attach probe failed", exc_info=True)decision = None+ if decision is not None and decision.outcome == REPLACE_HOST:+ return # start_gateway replaces the owner; the config guard below must not pre-empt itif 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)+ if decision.outcome == REFUSE:+ sys.exit(_host_decision_exit_code(decision))+ if _running_under_gateway_supervisor():+ sys.exit(_host_decision_exit_code(decision))sys.exit(0)# No host record (older gateway, unwritable lock dir): the config-derived refusal still applies._guard_named_profile_under_multiplexer(force=force)@@ -3982,7 +4006,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()- _attach_to_host_gateway_or_guard(force=force)+ _attach_to_host_gateway_or_guard(force=force, replace=replace)_guard_supervised_gateway_conflict(force=force)_guard_existing_gateway_process_conflict(replace=replace)sys.path.insert(0, str(PROJECT_ROOT))@@ -4042,7 +4066,7 @@ def run_gateway(verbose: int = 0, quiet: bool = False, replace: bool = False, fosuccess = Falsetry:- success = asyncio.run(start_gateway(replace=replace, verbosity=verbosity))+ success = asyncio.run(start_gateway(replace=replace, force=force, verbosity=verbosity))_exit_diag("asyncio.run.returned", success=success)except KeyboardInterrupt:# Detached Windows runs absorb SIGINT above; keep the handler for console runs.@@ -4753,6 +4777,17 @@ def _stop_host_multiplexer(owner) -> int:return 0+def _discard_dead_host_record() -> bool:+ """Drop the host rendezvous record once its owner is provably gone (after a confirmed stop)."""+ try:+ from gateway.host_rendezvous import ROLE_GATEWAY, discard_dead_record++ return discard_dead_record(ROLE_GATEWAY)+ except Exception:+ logger.debug("Host record retraction failed", exc_info=True)+ return False++def _restart_all(system: bool) -> None:owner = _host_multiplexer_for_all_verb()if owner is not None and not _host_multiplexer_is_ours(owner):@@ -4782,12 +4817,17 @@ def _restart_all(system: bool) -> None: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()+ # Retract the stopped owner's rendezvous record. Leaving it made this very function a silent+ # no-op: the re-entered `gateway run` below read the corpse's record and ATTACHED to it.+ _discard_dead_host_record()print("Starting gateway...")# Even without a registered task, gateway_windows.start() uses the detached launcher.kind = _installed_service_kind_for(is_windows)if kind is None:- run_gateway(verbose=0)+ # replace=True: if the old owner is still draining (a long drain, an ineffective SIGKILL, a+ # foreign-home owner the scan never saw), take the host over instead of attaching to it.+ run_gateway(verbose=0, replace=True)else:_service_call(kind, "start", system)@@ -4797,7 +4837,11 @@ def _cmd_restart(args):system = getattr(args, "system", False)restart_all = getattr(args, "all", False)force = getattr(args, "force", False)- _guard_named_profile_under_multiplexer(force=force)+ # `--all` targets the ONE host multiplexer and _restart_all does its own ownership check with+ # the right one-liner; running the generic named-profile guard first made that branch+ # unreachable for `-p X gateway restart --all` (it printed a bare `gateway restart` instead).+ if not restart_all:+ _guard_named_profile_under_multiplexer(force=force)if restart_all and _dispatch_all_via_service_manager_if_s6("restart"):returnif not restart_all and _dispatch_via_service_manager_if_s6("restart"):diff --git a/scripts/run_tests.sh b/scripts/run_tests.shindex 77eedc6d1cc..bc0b4e6b98f 100755--- a/scripts/run_tests.sh+++ b/scripts/run_tests.sh@@ -143,7 +143,8 @@ done# credential can leak" property stays auditable at a glance.TEST_ENV=()for _test_var in HERMES_TEST_IMAGE HERMES_TEST_WORKERS HERMES_TEST_PATHS \- HERMES_TEST_FILE_TIMEOUT HERMES_TEST_FILE_RETRIES HERMES_TEST_SLICE; do+ HERMES_TEST_FILE_TIMEOUT HERMES_TEST_FILE_RETRIES HERMES_TEST_SLICE \+ HERMES_GATEWAY_LOCK_DIR; doif [ -n "${!_test_var:-}" ]; thenTEST_ENV+=("$_test_var=${!_test_var}")fidiff --git a/tests/conftest.py b/tests/conftest.pyindex 4c11007e4db..ae7af042a82 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -127,10 +127,28 @@ HERMES_HOME_AT_CONFTEST_IMPORT = os.environ.get("HERMES_HOME", "")# 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-")+# nothing to do with it. Give each pytest PROCESS its own rendezvous dir.+#+# A caller-supplied value always wins (both here and in the per-test fixture+# below) — otherwise the documented override is a silent no-op.+HOST_LOCK_DIR_AT_CONFTEST_IMPORT = os.environ.get("HERMES_GATEWAY_LOCK_DIR", "")+if not HOST_LOCK_DIR_AT_CONFTEST_IMPORT:+ # Deterministic per-PID name, not mkdtemp: the parallel runner SIGKILLs a worker on timeout,+ # which never runs atexit, so a random dir per run leaked one directory per killed worker.+ # A fixed name is reused by the next process with that PID, and dead siblings are swept here.+ _LOCK_DIR_PREFIX = "hermes-test-gateway-locks-"+ _LOCK_DIR_ROOT = Path(tempfile.gettempdir())+ for _stale in _LOCK_DIR_ROOT.glob(f"{_LOCK_DIR_PREFIX}*"):+ try:+ _stale_pid = int(_stale.name[len(_LOCK_DIR_PREFIX):])+ except ValueError:+ continue+ try:+ os.kill(_stale_pid, 0)+ except OSError:+ shutil.rmtree(_stale, ignore_errors=True)+ _SESSION_LOCK_DIR = str(_LOCK_DIR_ROOT / f"{_LOCK_DIR_PREFIX}{os.getpid()}")+ shutil.rmtree(_SESSION_LOCK_DIR, ignore_errors=True)os.environ["HERMES_GATEWAY_LOCK_DIR"] = _SESSION_LOCK_DIRatexit.register(shutil.rmtree, _SESSION_LOCK_DIR, True)@@ -516,7 +534,9 @@ def _hermetic_environment(tmp_path, monkeypatch):# 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"))+ # Skipped when the caller supplied the variable, so an explicit override still works.+ if not HOST_LOCK_DIR_AT_CONFTEST_IMPORT:+ 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 testdiff --git a/tests/gateway/test_host_attach_lifecycle.py b/tests/gateway/test_host_attach_lifecycle.pyindex 3701351ff7f..9591df8a55c 100644--- a/tests/gateway/test_host_attach_lifecycle.py+++ b/tests/gateway/test_host_attach_lifecycle.py@@ -1,13 +1,21 @@"""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).+Invariants, all against a REAL live process standing in for the owner:++* ATTACH requires a LIVE ``identify`` answer. A record on its own proves only that an owner+ exists — believing its ``profiles`` list parked a second profile's supervised unit against a+ served set that process had not committed to (and, with multiplex off, never would).+* ``--replace`` signals the owner instead of standing down.+* ``--force`` starts without asking the owner anything.+* The claim-time record carries NO served set; it is filled in once the channel answers.++The record is written as raw JSON, not via ``HostRecord(...)``, so these tests collect and RUN+against a tree without the ``home`` field and fail on the OUTCOME rather than on a TypeError."""import asyncioimport json+import osimport subprocessimport sysfrom pathlib import Path@@ -18,6 +26,23 @@ from gateway import host_attach, host_rendezvous as hrfrom gateway import run as gateway_run+def _reset_probe_memo() -> None:+ """Drop the host-gateway memo when the tree HAS one.++ ``getattr`` on purpose: a tree without the memo must still run these tests and fail on the+ OUTCOME, never error at fixture setup — an import tripwire proves nothing about behaviour.+ """+ getattr(host_attach, "invalidate_host_gateway_cache", lambda: None)()++[email protected](autouse=True)+def _no_memo():+ """The probe is memoized for a couple of seconds; each arrangement starts from cold."""+ _reset_probe_memo()+ yield+ _reset_probe_memo()++@pytest.fixturedef owner_pid(tmp_path, monkeypatch):"""A REAL live process standing in for the host gateway (liveness is proved, not stubbed)."""@@ -31,19 +56,58 @@ def owner_pid(tmp_path, monkeypatch):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))+ payload = {+ "role": hr.ROLE_GATEWAY,+ "home": str(home),+ "pid": pid,+ "createTime": hr.process_create_time(pid),+ "host": "",+ "port": None,+ "protocolVersion": hr.HOST_PROTOCOL_VERSION,+ "tokenFingerprint": "",+ "profiles": list(profiles),+ "updatedAt": "",+ }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")+ path.write_text(json.dumps(payload), encoding="utf-8")-def test_run_for_a_served_profile_attaches_and_spawns_nothing(tmp_path, monkeypatch, owner_pid):- owner_home = tmp_path / "root"+def _answer_identify(monkeypatch, pid: int, home: Path, served: list[str]) -> None:+ """Make the owner's control socket answer ``identify`` — the ONLY source of a served set."""+ monkeypatch.setattr(+ "gateway.control_socket.identify_gateway",+ lambda dialled, **kw: (+ {"pid": pid, "hermes_home": str(home), "served_profiles": served}+ if Path(dialled) == home else None))+++def test_a_record_only_owner_never_produces_attach(tmp_path, monkeypatch, owner_pid):+ """Owner present, control socket silent: the served set is UNKNOWN, so never ATTACH.++ The claim-time record lands before the socket binds, so during a boot race a second profile's+ supervised unit read "I am already served" from a process that had committed to nothing — and+ exited 78, which parks the unit for good.+ """ours = tmp_path / "root" / "profiles" / "other"- _publish(owner_pid, owner_home, ("default", "other"))+ _publish(owner_pid, tmp_path / "root", ("default", "other"))+ monkeypatch.setattr(host_attach, "ATTACH_CHANNEL_WAIT_S", 0.0)+ monkeypatch.setattr("gateway.control_socket.identify_gateway", lambda *a, **k: None)+ monkeypatch.setattr("gateway.control_socket.rescan_gateway_profiles", lambda *a, **k: None)++ decision = host_attach.decide(ours)++ assert decision.outcome == host_attach.REFUSE+ # ...and it is a RUNTIME observation, so a supervisor must retry rather than park the unit.+ assert decision.transient is True+ assert decision.owner is not None and decision.owner.served_known is False+++def test_attach_needs_a_live_identify_answer(tmp_path, monkeypatch, owner_pid):+ owner_home = tmp_path / "root"+ ours = owner_home / "profiles" / "other"+ _publish(owner_pid, owner_home, ()) # the record claims nothing; the socket answers+ _answer_identify(monkeypatch, owner_pid, owner_home, ["default", "other"])monkeypatch.setattr(gateway_run, "get_hermes_home", lambda: ours)def _never(*a, **k):@@ -56,10 +120,10 @@ def test_run_for_a_served_profile_attaches_and_spawns_nothing(tmp_path, monkeypadef 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"+ ours = owner_home / "profiles" / "other"_publish(owner_pid, owner_home, ("default",))+ _answer_identify(monkeypatch, 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):@@ -73,15 +137,86 @@ def test_run_for_an_unserved_profile_rescans_then_attaches(tmp_path, monkeypatchdef 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)+ owner_home = tmp_path / "root"+ _publish(owner_pid, owner_home, ("default",))+ _answer_identify(monkeypatch, owner_pid, owner_home, ["default"])+ monkeypatch.setattr(gateway_run, "get_hermes_home", lambda: owner_home / "profiles" / "other")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):+def test_replace_signals_the_owner_instead_of_standing_down(tmp_path, monkeypatch, owner_pid):+ """``gateway run --replace`` against a live owner must REACH it — the branch was dead code."""+ owner_home = tmp_path / "root"+ _publish(owner_pid, owner_home, ("default", "other"))+ _answer_identify(monkeypatch, owner_pid, owner_home, ["default", "other"])+ monkeypatch.setattr(gateway_run, "get_hermes_home", lambda: owner_home / "profiles" / "other")+ signalled: list[int] = []++ async def _replace(pid, replace):+ signalled.append(pid)+ return True++ monkeypatch.setattr(gateway_run, "_start_gateway_replace_existing_instance", _replace)++ assert asyncio.run(gateway_run._host_attach_or_none(replace=True)) is None+ assert signalled == [owner_pid]+++def test_force_starts_without_consulting_the_owner(tmp_path, monkeypatch, owner_pid):+ """``--force`` printed the starting banner and then attached anyway. It must START."""+ owner_home = tmp_path / "root"+ _publish(owner_pid, owner_home, ("default", "other"))+ _answer_identify(monkeypatch, owner_pid, owner_home, ["default", "other"])+ monkeypatch.setattr(gateway_run, "get_hermes_home", lambda: owner_home / "profiles" / "other")++ assert asyncio.run(gateway_run._host_attach_or_none(replace=False, force=True)) is None+++def test_the_claim_time_record_publishes_no_served_set(tmp_path, monkeypatch):+ """Claim time is too early to know the served set; publishing a guess strands other profiles."""+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "locks"))+ monkeypatch.setattr(gateway_run, "get_hermes_home", lambda: tmp_path / "root")+ monkeypatch.setattr(hr, "served_profiles",+ lambda **kw: pytest.fail("the claim must not guess a served set"))+ try:+ gateway_run._claim_host_gateway_role()+ record = hr.read_record(hr.ROLE_GATEWAY)+ assert record is not None and record.pid == os.getpid()+ assert record.profiles == ()+ finally:+ hr.release_host_lock(hr.ROLE_GATEWAY)+ 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."""+ asked: list[bool] = []++ def _roster(*, multiplex):+ asked.append(multiplex)+ return ([("default", Path("/x")), ("other", Path("/y"))] if multiplex+ 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]++[email protected](sys.platform == "win32",+ reason="POSIX ownership check; Windows has no st_uid to compare")+def test_a_foreign_record_is_not_a_record(tmp_path, monkeypatch, owner_pid):+ """A record this OS user did not write must never decide our lifecycle (forgery/DoS)."""_publish(owner_pid, tmp_path / "root", ("default", "other"))- assert host_attach.host_gateway_serving("default") is not None+ real_uid = os.getuid()+ monkeypatch.setattr(os, "getuid", lambda: real_uid + 1)++ assert hr.read_record(hr.ROLE_GATEWAY) is None+ assert host_attach.host_gateway() is Nonediff --git a/tests/gateway/test_runner_startup_failures.py b/tests/gateway/test_runner_startup_failures.pyindex 8b94df1a42e..cab556b9075 100644--- a/tests/gateway/test_runner_startup_failures.py+++ b/tests/gateway/test_runner_startup_failures.py@@ -8,6 +8,22 @@ from gateway.run import GatewayRunnerfrom gateway.status import read_runtime_status[email protected](autouse=True)+def _host_attach_gate_is_not_under_test(monkeypatch):+ """These tests exercise the STARTUP path, not the host-attach gate that now runs in front of it.++ Without the stub they pass only while the shared rendezvous dir happens to be empty: any record+ there makes ``start_gateway`` attach and return before reaching the code under test. The host+ role claimed along the way is released afterwards, so one test's owner is not the next one's.+ """+ monkeypatch.setattr("gateway.run._host_attach_or_none", AsyncMock(return_value=None))+ yield+ from gateway import host_rendezvous as hr++ hr.release_host_lock(hr.ROLE_GATEWAY)+ hr.clear_record(hr.ROLE_GATEWAY)++@pytest.mark.parametrize("code, expected",[diff --git a/tests/hermes_cli/test_gateway.py b/tests/hermes_cli/test_gateway.pyindex db73ae46443..0b1313b2de9 100644--- a/tests/hermes_cli/test_gateway.py+++ b/tests/hermes_cli/test_gateway.py@@ -78,7 +78,7 @@ def _run_native_windows_gateway_start_diag(import hermes_cli.gateway as gateway_cli- async def start_gateway(*, replace, verbosity):+ async def start_gateway(**kwargs):assert "_HERMES_GATEWAY_BREAKAWAY" not in os.environreturn True@@ -89,6 +89,7 @@ def _run_native_windows_gateway_start_diag(gateway_cli._guard_official_docker_root_gateway = lambda: Nonegateway_cli._guard_named_profile_under_multiplexer = lambda force=False: None+ gateway_cli._attach_to_host_gateway_or_guard = lambda **kwargs: Nonegateway_cli._guard_supervised_gateway_conflict = lambda force=False: Nonegateway_cli._guard_existing_gateway_process_conflict = lambda replace=False: Nonegateway_cli.supports_systemd_services = lambda: False@@ -192,7 +193,7 @@ def test_gateway_run_subprocess_preserves_daemon_exit_codes(outcome = os.environ["HERMES_TEST_GATEWAY_OUTCOME"]- async def start_gateway(*, replace, verbosity):+ async def start_gateway(**kwargs):if outcome == "failure":return Falseraise SystemExit(int(outcome.split(":", 1)[1]))@@ -204,6 +205,7 @@ def test_gateway_run_subprocess_preserves_daemon_exit_codes(gateway_cli._guard_official_docker_root_gateway = lambda: Nonegateway_cli._guard_named_profile_under_multiplexer = lambda force=False: None+ gateway_cli._attach_to_host_gateway_or_guard = lambda **kwargs: Nonegateway_cli._guard_supervised_gateway_conflict = lambda force=False: Nonegateway_cli._guard_existing_gateway_process_conflict = lambda replace=False: Nonegateway_cli.supports_systemd_services = lambda: Falsediff --git a/tests/hermes_cli/test_gateway_host_verbs.py b/tests/hermes_cli/test_gateway_host_verbs.pyindex 568c5652a07..2ec0feb8862 100644--- a/tests/hermes_cli/test_gateway_host_verbs.py+++ b/tests/hermes_cli/test_gateway_host_verbs.py@@ -1,8 +1,18 @@-"""``gateway start --all`` / ``restart --all`` mean "the ONE host multiplexer", not "every gateway".+"""``gateway start/restart --all`` and ``gateway run`` mean "the ONE host multiplexer".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.+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.++Also covered here, because each was proven dead or wrong on the PR head:++* a supervised attach exits 75 (retry), never 78 (park) — the observation is transient;+* ``--replace`` is not eaten by the CLI guard, so ``start_gateway`` can signal the owner;+* ``restart --all`` retracts the stopped owner's record and re-enters with ``replace=True``,+ instead of attaching to the corpse it just stopped;+* ``-p X gateway restart --all`` reaches the ``--all``-aware branch.++The record is written as raw JSON so the file collects against a tree without the ``home`` field."""import json@@ -13,24 +23,53 @@ from types import SimpleNamespaceimport pytest+from gateway import host_attachfrom gateway import host_rendezvous as hrfrom hermes_cli import gateway as gw+def _reset_probe_memo() -> None:+ """Drop the host-gateway memo when the tree HAS one.++ ``getattr`` on purpose: a tree without the memo must still run these tests and fail on the+ OUTCOME, never error at fixture setup — an import tripwire proves nothing about behaviour.+ """+ getattr(host_attach, "invalidate_host_gateway_cache", lambda: None)()++[email protected](autouse=True)+def _no_memo():+ """The probe is memoized for a couple of seconds; each arrangement starts from cold."""+ _reset_probe_memo()+ yield+ _reset_probe_memo()+++def _write_record(pid: int, home: Path, profiles: tuple[str, ...]) -> None:+ payload = {+ "role": hr.ROLE_GATEWAY, "home": str(home), "pid": pid,+ "createTime": hr.process_create_time(pid), "host": "", "port": None,+ "protocolVersion": hr.HOST_PROTOCOL_VERSION, "tokenFingerprint": "",+ "profiles": list(profiles), "updatedAt": "",+ }+ path = hr.record_path(hr.ROLE_GATEWAY)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(payload), encoding="utf-8")++@pytest.fixturedef host_owner(tmp_path, monkeypatch):- """A REAL live process published as the host gateway serving three profiles."""+ """A REAL live process published as the host gateway, answering identify for 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")+ home = tmp_path / "root"+ _write_record(child.pid, home, ("default", "ops", "coder"))+ monkeypatch.setattr(+ "gateway.control_socket.identify_gateway",+ lambda dialled, **kw: {"pid": child.pid, "hermes_home": str(home),+ "served_profiles": ["default", "ops", "coder"]})try:- yield SimpleNamespace(pid=child.pid, home=tmp_path / "root")+ yield SimpleNamespace(pid=child.pid, home=home, proc=child)finally:child.terminate()child.wait(timeout=10)@@ -68,3 +107,83 @@ def test_restart_all_refuses_to_sweep_a_host_multiplexer_owned_by_another_profilwith pytest.raises(SystemExit) as exc:gw._restart_all(system=False)assert exc.value.code == gw.GATEWAY_FATAL_CONFIG_EXIT_CODE+++def test_restart_all_does_not_attach_to_the_process_it_just_stopped(+ host_owner, monkeypatch, tmp_path):+ """After a confirmed stop the record is retracted and the re-entry carries ``replace``.++ Without both, the re-entered ``gateway run`` read the corpse's record, decided ATTACH and+ exited 0 — a restart that silently left the host with no gateway at all.+ """+ monkeypatch.setattr("gateway.status._get_process_hermes_home", lambda: host_owner.home)+ monkeypatch.setattr(gw, "_stop_installed_service", lambda system: False)+ monkeypatch.setattr(gw, "kill_gateway_processes", lambda **k: 1)+ monkeypatch.setattr(gw, "_wait_for_api_server_port_free", lambda *a, **k: None)+ monkeypatch.setattr(gw, "_installed_service_kind_for", lambda *a, **k: None)+ monkeypatch.setattr(gw, "_print_unfolded_gateway_note", lambda owner: None)++ def _stopped(*a, **k):+ # The owner really is gone by the time the re-entry happens.+ host_owner.proc.kill()+ host_owner.proc.wait(timeout=10)+ _reset_probe_memo()++ monkeypatch.setattr(gw, "_wait_for_gateway_exit", _stopped)+ reentry: list[dict] = []+ monkeypatch.setattr(gw, "run_gateway", lambda **kw: reentry.append(kw))++ gw._restart_all(system=False)++ assert hr.read_record(hr.ROLE_GATEWAY, include_stale=True) is None, \+ "the stopped owner's record must be retracted"+ assert reentry and reentry[0].get("replace") is True+++def test_named_profile_restart_all_reaches_the_all_aware_branch(monkeypatch):+ """The generic guard ran first and printed a bare `gateway restart` (no --all)."""+ monkeypatch.setattr(gw, "_refuse_from_inside_gateway", lambda *a, **k: None)+ monkeypatch.setattr(gw, "_dispatch_all_via_service_manager_if_s6", lambda verb: False)+ monkeypatch.setattr(gw, "_guard_named_profile_under_multiplexer",+ lambda **k: pytest.fail("the generic guard pre-empted the --all branch"))+ called: list[bool] = []+ monkeypatch.setattr(gw, "_restart_all", lambda system: called.append(True))++ gw._cmd_restart(SimpleNamespace(system=False, all=True, force=False))++ assert called == [True]+++def test_a_supervised_attach_is_retried_not_parked(monkeypatch, capsys):+ """78 parks the unit for good; "someone serves me right now" is a transient observation."""+ owner = host_attach.HostGateway(4321, Path("/somewhere"), ("default", "other"))+ monkeypatch.setattr(+ "gateway.host_attach.decide",+ lambda home, replace=False: host_attach.HostAttachDecision(+ host_attach.ATTACH, "attached", owner, transient=True))+ monkeypatch.setattr(gw, "_running_under_gateway_supervisor", lambda: True)++ with pytest.raises(SystemExit) as exc:+ gw._attach_to_host_gateway_or_guard(force=False)++ assert exc.value.code == gw.GATEWAY_SERVICE_RESTART_EXIT_CODE+ assert exc.value.code != gw.GATEWAY_FATAL_CONFIG_EXIT_CODE+++def test_replace_is_not_eaten_by_the_cli_guard(monkeypatch):+ """The guard exited before ``start_gateway`` ever saw ``--replace``, so nothing was replaced."""+ owner = host_attach.HostGateway(4321, Path("/somewhere"), ("default", "other"))+ seen: list[bool] = []++ def _decide(home, replace=False):+ seen.append(replace)+ return host_attach.HostAttachDecision(+ host_attach.REPLACE_HOST if replace else host_attach.ATTACH, "", owner)++ monkeypatch.setattr("gateway.host_attach.decide", _decide)+ monkeypatch.setattr(gw, "_guard_named_profile_under_multiplexer",+ lambda **k: pytest.fail("--replace must not fall through to the guard"))++ gw._attach_to_host_gateway_or_guard(force=False, replace=True) # must not raise SystemExit++ assert seen == [True], "the CLI guard must pass --replace into the host decision"diff --git a/tests/hermes_cli/test_gateway_run_hard_exit.py b/tests/hermes_cli/test_gateway_run_hard_exit.pyindex eb1e7c5eb5a..8dfaff296b1 100644--- a/tests/hermes_cli/test_gateway_run_hard_exit.py+++ b/tests/hermes_cli/test_gateway_run_hard_exit.py@@ -25,7 +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, "_attach_to_host_gateway_or_guard", lambda **kwargs: 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.mdindex bf6c76eadbf..a47eddf75f9 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 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.+**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 75 (EX_TEMPFAIL) instead, so the redundant unit is RETRIED rather than parked: "someone else serves me right now" is a runtime observation that ends when that process does, and 78 (which systemd, s6 and launchd all treat as permanent) would strand the profile. ATTACH requires a live `identify` answer from the owner; a rendezvous record with nothing answering behind it proves an owner exists but never that it serves you, so it yields a transient refusal (exit 75), never an attach. `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 profilesdiff --git a/website/docs/user-guide/multi-profile-gateways.md b/website/docs/user-guide/multi-profile-gateways.mdindex e29d28b1547..fc8672013c8 100644--- a/website/docs/user-guide/multi-profile-gateways.md+++ b/website/docs/user-guide/multi-profile-gateways.md@@ -81,7 +81,12 @@ rather than "this profile's gateway":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.+ launched the running process; `hermes gateway run --force` starts a separate+ gateway without asking the host process at all (the escape hatch when it is+ wedged or answering wrongly).+- Under a service supervisor the attach exits 75, not 0 — systemd, s6 and+ launchd all restart a 75 after a short delay, so the unit keeps retrying and+ takes over by itself the moment the host process goes away.Multiplexing is **on by default** (`gateway.multiplex_profiles` defaults to`true`), with one safety rule: an *unset* flag is a request the default gateway