Skip to content

The agent that grows with you

fix(gateway): multiplex convergence works inside an s6 container; a standalone-on-a-guard host says so loudly

Hermes Agentb70ec27fa722
diff --git a/hermes_cli/container_boot.py b/hermes_cli/container_boot.py
index 3a2eea9abfe..8c4d6089455 100644
--- a/hermes_cli/container_boot.py
+++ b/hermes_cli/container_boot.py
@@ -13,13 +13,12 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Literal, Sequence
+from hermes_cli.gateway_multiplex_s6 import AUTOSTART_STATES as _AUTOSTART_STATES, fold_named_slot_intent
+
log = logging.getLogger(__name__)
-# Only this desired state auto-restarts; everything else (startup_failed, starting, stopped,
-# missing) registers the slot down and waits for the user — no crash-loop of a broken gateway
-# across `docker restart`. Older installs only have gateway_state; newer lifecycle commands
-# persist desired_state separately so a transient runtime state can't erase operator intent.
-_AUTOSTART_STATES = frozenset({"running"})
+# Older installs only have gateway_state; newer lifecycle commands persist desired_state separately
+# so a transient runtime state can't erase operator intent.
# Transient sub-states of a RUNNING gateway (not an operator stop, not a failed boot). A gateway
# hard-killed in one of them with no `desired_state` would otherwise stay DOWN on every later boot
# (observed: staging stranded at `draining`); map them to `running`, mirroring gateway/run.py.
@@ -119,8 +118,8 @@ def reconcile_profile_gateways(
# booted with ZERO gateways: it has no root state (or "stopped"), every named slot is now
# registered down unconditionally, and every action reported "registered" — a container that
# looks healthy while nothing is listening.
- folded = [name for name, _dir, prior in named if prior in _AUTOSTART_STATES]
- default_should_start = default_prior_state in _AUTOSTART_STATES or bool(folded)
+ fold = fold_named_slot_intent(default_prior_state, ((name, prior) for name, _dir, prior in named))
+ folded, default_should_start = list(fold.folded), fold.root_should_start
if folded and default_prior_state not in _AUTOSTART_STATES:
log.warning("%s", boot_notice(folded))
if not dry_run:
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index aa677795587..793d7444057 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -1541,14 +1541,9 @@ def _print_gateway_process_mismatch(snapshot: GatewayRuntimeSnapshot) -> None:
def _print_multiplex_standalone_reason() -> None:
"""The boot guard kept an unset-default gateway standalone: say so in status, with the remedy."""
- try:
- from gateway.status import read_runtime_status
- reason = (read_runtime_status() or {}).get("multiplex_standalone_reason")
- except Exception:
- return
- if reason:
- print(f"⚠ Serving the default profile only: {reason}")
- print(" Fold every profile onto this gateway: hermes gateway migrate --multiplex")
+ from hermes_cli.gateway_multiplex_mode import recorded_standalone_warning_lines
+ for line in recorded_standalone_warning_lines():
+ print(line)
def _print_served_ingress_urls(profile: str | None = None) -> None:
diff --git a/hermes_cli/gateway_migrate.py b/hermes_cli/gateway_migrate.py
index 73537b9fdda..28473b75068 100644
--- a/hermes_cli/gateway_migrate.py
+++ b/hermes_cli/gateway_migrate.py
@@ -272,9 +272,22 @@ def _gateway_identity(home: Path, pid: Optional[int], services: list[tuple[str,
def _installed_services(home: Path) -> list[tuple[str, bool]]:
- """Every installed service for ``home``'s gateway (units / plist / scheduled task), user scope first."""
+ """Every installed service for ``home``'s gateway (units / plist / scheduled task), user scope first.
+
+ Under s6 the footprint is the SLOT: the root slot always (it is what a restart goes through),
+ a named profile's slot only while it is UP — a registered-down slot is what the container's
+ boot leaves behind for every named profile and is not a gateway."""
from hermes_cli import gateway as gw
found: list[tuple[str, bool]] = []
+ if gw._running_under_s6():
+ from hermes_cli.gateway_multiplex_s6 import named_slot_name, slot_is_up
+ from hermes_cli.service_manager import S6ServiceManager
+ from hermes_constants import profile_name_for_home
+ name = profile_name_for_home(home) or "default"
+ slot_dir = S6ServiceManager().scandir / named_slot_name(name)
+ if slot_dir.is_dir() and (name == "default" or slot_is_up(name)):
+ found.append(("s6", False))
+ return found
with _home_env(home):
if gw.supports_systemd_services():
found.extend(("systemd", system) for system in (False, True) if gw.get_systemd_unit_path(system=system).exists())
@@ -310,6 +323,8 @@ def _systemd_service_user(home: Path, services: list[tuple[str, bool]]) -> Optio
def _service_op(kind: str, system: bool, verb: str, home: Path, *, run_as_user: Optional[str] = None) -> None:
"""``stop`` / ``uninstall`` / ``start`` / ``restart`` / ``install`` on ``home``'s service."""
+ if kind == "s6":
+ return _s6_slot_op(verb, home)
from hermes_cli import gateway as gw
with _home_env(home):
if verb == "install":
@@ -331,6 +346,21 @@ def _stop_gateway_process(home: Path) -> None:
_stop_gateway_process(home)
+def _s6_slot_op(verb: str, home: Path) -> None:
+ """The s6 leg of :func:`_service_op`. A named profile's slot is never uninstalled: it stays
+ registered DOWN (``down`` file) as the target of a later ``hermes -p X gateway start``, exactly
+ the shape the container's boot produces. The root slot is (re)started so it re-reads its config."""
+ from hermes_cli.gateway_multiplex_s6 import bring_root_slot_up, park_named_slot
+ from hermes_constants import profile_name_for_home
+ name = profile_name_for_home(home) or "default"
+ if name == "default":
+ if verb in ("start", "restart"):
+ bring_root_slot_up()
+ return # install/uninstall/stop of the root slot are not migration steps
+ if verb == "stop":
+ park_named_slot(name)
+
+
def _spawn_detached_gateway(home: Path) -> bool:
from hermes_cli import gateway as gw
with _home_env(home):
@@ -1105,19 +1135,23 @@ def rollback_migration(default_home: Optional[Path] = None) -> bool:
def _host_supports_migration() -> Optional[str]:
- """Reason the host cannot be converged by this command (s6 slots), else None.
+ """Reason the host cannot be converged by this command, else None.
- Windows IS handled now: per-profile Scheduled Tasks (and the Startup-folder fallback) are
- detected and removed like any other unit. s6 is not, and cannot be from here: the per-profile
- gateways are slots the container image registers at boot
- (``hermes_cli/container_boot.py::reconcile_profile_gateways``), so the convergence belongs to
- the container's own boot, not to a process inside it.
+ Windows IS handled (per-profile Scheduled Tasks and the Startup-folder fallback are removed
+ like any other unit). s6 IS handled too, in-process: a named profile's slot that is UP is
+ parked (``s6-svc -d`` + ``down`` file) and its autostart intent folded into the root slot the
+ same way the container's boot does it (``hermes_cli.gateway_multiplex_s6``). What cannot be
+ done from here is register a slot the boot never created — that is the one refusal left.
"""
from hermes_cli import gateway as gw
- if gw._running_under_s6():
- return ("s6-supervised container: per-profile gateways are s6 slots registered by the "
- "container's boot, not by this process. Restart the container so its boot "
- "reconciles them; nothing on this host was changed.")
+ if not gw._running_under_s6():
+ return None
+ from hermes_cli.gateway_multiplex_s6 import named_slot_name
+ from hermes_cli.service_manager import S6ServiceManager
+ scandir = S6ServiceManager().scandir
+ if not (scandir / named_slot_name("default")).is_dir():
+ return (f"s6-supervised container without a root gateway slot ({scandir / named_slot_name('default')}); "
+ "the container's boot registers it — restart the container.")
return None
diff --git a/hermes_cli/gateway_multiplex_mode.py b/hermes_cli/gateway_multiplex_mode.py
index 60cf9d63e3b..a2b871394c3 100644
--- a/hermes_cli/gateway_multiplex_mode.py
+++ b/hermes_cli/gateway_multiplex_mode.py
@@ -159,6 +159,32 @@ def implicit_multiplex_blocker() -> Optional[str]:
return None
+def _default_profile_home() -> Path:
+ from hermes_constants import get_default_hermes_root
+ return get_default_hermes_root()
+
+
+def persist_resolved_default(decision: MultiplexDecision, default_home: Optional[Path] = None) -> bool:
+ """Write ``gateway.multiplex_profiles: true`` into the DEFAULT profile's config.yaml once the
+ runtime has resolved the unset key to on, so the file reads as the gateway behaves ("left unset"
+ was read as "off" by more than one operator). Comment-preserving writer, once, never on a guard
+ refusal (the file would then promise a topology the gateway refused). Returns True on a write."""
+ if not decision.enabled or decision.source == "guard":
+ return False
+ default_home = Path(default_home) if default_home is not None else _default_profile_home()
+ try:
+ if explicit_multiplex_flag(default_home) is True:
+ return False
+ from hermes_cli.gateway_migrate import _write_multiplex_flag
+ _write_multiplex_flag(default_home, True)
+ except Exception:
+ logger.debug("could not persist gateway.multiplex_profiles: true", exc_info=True)
+ return False
+ logger.info("Wrote gateway.multiplex_profiles: true to %s (the resolved default, made explicit).",
+ default_home / "config.yaml")
+ return True
+
+
def resolve_multiplex_mode(config) -> MultiplexDecision:
"""Settle ``config.multiplex_profiles`` for one gateway boot; the config is updated in place.
@@ -212,5 +238,58 @@ def log_multiplex_decision(decision: MultiplexDecision) -> None:
logger.warning(
"This gateway stays standalone: %s. It serves only the launching profile.",
decision.reason)
+ for line in standalone_warning_lines(decision):
+ print(line)
elif decision.source == "default":
logger.info("Serving every profile on this host (gateway.multiplex_profiles unset; default on).")
+ persist_resolved_default(decision)
+
+
+def unserved_profiles() -> list[str]:
+ """Named profiles a standalone gateway leaves without a bot (the whole point of the warning)."""
+ from hermes_constants import get_hermes_home, profile_name_for_home
+ from hermes_cli.profiles import profiles_to_serve
+ me = profile_name_for_home(get_hermes_home()) or "default"
+ return [name for name, _home in profiles_to_serve(multiplex=True, include_parked=True) if name != me]
+
+
+def standalone_warning_lines(decision: MultiplexDecision, unserved: Optional[list[str]] = None) -> list[str]:
+ """The boxed warning a multi-profile host prints when a guard keeps its gateway standalone.
+
+ Empty for anything but a guard refusal on a host with other profiles to serve: a single-profile
+ install has nothing unserved, so there is nothing to shout about. The same box appears at
+ gateway start, in the ``hermes update`` summary and (as text) in the dashboard banner.
+ """
+ if decision.source != "guard" or decision.reason == SINGLE_PROFILE_REASON:
+ return []
+ if unserved is None:
+ try:
+ unserved = unserved_profiles()
+ except Exception:
+ unserved = []
+ if not unserved:
+ return []
+ from hermes_cli.gateway_migrate import MIGRATE_COMMAND
+ body = [
+ "⚠ This gateway is STANDALONE: it serves only its own profile.",
+ "Profiles NOT served (their bots stay silent): " + ", ".join(unserved),
+ f"Why: {decision.reason}",
+ f"Fix: {MIGRATE_COMMAND}",
+ ]
+ width = max(len(line) for line in body) + 2
+ return ["┌" + "─" * width + "┐",
+ *[f"│ {line.ljust(width - 1)}│" for line in body],
+ "└" + "─" * width + "┘"]
+
+
+def recorded_standalone_warning_lines() -> list[str]:
+ """Same box, rebuilt from the live gateway's ``gateway_state.json`` for processes that did not
+ make the decision (``hermes update``'s summary, ``hermes gateway status``)."""
+ try:
+ from gateway.status import read_runtime_status
+ reason = (read_runtime_status() or {}).get("multiplex_standalone_reason")
+ except Exception:
+ return []
+ if not reason:
+ return []
+ return standalone_warning_lines(MultiplexDecision(False, "guard", str(reason)))
diff --git a/hermes_cli/gateway_multiplex_s6.py b/hermes_cli/gateway_multiplex_s6.py
new file mode 100644
index 00000000000..1bdf8945c86
--- /dev/null
+++ b/hermes_cli/gateway_multiplex_s6.py
@@ -0,0 +1,108 @@
+"""s6 leg of the one-gateway-per-host convergence, shared by container boot and in-process migration.
+
+Inside the official image every profile has an s6 slot (``/run/service/gateway-<profile>``). The
+container's boot (``hermes_cli/container_boot.py``) registers every NAMED slot down and lets the
+root slot inherit their autostart intent; ``hermes gateway migrate --multiplex`` (and the hook
+``hermes update`` runs) must be able to do the same thing to a slot that is UP, from inside the
+running container, without a container restart. Both paths decide "which named intents fold into
+the root slot" through :func:`fold_named_slot_intent` so they can never disagree.
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Iterable, Optional, Sequence
+
+logger = logging.getLogger(__name__)
+
+#: Only this desired state autostarts; everything else (startup_failed, starting, stopped, missing)
+#: waits for the operator — no crash-loop of a broken gateway across ``docker restart``.
+AUTOSTART_STATES = frozenset({"running"})
+
+
+@dataclass(frozen=True)
+class FoldDecision:
+ #: Named profiles whose autostart intent the root slot takes over.
+ folded: tuple[str, ...]
+ #: Whether the root slot must be up after the fold.
+ root_should_start: bool
+
+
+def fold_named_slot_intent(default_prior_state: Optional[str],
+ named_states: Iterable[tuple[str, Optional[str]]]) -> FoldDecision:
+ """The ONE rule for folding per-profile s6 slots into the root slot.
+
+ A named slot is never booted from its own intent (a started named slot IS a second gateway on
+ this host); its ``running`` intent moves to the root slot, which is the process that serves it.
+ Without the fold an image only ever driven as ``hermes -p coder gateway start`` came up with
+ ZERO gateways: no root state, every named slot registered down, every action "registered".
+ """
+ folded = tuple(sorted(name for name, prior in named_states if prior in AUTOSTART_STATES))
+ return FoldDecision(folded=folded,
+ root_should_start=default_prior_state in AUTOSTART_STATES or bool(folded))
+
+
+def named_slot_name(profile: str) -> str:
+ from hermes_cli.service_manager import S6_SERVICE_PREFIX
+ return f"{S6_SERVICE_PREFIX}{profile}"
+
+
+def running_named_slots(profiles: Sequence[str], manager=None) -> list[str]:
+ """Named profiles whose s6 slot is UP right now — the only s6 state that is a second gateway.
+
+ A registered-down slot (what boot leaves behind) is a start target for ``hermes -p X gateway
+ start``, not a running gateway, and must never veto the multiplex default.
+ """
+ manager = manager or _manager()
+ up: list[str] = []
+ for profile in profiles:
+ if profile == "default":
+ continue
+ try:
+ if manager.is_running(named_slot_name(profile)):
+ up.append(profile)
+ except Exception: # an unprobeable slot is not a running gateway
+ logger.debug("could not probe s6 slot for %s", profile, exc_info=True)
+ return up
+
+
+def slot_is_up(profile: str, manager=None) -> bool:
+ return bool(running_named_slots([profile], manager))
+
+
+def park_named_slot(profile: str, manager=None) -> None:
+ """Stop a named profile's slot and write its ``down`` file so a supervisor restart does not
+ revive it (``s6-svc -d`` alone is undone by the next ``s6-svscanctl -a``/container restart)."""
+ manager = manager or _manager()
+ slot = named_slot_name(profile)
+ if manager.is_running(slot):
+ manager.stop(slot)
+ _wait_down(manager.scandir / slot)
+ (manager.scandir / slot / "down").touch()
+
+
+def _wait_down(service_dir: Path, timeout_ms: int = 15000) -> None:
+ from hermes_cli.service_manager import _s6_run
+ try:
+ _s6_run("s6-svwait", "-d", "-t", str(timeout_ms), str(service_dir), timeout=timeout_ms / 1000 + 5)
+ except Exception:
+ logger.debug("s6-svwait failed for %s", service_dir, exc_info=True)
+
+
+def bring_root_slot_up(manager=None) -> str:
+ """Start (or restart, so it re-reads its config) the root slot; returns a one-line description."""
+ manager = manager or _manager()
+ slot = named_slot_name("default")
+ (manager.scandir / slot / "down").unlink(missing_ok=True)
+ if manager.is_running(slot):
+ manager.restart(slot)
+ return "restarted the root gateway slot (s6)"
+ manager.start(slot)
+ return "started the root gateway slot (s6)"
+
+
+def _manager():
+ from hermes_cli.service_manager import S6ServiceManager
+ return S6ServiceManager()
diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.py
index 69468fad580..258ee2f6f27 100644
--- a/hermes_cli/update_cmd_maint.py
+++ b/hermes_cli/update_cmd_maint.py
@@ -394,6 +394,12 @@ def _print_update_summary(*, node_failures: list, desktop_build_ok: bool, pre_up
print(line)
else:
_print_update_completion(_update_complete_message(pre_update_version))
+ # A multi-profile host whose gateway came back standalone on a guard says so here too — the
+ # update summary is the one line operators read (the boot log under s6 is not).
+ with suppress(Exception):
+ from hermes_cli.gateway_multiplex_mode import recorded_standalone_warning_lines
+ for line in recorded_standalone_warning_lines():
+ print(line)
return desktop_build_ok and sqlite_runtime_ok
diff --git a/hermes_cli/web_routers/status.py b/hermes_cli/web_routers/status.py
index 99fcf9a1393..621771acabc 100644
--- a/hermes_cli/web_routers/status.py
+++ b/hermes_cli/web_routers/status.py
@@ -535,6 +535,7 @@ async def get_status(profile: Optional[str] = None):
status["profiles"] = topology["profiles"]
status["parked_profiles"] = topology.get("parked_profiles", [])
status["gateway_mode"] = topology["gateway_mode"]
+ status["multiplex_standalone_reason"] = topology.get("multiplex_standalone_reason")
# Host paths, gateway PID, internal health URL and per-gateway ports are deployment
# recon a liveness probe never needs, and on a gated bind *any* unauthenticated caller
diff --git a/hermes_cli/web_server_gateway.py b/hermes_cli/web_server_gateway.py
index 6f11807fdc6..66d64034cb3 100644
--- a/hermes_cli/web_server_gateway.py
+++ b/hermes_cli/web_server_gateway.py
@@ -156,6 +156,7 @@ def _collect_profile_gateway_topology() -> Dict[str, Any]:
gateways: List[Dict[str, Any]] = []
profile_platforms: Dict[str, dict] = {}
multiplex = False
+ standalone_reason: Optional[str] = None
for name, home in homes:
try:
# A served profile's liveness is the multiplexer's: listing it here showed one phantom
@@ -171,6 +172,8 @@ def _collect_profile_gateway_topology() -> Dict[str, Any]:
served = [str(p) for p in ((runtime or {}).get("served_profiles") or [])]
if name == "default" and len(served) > 1:
multiplex = True
+ if (runtime or {}).get("multiplex_standalone_reason"):
+ standalone_reason = str(runtime["multiplex_standalone_reason"])
plats = (runtime or {}).get("platforms")
owned: dict = {}
if isinstance(plats, dict) and plats:
@@ -188,10 +191,16 @@ def _collect_profile_gateway_topology() -> Dict[str, Any]:
mode = "multiplex"
else:
mode = {0: "none", 1: "single"}.get(len(gateways), "multiple")
+ # A guard refusal on a multi-profile host is what the dashboard banner shows; a single-profile
+ # install has nothing unserved and gets no banner.
+ from hermes_cli.gateway_multiplex_mode import SINGLE_PROFILE_REASON
+ if standalone_reason == SINGLE_PROFILE_REASON or len(homes) < 2:
+ standalone_reason = None
return {
"profiles": [name for name, _home in homes],
"parked_profiles": [name for name, home in homes if name != "default" and profile_is_parked(home)],
"gateway_mode": mode,
+ "multiplex_standalone_reason": standalone_reason,
"gateways": gateways,
"profile_platforms": profile_platforms}
diff --git a/tests/hermes_cli/test_gateway_multiplex_s6.py b/tests/hermes_cli/test_gateway_multiplex_s6.py
new file mode 100644
index 00000000000..53e2361ffdd
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_multiplex_s6.py
@@ -0,0 +1,116 @@
+"""s6 container: the unset multiplex default resolves ON when the boot has parked every named
+slot, ``hermes gateway migrate --multiplex`` folds an UP slot in-process, a guard refusal on a
+multi-profile host is loud, and the resolved default is written back to config.yaml."""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+import hermes_constants
+from hermes_cli import gateway as gw
+from hermes_cli import gateway_migrate as gm
+from hermes_cli import gateway_multiplex_mode as mode
+from hermes_cli import gateway_multiplex_s6 as s6
+from hermes_cli.container_boot import reconcile_profile_gateways
+from hermes_cli.service_manager import S6ServiceManager
+
+
+class _FakeS6:
+ """Slot state the way ``s6-svstat`` would report it, plus what stop/start would do to it."""
+
+ def __init__(self, scandir: Path, up: set[str]):
+ self.scandir, self.up, self.calls = scandir, set(up), []
+ for slot in ("gateway-default", "gateway-alpha", "gateway-beta"):
+ (scandir / slot).mkdir(parents=True)
+
+ def is_running(self, name):
+ return name in self.up
+
+ def stop(self, name):
+ self.calls.append(("stop", name)); self.up.discard(name)
+
+ def start(self, name):
+ self.calls.append(("start", name)); self.up.add(name)
+
+ def restart(self, name):
+ self.calls.append(("restart", name)); self.up.add(name)
+
+
+def s6_host(tmp_path, monkeypatch):
+ root = tmp_path / "data"
+ for sub in ("profiles/alpha", "profiles/beta"):
+ (root / sub).mkdir(parents=True)
+ (root / sub / "SOUL.md").write_text("x", encoding="utf-8")
+ (root / "config.yaml").write_text("# my config\nmodel:\n default: x\n", encoding="utf-8")
+ (root / ".env").write_text("TELEGRAM_BOT_TOKEN=111111:default-token\n", encoding="utf-8")
+ (root / "profiles/alpha/.env").write_text("TELEGRAM_BOT_TOKEN=222222:alpha-token\n", encoding="utf-8")
+ (root / "profiles/beta/.env").write_text("DISCORD_BOT_TOKEN=beta-discord-333333\n", encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(root))
+ for name in ("GATEWAY_MULTIPLEX_PROFILES", "TELEGRAM_BOT_TOKEN", "DISCORD_BOT_TOKEN", "API_SERVER_KEY"):
+ monkeypatch.delenv(name, raising=False)
+ monkeypatch.setattr(hermes_constants, "_default_hermes_root_memo", None)
+ scandir = tmp_path / "run-service"
+ fake = _FakeS6(scandir, up=set())
+ monkeypatch.setattr(gw, "_running_under_s6", lambda: True)
+ monkeypatch.setattr(S6ServiceManager, "__init__", lambda self, scandir=scandir: setattr(self, "scandir", scandir))
+ monkeypatch.setattr(s6, "_manager", lambda: fake)
+ monkeypatch.setattr(s6, "_wait_down", lambda service_dir, timeout_ms=0: None)
+ monkeypatch.setattr(gm, "_live_gateway_pid", lambda home: None)
+ monkeypatch.setattr(gm, "_wait_for_served", lambda home, expected, timeout: sorted(expected))
+ return root, fake
+
+
+def test_parked_named_slots_do_not_veto_the_unset_default(s6_host):
+ """The user's exact scenario: boot parked alpha+beta down, key unset → the guard must let the
+ default apply (only an UP named slot is a second gateway). Base refused with 'Restart the container'."""
+ root, fake = s6_host
+ from gateway.config import GatewayConfig
+ decision = mode.resolve_multiplex_mode(GatewayConfig.from_dict({}))
+ assert (decision.enabled, decision.source) == (True, "default"), decision
+ fake.up.add("gateway-alpha")
+ blocked = mode.resolve_multiplex_mode(GatewayConfig.from_dict({}))
+ assert blocked.source == "guard" and "alpha" in blocked.reason
+
+
+def test_migrate_folds_an_up_named_slot_in_process_and_boot_shares_the_rule(s6_host, tmp_path):
+ """In-container convergence: an UP alpha slot is stopped + parked (down file), the root slot
+ (re)started, no container restart. The fold rule is the ONE ``fold_named_slot_intent``."""
+ root, fake = s6_host
+ fake.up.update({"gateway-alpha", "gateway-default"})
+ plan = gm.build_migration_plan()
+ assert [p.name for p in plan.standalone_secondaries] == ["alpha"]
+ assert gm.apply_migration(plan, served_wait=0) is True
+ assert ("stop", "gateway-alpha") in fake.calls and ("restart", "gateway-default") in fake.calls
+ assert (fake.scandir / "gateway-alpha" / "down").exists()
+ assert "gateway-alpha" not in fake.up and "gateway-default" in fake.up
+ assert mode.explicit_multiplex_flag(root) is True
+ # Boot and migration fold through the same function: a running named intent moves to the root.
+ fold = s6.fold_named_slot_intent(None, [("alpha", "running"), ("beta", "stopped")])
+ assert fold == s6.FoldDecision(folded=("alpha",), root_should_start=True)
+ (root / "profiles/alpha/gateway_state.json").write_text('{"desired_state": "running"}', encoding="utf-8")
+ actions = {a.profile: a for a in reconcile_profile_gateways(
+ hermes_home=root, scandir=tmp_path / "boot-svc", dry_run=True, container_argv=())}
+ assert actions["default"].action == "started" and actions["alpha"].folded_into_root
+
+
+def test_standalone_box_names_unserved_profiles_and_is_silent_for_single_profile(s6_host):
+ guard = mode.MultiplexDecision(False, "guard", "profile(s) 'alpha' still run their own gateway")
+ lines = mode.standalone_warning_lines(guard)
+ assert lines[0].startswith("┌") and lines[-1].startswith("└")
+ assert any("alpha, beta" in line for line in lines) and any("migrate --multiplex" in line for line in lines)
+ assert mode.standalone_warning_lines(mode.MultiplexDecision(False, "guard", mode.SINGLE_PROFILE_REASON)) == []
+ assert mode.standalone_warning_lines(mode.MultiplexDecision(True, "default", "unset")) == []
+
+
+def test_resolved_default_is_written_once_and_never_on_a_guard(s6_host):
+ root, _fake = s6_host
+ guard = mode.MultiplexDecision(False, "guard", "profile(s) 'alpha' still run their own gateway")
+ assert mode.persist_resolved_default(guard, root) is False
+ assert mode.explicit_multiplex_flag(root) is None
+ on = mode.MultiplexDecision(True, "default", "unset; default applies")
+ assert mode.persist_resolved_default(on, root) is True
+ text = (root / "config.yaml").read_text(encoding="utf-8")
+ assert "# my config" in text and "multiplex_profiles: true" in text # comment-preserving writer
+ assert mode.persist_resolved_default(on, root) is False # already explicit: once
diff --git a/web/src/App.tsx b/web/src/App.tsx
index 9a611a5399c..4dd47f27e04 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -73,6 +73,7 @@ import { useProfileScope } from "@/contexts/useProfileScope";
import { ProfileSwitcher } from "@/components/ProfileSwitcher";
import { ProfileScopeBanner } from "@/components/ProfileScopeBanner";
import { MemoryPressureBanner } from "@/components/MemoryPressureBanner";
+import { MultiplexStandaloneBanner } from "@/components/MultiplexStandaloneBanner";
import { useSystemActions } from "@/contexts/useSystemActions";
import type { SystemAction } from "@/contexts/system-actions-context";
// Route pages are lazy-loaded so the initial dashboard shell does not pay for
@@ -576,6 +577,7 @@ export default function App() {
<PluginSlot name="header-banner" />
<ProfileScopeBanner />
<MemoryPressureBanner status={sidebarStatus} />
+ <MultiplexStandaloneBanner status={sidebarStatus} />
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
<div className="flex min-h-0 min-w-0 flex-1">
diff --git a/web/src/components/MultiplexStandaloneBanner.tsx b/web/src/components/MultiplexStandaloneBanner.tsx
new file mode 100644
index 00000000000..d84e6a89ecf
--- /dev/null
+++ b/web/src/components/MultiplexStandaloneBanner.tsx
@@ -0,0 +1,66 @@
+import { useState } from "react";
+import { AlertTriangle, X } from "lucide-react";
+import type { StatusResponse } from "@/lib/api";
+import { useI18n } from "@/i18n";
+
+/**
+ * A multi-profile host whose gateway came up STANDALONE on a boot guard: every other
+ * profile's bot is silent until `hermes gateway migrate --multiplex` runs. The backend only
+ * sets `multiplex_standalone_reason` when there is something unserved (never for a
+ * single-profile install), so presence == show. Dismissal is session-scoped and keyed on the
+ * reason text so a different blocker re-surfaces.
+ */
+const STORAGE_KEY = "multiplexStandaloneBannerDismissed";
+
+export function MultiplexStandaloneBanner({
+ status,
+}: {
+ status: StatusResponse | null;
+}) {
+ const { t } = useI18n();
+ const reason = status?.multiplex_standalone_reason ?? null;
+ const [dismissed, setDismissed] = useState<string | null>(() => {
+ try {
+ return sessionStorage.getItem(STORAGE_KEY);
+ } catch {
+ return null;
+ }
+ });
+ if (!reason || dismissed === reason) return null;
+
+ const unserved = (status?.profiles ?? []).filter((p) => p !== "default");
+ const template =
+ t.app.multiplexStandaloneBanner ??
+ "Your gateway serves only one profile. Not served: {profiles}. Why: {reason}. Fix: hermes gateway migrate --multiplex";
+ const message = template
+ .replace("{profiles}", unserved.length > 0 ? unserved.join(", ") : "—")
+ .replace("{reason}", reason);
+
+ const dismiss = () => {
+ try {
+ sessionStorage.setItem(STORAGE_KEY, reason);
+ } catch {
+ /* ignore */
+ }
+ setDismissed(reason);
+ };
+
+ return (
+ <div
+ role="alert"
+ data-testid="multiplex-standalone-banner"
+ className="flex items-center gap-2 border-b border-amber-500/40 bg-amber-500/10 px-4 py-1.5 text-xs text-amber-300"
+ >
+ <AlertTriangle className="h-3.5 w-3.5 shrink-0" />
+ <span className="min-w-0 flex-1">{message}</span>
+ <button
+ type="button"
+ aria-label={t.app.dismiss ?? "Dismiss"}
+ onClick={dismiss}
+ className="shrink-0 opacity-70 hover:opacity-100"
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ </div>
+ );
+}
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index d2cfa1ba8b7..6e70c305b06 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -110,6 +110,8 @@ export const en: Translations = {
"Your agent's disk is almost full. New messages, memories, and settings may fail to save.",
diskElevatedBanner:
"Your agent's disk is filling up. Consider clearing old sessions or expanding its storage.",
+ multiplexStandaloneBanner:
+ "Your gateway serves only one profile. Not served: {profiles}. Why: {reason}. Fix: hermes gateway migrate --multiplex",
dismiss: "Dismiss",
},
diff --git a/web/src/i18n/types.ts b/web/src/i18n/types.ts
index ea0597f4755..bddad31aca3 100644
--- a/web/src/i18n/types.ts
+++ b/web/src/i18n/types.ts
@@ -127,6 +127,8 @@ export interface Translations {
/** NS-656 disk-usage banner — optional, English fallback. */
diskCriticalBanner?: string;
diskElevatedBanner?: string;
+ /** Multi-profile host whose gateway boots standalone on a guard — optional, English fallback. */
+ multiplexStandaloneBanner?: string;
dismiss?: string;
};
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index f9ff67aa433..33aeedcc7c9 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -1998,6 +1998,13 @@ export interface StatusResponse {
config_version: number;
env_path: string;
gateway_exit_reason: string | null;
+ /** Why a multi-profile host's gateway came up STANDALONE on a boot guard (unset
+ * ``gateway.multiplex_profiles`` refused): the other profiles' bots are silent until
+ * ``hermes gateway migrate --multiplex`` runs. null/absent when it multiplexes or only one
+ * profile exists. */
+ multiplex_standalone_reason?: string | null;
+ /** Every profile installed on this host (multiplex or not). */
+ profiles?: string[];
gateway_health_url: string | null;
/** Seconds since the gateway's housekeeping last stamped gateway_state.json, set only when the
* process is alive but the stamp is past the freshness TTL (loop/housekeeping wedged).