The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: doctor, cron status, claw and gateway status report the real host topology
teknium1a1398a6f6722
diff --git a/gateway/host_topology.py b/gateway/host_topology.pynew file mode 100644index 00000000000..c2750c732b9--- /dev/null+++ b/gateway/host_topology.py@@ -0,0 +1,106 @@+"""Who owns the gateway role on THIS host, and which profiles does that one process serve?++Multiplex-only (Teknium ruling): exactly ONE ``hermes gateway run`` per host, multiplexing every+profile. Every reporting surface (doctor, ``cron status``, ``claw``, the dashboard liveness ladder)+used to ask a per-PROFILE question instead — "does *my* profile own a gateway process?" — and a+profile that is SERVED by the host gateway answered "no". That produced three user-visible lies:+"not running", "Per-profile gateways: 0/3 up", and a silently skipped destructive-action warning.++:func:`host_gateway_topology` answers the real question once, from+:mod:`gateway.host_rendezvous` (the authoritative host record the winning process publishes),+falling back to the default home's recorded ``served_profiles`` for a gateway that predates the+record. ``default`` is just another served profile here, never a special owner.+"""++from __future__ import annotations++import logging+from dataclasses import dataclass+from typing import Optional++logger = logging.getLogger(__name__)+++def _normalized(name: Optional[str]) -> str:+ if not name:+ return ""+ try:+ from hermes_cli.profiles import normalize_profile_name++ return normalize_profile_name(name)+ except Exception:+ return str(name).strip().lower()+++@dataclass(frozen=True)+class HostGatewayTopology:+ """The single gateway process on this host plus the profile roster it multiplexes.++ ``source`` names the rung that answered (``host_record`` / ``served_record``) — for logs and+ tests only; never branch product behaviour on it.+ """++ pid: int+ profiles: tuple[str, ...]+ source: str++ def serves(self, profile_name: Optional[str]) -> bool:+ """True when this host process ticks/serves ``profile_name`` (``default`` included)."""+ wanted = _normalized(profile_name)+ return bool(wanted) and wanted in {_normalized(p) for p in self.profiles}++ def describe(self) -> str:+ """``the host gateway (PID 42) serving profiles default, coder`` — one shared phrasing so+ doctor, cron status and the state.db holder lines cannot drift apart."""+ roster = ", ".join(self.profiles) if self.profiles else "an unknown profile set"+ return f"the host gateway (PID {self.pid}) serving profiles {roster}"+++def _from_host_record() -> Optional[HostGatewayTopology]:+ from gateway import host_rendezvous as hr++ record = hr.read_record(hr.ROLE_GATEWAY) # already drops stale/PID-reused records+ if record is None or not record.pid:+ return None+ return HostGatewayTopology(pid=int(record.pid), profiles=tuple(record.profiles), source="host_record")+++def _from_served_record() -> Optional[HostGatewayTopology]:+ """A gateway started before the host record existed still publishes ``served_profiles`` into+ the default home's ``gateway_state.json``; that plus a proven-live PID is the same fact."""+ from hermes_cli.gateway_multiplex_served import live_default_gateway_pid, recorded_served_profiles++ pid = live_default_gateway_pid()+ if pid is None:+ return None+ served = recorded_served_profiles() or []+ roster = ["default"] + [str(p) for p in served if _normalized(p) != "default"]+ return HostGatewayTopology(pid=int(pid), profiles=tuple(roster), source="served_record")+++def host_gateway_topology() -> Optional[HostGatewayTopology]:+ """The one live host gateway and its served profiles, or None when no gateway owns the role."""+ for rung in (_from_host_record, _from_served_record):+ try:+ topology = rung()+ except Exception:+ logger.debug("host gateway topology rung %s failed", rung.__name__, exc_info=True)+ continue+ if topology is not None:+ return topology+ return None+++def host_gateway_serving(profile_name: Optional[str] = None) -> Optional[HostGatewayTopology]:+ """The host gateway when it serves ``profile_name`` (default: the active profile), else None."""+ topology = host_gateway_topology()+ if topology is None:+ return None+ if profile_name is None:+ try:+ from hermes_cli.profiles import get_active_profile_name++ profile_name = get_active_profile_name()+ except Exception:+ return None+ return topology if topology.serves(profile_name) else Nonediff --git a/gateway/status.py b/gateway/status.pyindex 5adf97c2e11..7a24ed0fe88 100644--- a/gateway/status.py+++ b/gateway/status.py@@ -1239,22 +1239,48 @@ class GatewayLiveness:runtime: Optional[dict[str, Any]] = None-def multiplexer_liveness_for_profile(profile_dir: Path) -> Optional[tuple[int, dict[str, Any]]]:- """``(pid, default gateway_state.json)`` when the live default multiplexer serves the named profile at- ``profile_dir``; None for the default home itself, an unserved profile, or no live multiplexer.+def profile_name_for_home(profile_home: Path) -> Optional[str]:+ """Profile id of any Hermes home: ``<root>/profiles/<name>`` → ``<name>``, the default root →+ ``"default"``, anything else → None. Multiplex-only makes ``default`` an ordinary served+ profile, so reporting surfaces need a name for it too."""+ home = Path(profile_home)+ named = _profile_name_for_home(home)+ if named:+ return named+ try:+ from hermes_constants import get_default_hermes_root+ if home.resolve() == Path(get_default_hermes_root()).resolve():+ return "default"+ except Exception:+ return None+ return None+- A served profile owns no ``gateway.pid``/``gateway_state.json`` (#97120), so every PID-file rung of the- dashboard ladder reports it stopped while ``hermes -p X status`` says running — the two must agree.+def multiplexer_liveness_for_profile(profile_dir: Path) -> Optional[tuple[int, dict[str, Any]]]:+ """``(pid, host gateway_state.json)`` when the ONE live host gateway serves the profile whose home+ is ``profile_dir``; None for a home it does not serve or when no gateway owns the host role.++ Multiplex-only: ``default`` is just another served profile, not the owner of a private topology —+ resolving from the host rendezvous record (``gateway/host_topology.py``) is what lets it be+ reported as SERVED rather than only as owner. A served profile owns no+ ``gateway.pid``/``gateway_state.json`` (#97120), so every PID-file rung of the dashboard ladder+ reports it stopped while ``hermes -p X status`` says running — the two must agree."""- name = _profile_name_for_home(Path(profile_dir))+ name = profile_name_for_home(Path(profile_dir))if not name:return None+ from gateway.host_topology import host_gateway_topologyfrom hermes_cli.gateway import named_profile_served_by_running_multiplexerfrom hermes_cli.gateway_multiplex_served import live_default_gateway_pidfrom hermes_constants import get_default_hermes_root- if not named_profile_served_by_running_multiplexer(name):+ topology = host_gateway_topology()+ if topology is not None and topology.serves(name):+ pid: Optional[int] = topology.pid+ elif name != "default" and named_profile_served_by_running_multiplexer(name):+ # Config-derived fallback for a record that predates ``served_profiles``.+ pid = live_default_gateway_pid()+ else:return None- pid = live_default_gateway_pid()if pid is None:return Nonereturn pid, read_runtime_status(get_default_hermes_root() / "gateway_state.json") or {}diff --git a/hermes_cli/claw.py b/hermes_cli/claw.pyindex f792b05accb..b195b191b29 100644--- a/hermes_cli/claw.py+++ b/hermes_cli/claw.py@@ -1,5 +1,6 @@"""hermes claw — OpenClaw migration commands."""+import contextlibimport importlib.utilimport itertoolsimport logging@@ -166,9 +167,27 @@ def _warn_if_openclaw_running(auto_yes: bool) -> None:def _warn_if_gateway_running(auto_yes: bool) -> None:- """Warn if a Hermes gateway has connected platforms (token conflicts, e.g. Telegram 409)."""- from gateway.status import get_running_pid, read_runtime_status- platforms = ((read_runtime_status() or {}).get("platforms") or {}) if get_running_pid() else {}+ """Warn if the HOST gateway has connected platforms for this profile (token conflicts, e.g.+ Telegram 409).++ Multiplex-only: one host process serves N profiles, so a SERVED profile owns no ``gateway.pid``.+ Gating on ``get_running_pid()`` made this destructive-action warning silently vanish for exactly+ those profiles — the liveness ladder answers for the served case too.+ """+ from gateway.status import (+ profile_platforms_from_multiplexer, read_runtime_status, resolve_gateway_liveness)+ liveness = resolve_gateway_liveness(use_cache=False)+ platforms: dict = {}+ if liveness.running:+ profile = None+ with contextlib.suppress(Exception):+ from hermes_cli.profiles import get_active_profile_name+ profile = get_active_profile_name()+ if liveness.source == "multiplexer" and profile and profile != "default":+ # Served profile: its platforms live under `<profile>:<platform>` in the host record.+ platforms = profile_platforms_from_multiplexer(liveness.runtime, profile)+ else:+ platforms = (liveness.runtime or read_runtime_status() or {}).get("platforms") or {}connected = [name for name, info in platforms.items()if isinstance(info, dict) and info.get("state") == "connected"]if connected and _warn_running(@@ -176,7 +195,7 @@ def _warn_if_gateway_running(auto_yes: bool) -> None:("Migrating bot tokens while the gateway is active will cause ""conflicts (Telegram, Discord, and Slack only allow one active ""session per token).",- "Recommendation: stop the gateway first with 'hermes gateway stop'."),+ "Recommendation: stop the host gateway first with 'hermes gateway stop'."),"Continue anyway?", declined="Migration cancelled. Stop the gateway and try again.",) is False:sys.exit(0)diff --git a/hermes_cli/cron.py b/hermes_cli/cron.pyindex bf66a72b5f4..4a73da8eb05 100644--- a/hermes_cli/cron.py+++ b/hermes_cli/cron.py@@ -464,10 +464,18 @@ def cron_status():print(color(" (No ticker heartbeat is expected for an external provider; ""due jobs are delivered by an authenticated webhook.)", Colors.DIM))else:- pids = find_gateway_pids()+ from gateway.host_topology import host_gateway_serving+ active = get_active_profile_name()+ # FIRST question under multiplex-only: is the HOST gateway alive and does it tick THIS+ # profile? Starting from find_gateway_pids() (argv `-p <name>`) made every served profile+ # report "not running" and told the user to start a SECOND host process.+ host = None+ with contextlib.suppress(Exception):+ host = host_gateway_serving(active)+ pids = [] if host is not None else find_gateway_pids()gateway_alive_via_lock = Falseserved_by_multiplexer = False- if not pids:+ if host is None and not pids:# The pid scan transiently misses a live gateway right after a restart; the runtime# lock proves the process is alive. Declare "not running" only when both agree.with contextlib.suppress(Exception):@@ -481,15 +489,17 @@ def cron_status():# Multiplexer identity does not establish the active profile's ticker health.if not gateway_alive_via_lock:served_by_multiplexer = named_profile_served_by_running_multiplexer()- if pids or gateway_alive_via_lock or served_by_multiplexer:+ if host is not None:+ print(f" Scheduler host: {host.describe()}")+ _print_ticker_health([host.pid], restart_command="hermes gateway restart")+ elif pids or gateway_alive_via_lock or served_by_multiplexer:if served_by_multiplexer:- print(" Scheduler host: default-profile multiplexer")+ print(" Scheduler host: the host gateway (multiplexing this profile)")_print_ticker_health([], restart_command="hermes --profile default gateway restart")else:_print_ticker_health(pids)else:- print(color("✗ Gateway is not running — cron jobs will NOT fire", Colors.RED))- active = get_active_profile_name()+ print(color("✗ No gateway is running on this host — cron jobs will NOT fire", Colors.RED))# When scheduling last worked before the host went away: without this, a# 7h-overdue job still reads as a normal upcoming "Next run" (#114309).with contextlib.suppress(Exception):@@ -499,18 +509,18 @@ def cron_status():print(color(" Scheduler last ticked "f"{_format_lateness(hb_age)} ago — jobs that came due ""since then have not fired.", Colors.YELLOW))- print("\n To enable automatic execution for this profile:\n"- " hermes gateway install # Install as a user service\n"- " sudo hermes gateway install --system # Linux servers: boot-time system service\n"- " hermes gateway run # Or run in foreground")+ print("\n Start the ONE host gateway (it multiplexes every profile, this one included):\n"+ " hermes --profile default gateway install # user service\n"+ " sudo hermes --profile default gateway install --system # Linux servers: boot-time service\n"+ " hermes --profile default gateway run # Or run in foreground")if active not in ("default", "custom"):- print("\n Alternatives for this named profile:\n"- " Keep the Desktop app open with this profile included in its scheduler and the machine awake, or\n"- " configure a running default gateway to tick this profile:\n"+ print("\n Then make sure it serves this profile:\n"" hermes --profile default config set gateway.multiplex_profiles true\n"" hermes --profile default gateway restart\n"- " To migrate existing per-profile services with preflight checks:\n"+ " To fold existing per-profile services into it, with preflight checks:\n"" hermes --profile default gateway migrate --multiplex\n"+ " LEGACY (pre-multiplex topology, not recommended): a per-profile service via\n"+ " hermes gateway install # starts a SECOND gateway process on this host\n"" Check: hermes cron status from this profile should show its ticker heartbeat.\n")print()diff --git a/hermes_cli/doctor_platform.py b/hermes_cli/doctor_platform.pyindex 5646f787086..f839e501c49 100644--- a/hermes_cli/doctor_platform.py+++ b/hermes_cli/doctor_platform.py@@ -206,7 +206,7 @@ def _check_version_consistency(issues: list[str]) -> None:def _check_s6_supervision(issues: list[str]) -> None:- """Under our s6 /init, report static services and per-profile gateway slots that are ``up``; no-op elsewhere.+ """Under our s6 /init, report static services and the ONE host gateway slot; no-op elsewhere.Counterpart to :func:`_check_gateway_service_linger` (systemd-on-host)."""try:from hermes_cli.service_manager import S6ServiceManager, detect_service_manager@@ -219,12 +219,29 @@ def _check_s6_supervision(issues: list[str]) -> None:for static in ("main-hermes", "dashboard"): # s6-rc symlinks under /run/service/, same s6-svstat probeup = mgr.is_running(static)(check_ok if up else check_info)(f"{static}: up" if up else f"{static}: down (expected if not enabled via env)")- profiles = mgr.list_profile_gateways()- if not profiles:- return check_info("No per-profile gateways registered yet — create one with `hermes profile create <name>`")- up_count = sum(1 for p in profiles if mgr.is_running(f"gateway-{p}"))- check_ok(f"Per-profile gateways: {up_count}/{len(profiles)} supervised up"- + (f" ({', '.join(sorted(profiles))})" if len(profiles) <= 8 else ""))+ _report_host_gateway_slot(mgr, issues)+++def _report_host_gateway_slot(mgr, issues: list[str]) -> None:+ """Multiplex-only: ONE gateway process serves N profiles, so report THAT process and its+ roster. The old ``Per-profile gateways: up/total`` line described a topology we no longer+ run — it counted supervision slots and never said which profiles were actually served."""+ from gateway.host_topology import host_gateway_topology+ slots = sorted(mgr.list_profile_gateways())+ topology = host_gateway_topology()+ if topology is None:+ if not slots:+ return check_info("No gateway registered yet — run `hermes gateway install`")+ up = [p for p in slots if mgr.is_running(f"gateway-{p}")]+ return check_warn(f"No host gateway owns the gateway role ({len(up)}/{len(slots)} supervision "+ f"slots up: {', '.join(slots)})", "(nothing is serving these profiles)")+ check_ok(f"Host gateway: {topology.describe()}")+ legacy_up = sorted(p for p in slots if p != "default" and mgr.is_running(f"gateway-{p}"))+ if legacy_up:+ check_warn(f"LEGACY per-profile gateway slots still supervised: {', '.join(legacy_up)}",+ "(multiplex-only: the host gateway already serves every profile from one process)")+ issues.append("Fold the legacy per-profile gateways into the host gateway: "+ "hermes --profile default gateway migrate --multiplex")def check_certificates(should_fix: bool = False, issues: "list | None" = None) -> None:@@ -276,13 +293,22 @@ def check_certificates(should_fix: bool = False, issues: "list | None" = None) -def _check_gateway_service_linger(issues: list[str]) -> None:- """Warn when a systemd user gateway service will stop after logout (skipped under s6: no linger concept)."""+ """Warn when a systemd user gateway service will stop after logout (skipped under s6: no linger concept).++ Multiplex-only: the HOST gateway runs under the default profile's unit, so a doctor run from a+ SERVED profile must still check it — gating on the active profile's own unit silently skipped+ the check for every profile that does not own a service of its own.+ """try:- from hermes_cli.gateway import get_systemd_linger_status, get_systemd_unit_path, is_linux+ from hermes_cli.gateway import (+ _SERVICE_BASE, get_systemd_linger_status, get_systemd_unit_path, is_linux)from hermes_cli.service_manager import detect_service_managerexcept Exception as e:return check_warn("Gateway service linger", f"(could not import gateway helpers: {e})")- if not is_linux() or detect_service_manager() == "s6" or not get_systemd_unit_path().exists():+ if not is_linux() or detect_service_manager() == "s6":+ return+ host_unit = Path.home() / ".config" / "systemd" / "user" / f"{_SERVICE_BASE}.service"+ if not (get_systemd_unit_path().exists() or host_unit.exists()):return_section("Gateway Service")linger_enabled, linger_detail = get_systemd_linger_status()diff --git a/hermes_cli/doctor_state.py b/hermes_cli/doctor_state.pyindex e7d67d3e4db..3df67c6f7f5 100644--- a/hermes_cli/doctor_state.py+++ b/hermes_cli/doctor_state.py@@ -48,10 +48,24 @@ def _bits(*pairs) -> list:return [fmt() for value, fmt in pairs if value is not None]-def _render_state_db_stats(stats: dict, holders=None) -> list:+def host_gateway_note() -> str:+ """``" (the host gateway (PID 42) serving profiles default, coder)"`` when one gateway process+ owns this host, else ``""``. Multiplex-only: the state.db holder and WAL lines used to imply a+ gateway per profile; the truth is one shared process serving N profiles, and stopping it stops+ every one of them."""+ try:+ from gateway.host_topology import host_gateway_topology+ topology = host_gateway_topology()+ except Exception:+ return ""+ return f" ({topology.describe()})" if topology is not None else ""+++def _render_state_db_stats(stats: dict, holders=None, host_note: str = "") -> list:"""Turn a collect_state_db_stats() dict into ``(kind, text, detail)`` rows, kind 'info' / 'warn'.Pure formatting — no I/O — so it is unit-testable without the doctor CLI. Tolerates None in every field.+ ``host_note`` names the shared host gateway among the holders (see :func:`host_gateway_note`)."""lines: list = []stats = stats or {}@@ -68,7 +82,7 @@ def _render_state_db_stats(stats: dict, holders=None) -> list:(stats.get("messages"), lambda: f"{stats['messages']:,} messages"),(stats.get("sessions"), lambda: f"{stats['sessions']:,} sessions"),(stats.get("journal_mode") or None, lambda: f"journal_mode={stats['journal_mode']}"),- (holders, lambda: f"{holders} process(es) holding the DB open"),+ (holders, lambda: f"{holders} process(es) holding the DB open{host_note}"),)if row_bits:lines.append(("info", ", ".join(row_bits), ""))@@ -82,12 +96,12 @@ def _render_state_db_stats(stats: dict, holders=None) -> list:if deferral.get("futile"):lines.append(("warn", f"state.db FTS repair is blocked by the same holder(s) PID(s) {pids} for "f"{deferral.get('holders_attempts') or '?'} consecutive deferral(s); waiting is futile",- "(stop ONLY the listed process(es) — the gateway keeps running and its own retry "- "rebuilds within a minute of the holder leaving)"))+ "(stop ONLY the listed process(es) — the host gateway keeps running and its own "+ "retry rebuilds within a minute of the holder leaving)"))else:lines.append(("warn", f"state.db FTS repair is blocked after {deferral.get('attempts') or '?'} deferral(s) "f"by PID(s) {pids}",- "(stop the listed processes; the gateway's own retry then rebuilds, or run "+ "(stop the listed processes; the host gateway's own retry then rebuilds, or run ""'hermes sessions optimize-storage' with every holder stopped)"))# Oversized DB: suggest auto_prune, plus the offline optimize-storage pass when the FTS rebuild is# pending OR the DB predates the current trigram layout (fts_storage_version < FTS_STORAGE_VERSION).@@ -96,7 +110,7 @@ def _render_state_db_stats(stats: dict, holders=None) -> list:stale_trigram = (fts is not None and fts.get("messages_fts_trigram")and (stats.get("fts_storage_version") or 0) < FTS_STORAGE_VERSION)if stats.get("fts_rebuild_pending") or stale_trigram:- detail += "; run 'hermes sessions optimize-storage' offline (with the gateway stopped) to compact FTS storage"+ detail += "; run 'hermes sessions optimize-storage' offline (with the host gateway stopped) to compact FTS storage"lines.append(("warn", f"state.db is large ({_human_bytes(logical)})", f"({detail})"))# WAL runaway is deliberately NOT warned here: _state_db_wal already warns above 50 MB and offers --fix.return lines@@ -294,7 +308,8 @@ def _state_db_stats(issues: list, state_db_path: Path) -> None:the gateway; any failure degrades to one info line rather than failing doctor."""with warn_on_error("state.db stats unavailable ({e})", "", report=lambda t, _d: check_info(t)):from hermes_state_dbfile import collect_state_db_stats, count_db_holders- rows = _render_state_db_stats(collect_state_db_stats(state_db_path), holders=count_db_holders(state_db_path))+ rows = _render_state_db_stats(collect_state_db_stats(state_db_path), holders=count_db_holders(state_db_path),+ host_note=host_gateway_note())for _kind, _text, _detail in rows:if _kind != "warn":check_info(_text + (f" {_detail}" if _detail else ""))@@ -357,9 +372,10 @@ def _retired_wal_holders(f: Finding, state_db_path: Path, _DHH: str) -> bool:rendered = ", ".join(describe_holder_pid(pid) for pid in pids)check_warn(f"{_DHH}/state.db: {len(pids)} process(es) still hold a retired WAL generation ({rendered})","(every new session refuses to open until they exit; health/stats probes skipped)")- f.issues.append(f"state.db retired WAL generation held by {rendered} — stop the gateway, dashboard and "- f"cron writers among them ('hermes {profile_cli_selector()}gateway stop', quit the Desktop "- "app), do not delete the WAL yourself, then rerun 'hermes doctor'")+ f.issues.append(f"state.db retired WAL generation held by {rendered}{host_gateway_note()} — stop the host "+ f"gateway, dashboard and cron writers among them ('hermes {profile_cli_selector()}gateway "+ "stop' stops the ONE host process serving every profile, quit the Desktop app), do not "+ "delete the WAL yourself, then rerun 'hermes doctor'")return Truediff --git a/tests/cron/test_cronjob_gateway_liveness.py b/tests/cron/test_cronjob_gateway_liveness.pyindex 58f54b94b18..3156c3ae822 100644--- a/tests/cron/test_cronjob_gateway_liveness.py+++ b/tests/cron/test_cronjob_gateway_liveness.py@@ -329,7 +329,7 @@ class TestCronStatusLockFirst:"""`hermes cron status` shares the lock-first false-alarm fix (#95947).Sibling site of `_builtin_gateway_liveness`: it previously declared- "Gateway is not running — cron jobs will NOT fire" from a bare+ "No gateway is running on this host — cron jobs will NOT fire" from a bare`find_gateway_pids()` miss even while the runtime lock proved thegateway (and its ticker) alive."""@@ -358,12 +358,12 @@ class TestCronStatusLockFirst:def test_lock_active_suppresses_not_running_false_alarm(self, hermes_env):text = self._run_status(pids=[], lock_active=True, lock_pid=4242)# The lock-first contract (#87033): an active runtime lock means the- # gateway process is alive, so the RED "Gateway is not running" alarm+ # gateway process is alive, so the RED "No gateway is running" alarm# must never fire. Since #98790 a never-written heartbeat is no longer# silently green — the YELLOW first-heartbeat notice (which also says# "NOT fire") is expected here, so assert on the red alarm itself# rather than the "NOT fire" substring both messages share.- assert "Gateway is not running" not in text+ assert "No gateway is running on this host" not in textassert "has not reported a heartbeat" in textassert "Gateway is running" in text or "running" in textdiff --git a/tests/gateway/test_host_topology.py b/tests/gateway/test_host_topology.pynew file mode 100644index 00000000000..988d7b46039--- /dev/null+++ b/tests/gateway/test_host_topology.py@@ -0,0 +1,42 @@+"""Host topology: the DEFAULT profile is a served profile, not a special owner.++``multiplexer_liveness_for_profile`` returned None for the default home by construction, so the+one profile the host gateway always serves could never be *reported* as served — the ladder had to+fall back to PID files that a multiplexed default may not own (a launch-service gateway, a+re-exec'd Desktop backend).+"""++import pytest+++def host_gateway(tmp_path, monkeypatch):+ from gateway import host_rendezvous as hr++ root = tmp_path / "hermes"+ (root / "profiles" / "coder").mkdir(parents=True)+ locks = tmp_path / "locks"+ locks.mkdir()+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(locks))+ monkeypatch.setattr("hermes_constants.get_default_hermes_root", lambda: root)+ hr.publish_record(hr.ROLE_GATEWAY, profiles=("default", "coder"))+ return root+++def test_default_home_is_reported_as_served_by_the_host_gateway(host_gateway):+ import os++ from gateway import status++ for home in (host_gateway, host_gateway / "profiles" / "coder"):+ resolved = status.multiplexer_liveness_for_profile(home)+ assert resolved is not None, f"{home} is served by the host gateway but reported unserved"+ assert resolved[0] == os.getpid()+++def test_unserved_profile_is_not_claimed_by_the_host_gateway(host_gateway, monkeypatch):+ from gateway import status++ monkeypatch.setattr("hermes_cli.gateway.named_profile_served_by_running_multiplexer", lambda *a: False)+ (host_gateway / "profiles" / "other").mkdir()+ assert status.multiplexer_liveness_for_profile(host_gateway / "profiles" / "other") is Nonediff --git a/tests/hermes_cli/test_cron.py b/tests/hermes_cli/test_cron.pyindex 9da7444e2ee..615f1094093 100644--- a/tests/hermes_cli/test_cron.py+++ b/tests/hermes_cli/test_cron.py@@ -352,7 +352,7 @@ class TestExternalCronProviderStatus:assert "managed scheduler" in outassert "not firing" not in out.lower()assert "STALLED" not in out- assert "Gateway is not running" not in out+ assert "No gateway is running on this host" not in out# Still surfaces the active-job summary.assert "active job(s)" in out@@ -634,7 +634,7 @@ class TestStatusSurfacesDeadScheduler:cron_command(Namespace(cron_command="list", all=False, json=False))list_out = capsys.readouterr().out- assert "Gateway is not running" in status_out+ assert "No gateway is running on this host" in status_outassert "Scheduler last ticked" in status_outassert "OVERDUE" in status_out and "7h ago" in status_out# The stale timestamp must no longer read as an upcoming run on either surface.diff --git a/tests/hermes_cli/test_cron_satellite_diagnostics.py b/tests/hermes_cli/test_cron_satellite_diagnostics.pyindex 4bb58fd21c0..330f57a25f9 100644--- a/tests/hermes_cli/test_cron_satellite_diagnostics.py+++ b/tests/hermes_cli/test_cron_satellite_diagnostics.py@@ -15,6 +15,9 @@ def served_root(tmp_path, monkeypatch):home.mkdir(parents=True)monkeypatch.setenv("HERMES_HOME", str(home))monkeypatch.setenv("HERMES_PROFILE", "probe")+ # Never read the real host rendezvous record of the developer's live gateway.+ (tmp_path / "locks").mkdir()+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "locks"))monkeypatch.delenv("GATEWAY_MULTIPLEX_PROFILES", raising=False)monkeypatch.setattr("hermes_constants.get_default_hermes_root", lambda: root)monkeypatch.setattr(jobs, "CRON_DIR", home / "cron")@@ -54,7 +57,7 @@ def test_status_preserves_profile_health_contract(served_root, capsys, monkeypatcron.cron_status()output = capsys.readouterr().out- assert ("Scheduler host: default-profile multiplexer" in output) == (mode in {"missing", "fresh", "stale"})+ assert ("Scheduler host: the host gateway" in output) == (mode in {"missing", "fresh", "stale"})assert ("will fire automatically" in output) == (mode in {"fresh", "local"})if mode in {"missing", "stale"}:assert "hermes --profile default gateway restart" in output@@ -63,11 +66,13 @@ def test_status_preserves_profile_health_contract(served_root, capsys, monkeypatif mode == "stale":assert "STALLED" in outputif mode in {"disabled", "excluded", "unrelated_pid"}:- assert "Gateway is not running" in output- assert "hermes gateway install" in output- assert "sudo hermes gateway install --system" in output- assert "hermes gateway run" in output+ assert "No gateway is running on this host" in output+ assert "hermes --profile default gateway install" in output+ assert "sudo hermes --profile default gateway install --system" in output+ assert "hermes --profile default gateway run" in outputassert "hermes --profile default gateway restart" in output+ # The per-profile service is offered only as the LEGACY second-process topology.+ assert "LEGACY (pre-multiplex topology, not recommended)" in outputif mode == "external":assert "managed scheduler" in outputassert "STALLED" not in output@@ -111,8 +116,10 @@ def test_standalone_guidance_matches_profile_membership(served_root, monkeypatchmonkeypatch.setattr("gateway.status.is_gateway_runtime_lock_active", lambda lock_path=None: False)cron_status()output = capsys.readouterr().out- assert "hermes gateway install" in output+ assert "hermes --profile default gateway install" in outputassert ("hermes --profile default gateway restart" in output) == (home_kind == "named")+ # A served/named profile is never told to start a SECOND host process except as LEGACY.+ assert ("LEGACY (pre-multiplex topology, not recommended)" in output) == (home_kind == "named")@pytest.mark.parametrize("detail", ["unreachable " * 30 + "\nsecret second line", ""])diff --git a/tests/hermes_cli/test_gateway_multiplex_served_record.py b/tests/hermes_cli/test_gateway_multiplex_served_record.pyindex 844a69f8d27..63acbcd8f73 100644--- a/tests/hermes_cli/test_gateway_multiplex_served_record.py+++ b/tests/hermes_cli/test_gateway_multiplex_served_record.py@@ -184,7 +184,8 @@ def test_satellite_gateway_identity_does_not_imply_cron_health(served_root, monkbuf = io.StringIO()with contextlib.redirect_stdout(buf):cr.cron_status()- assert "Scheduler host: default-profile multiplexer" in buf.getvalue()+ # Multiplex-only: the ONE host gateway is named as the ticker, with the profiles it serves.+ assert "Scheduler host: the host gateway" in buf.getvalue()# A live scheduler host alone does not prove this satellite's ticker is healthy.assert "has not reported a heartbeat" in buf.getvalue()assert "will fire automatically" not in buf.getvalue()diff --git a/tests/hermes_cli/test_multiplex_host_topology_reporting.py b/tests/hermes_cli/test_multiplex_host_topology_reporting.pynew file mode 100644index 00000000000..1b0bde719f3--- /dev/null+++ b/tests/hermes_cli/test_multiplex_host_topology_reporting.py@@ -0,0 +1,119 @@+"""Multiplex-only reporting: one host gateway serving N profiles must be reported as such.++Invariants (all fail on origin/main):+* ``hermes -p <served> cron status`` names the HOST gateway as the ticker and never tells the+ user to start a second process.+* ``hermes -p <served> doctor`` reports the single host gateway + its roster, not+ "Per-profile gateways: up/total", and still checks the HOST systemd unit's linger.+* ``hermes claw``'s destructive-action warning FIRES for a served profile.+* the state.db holder line names the shared host process and the profiles it serves.+"""++import json+import os++import pytest+++def served_host(tmp_path, monkeypatch):+ """A host gateway (this PID) serving ``default`` + ``served``; the active profile is ``served``,+ which owns no gateway.pid / gateway_state.json of its own (#97120)."""+ from gateway import host_rendezvous as hr++ root = tmp_path / "hermes"+ home = root / "profiles" / "served"+ home.mkdir(parents=True)+ locks = tmp_path / "locks"+ locks.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setenv("HERMES_PROFILE", "served")+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(locks))+ monkeypatch.setattr("hermes_constants.get_default_hermes_root", lambda: root)+ monkeypatch.setattr("hermes_cli.gateway.find_gateway_pids", lambda: [])+ monkeypatch.setattr("gateway.status.is_gateway_runtime_lock_active", lambda lock_path=None: False)+ hr.publish_record(hr.ROLE_GATEWAY, profiles=("default", "served"))+ return root+++def test_cron_status_names_the_host_gateway_for_a_served_profile(served_host, capsys, monkeypatch):+ from cron import jobs+ from hermes_cli import cron++ monkeypatch.setattr(jobs, "CRON_DIR", served_host / "profiles/served/cron")+ monkeypatch.setattr(jobs, "JOBS_FILE", served_host / "profiles/served/cron/jobs.json")+ cron.cron_status()+ out = capsys.readouterr().out++ assert f"the host gateway (PID {os.getpid()}) serving profiles default, served" in out+ assert "not running" not in out.lower()+ # Never route the user to a SECOND host process: per-profile install is legacy-only remediation.+ assert "hermes gateway install" not in out+ assert "sudo hermes gateway install --system" not in out+++def test_claw_warning_fires_for_a_served_profile(served_host, capsys, monkeypatch):+ from hermes_cli import claw++ (served_host / "gateway_state.json").write_text(json.dumps(+ {"served_profiles": ["default", "served"],+ "platforms": {"served:telegram": {"state": "connected"}, "telegram": {"state": "connected"}}}))+ fired = []+ monkeypatch.setattr(claw, "_warn_running", lambda *a, **k: fired.append(a) or True)++ claw._warn_if_gateway_running(auto_yes=True)++ assert fired, "destructive-action warning was silently skipped for a served profile"+ assert "telegram" in fired[0][1]+++def test_doctor_reports_the_single_host_gateway_not_per_profile_slots(served_host, capsys, monkeypatch):+ from hermes_cli import doctor_platform++ class _Mgr:+ def is_running(self, name):+ return name in ("main-hermes", "gateway-legacy")++ def list_profile_gateways(self):+ return ["default", "served", "legacy"]++ monkeypatch.setattr("hermes_cli.service_manager.detect_service_manager", lambda: "s6")+ monkeypatch.setattr("hermes_cli.service_manager.S6ServiceManager", _Mgr)+ issues: list[str] = []+ doctor_platform._check_s6_supervision(issues)+ out = capsys.readouterr().out++ assert "Per-profile gateways:" not in out+ assert f"Host gateway: the host gateway (PID {os.getpid()}) serving profiles default, served" in out+ assert "LEGACY per-profile gateway slots still supervised: legacy" in out+ assert any("migrate --multiplex" in i for i in issues)+++def test_doctor_checks_host_unit_linger_under_a_served_profile(served_host, tmp_path, capsys, monkeypatch):+ from hermes_cli import doctor_platform++ fake_home = tmp_path / "fakehome"+ unit_dir = fake_home / ".config" / "systemd" / "user"+ unit_dir.mkdir(parents=True)+ (unit_dir / "hermes-gateway.service").write_text("[Unit]\n") # the HOST unit; no per-profile unit+ monkeypatch.setenv("HOME", str(fake_home))+ monkeypatch.setattr("hermes_cli.gateway.is_linux", lambda: True)+ monkeypatch.setattr("hermes_cli.service_manager.detect_service_manager", lambda: "systemd")+ monkeypatch.setattr("hermes_cli.gateway.get_systemd_linger_status", lambda *a, **k: (False, "off"))++ issues: list[str] = []+ doctor_platform._check_gateway_service_linger(issues)++ assert "Systemd linger disabled" in capsys.readouterr().out+ assert any("enable-linger" in i for i in issues)+++def test_state_db_holder_line_names_the_shared_host_gateway(served_host):+ from hermes_cli import doctor_state++ rows = doctor_state._render_state_db_stats(+ {"messages": 5}, holders=3, host_note=doctor_state.host_gateway_note())+ text = " ".join(t for _kind, t, _detail in rows)++ assert f"3 process(es) holding the DB open (the host gateway (PID {os.getpid()}) " \+ "serving profiles default, served)" in textdiff --git a/website/docs/user-guide/multi-profile-gateways.md b/website/docs/user-guide/multi-profile-gateways.mdindex fc8672013c8..81df01e59a0 100644--- a/website/docs/user-guide/multi-profile-gateways.md+++ b/website/docs/user-guide/multi-profile-gateways.md@@ -376,7 +376,9 @@ parent conversation.There is a single process-level PID and lock (the multiplexer, under the default home). `hermes status` on the default profile reports the multiplexer and lists the profiles it serves (`Serves: coder, research`). `hermes -p coder status` and `hermes -p coder gateway status` report "running via the default-profile multiplexer" instead of "stopped". The dashboard's `/api/status?profile=coder` / Channels page report the multiplexer as coder's running gateway, with coder's own adapters as its platforms. The single `gateway_state.json` lives under the default home: secondary adapters appear there as `<profile>:<platform>` entries beside `served_profiles`; no per-profile gateway status file is written.-`hermes -p coder cron status` prints `Scheduler host: default-profile multiplexer`, then checks coder's own ticker heartbeat and last successful tick. A missing or stale heartbeat produces a warning rather than an unconditional running verdict; the restart hint targets `hermes --profile default gateway restart`. `cron list` and `cron create` also warn when a served profile has no fresh heartbeat. `cron status` adds tick-failure details that those lightweight checks do not read.+`hermes -p coder cron status` names the single host gateway and the profiles it serves — `Scheduler host: the host gateway (PID 4211) serving profiles default, coder` — then checks coder's own ticker heartbeat and last successful tick. A missing or stale heartbeat produces a warning rather than an unconditional running verdict. `cron list` and `cron create` also warn when a served profile has no fresh heartbeat. `cron status` adds tick-failure details that those lightweight checks do not read.++When no gateway owns the host role, `cron status` tells you to start the **one** host gateway (`hermes --profile default gateway install` / `gateway run`) and to make sure it serves this profile. Installing a per-profile service is shown only under `LEGACY (pre-multiplex topology, not recommended)`: it would start a second gateway process on the host. `hermes doctor` follows the same rule — under s6 it reports `Host gateway: the host gateway (PID 4211) serving profiles default, coder` instead of a per-profile slot count, flags any still-supervised per-profile slot as LEGACY, and checks the host systemd unit's linger even when you run doctor from a served profile. The `state.db` holder lines name the shared host process too, so "3 process(es) holding the DB open" says which gateway and which profiles stopping it would affect.#### What does **not** change