The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): surface secondary WhatsApp/Relay skipped under multiplex instead of a silent continue
teknium1395e4248d096
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.pyindex 1246f3542fe..46897b6c3e7 100644--- a/gateway/run_adapters.py+++ b/gateway/run_adapters.py@@ -955,6 +955,45 @@ class GatewayAdapterLifecycleMixin:)return True+ def _note_unserved_secondary_platform(self, profile_name: str, platform: Platform) -> None:+ """A secondary enabled a shared-ingress platform (Relay, WhatsApp) the multiplexer only runs on+ the default profile. Log the reason + remedy once per (profile, platform) and stamp a+ ``<profile>:<platform>`` status entry so ``hermes gateway status --profile X`` and the+ dashboard show *why* the channel is dead instead of nothing at all."""+ noted = getattr(self, "_unserved_secondary_platforms", None)+ if noted is None:+ noted = self._unserved_secondary_platforms = set()+ if (profile_name, platform) in noted:+ return+ noted.add((profile_name, platform))+ pv = platform.value+ logger.info(+ "[MULTIPLEX] Profile '%s': %s is enabled but not served — %s is process-level shared ingress "+ "owned by the default profile under multiplex. Enable and configure %s on the default profile "+ "(it serves every profile), or disable it in profile '%s'.",+ profile_name, pv, pv, pv, profile_name,+ )+ self._update_platform_runtime_status(+ f"{profile_name}:{pv}", platform_state="disabled", error_code="multiplex_shared_ingress",+ error_message="not served under multiplex (shared ingress owned by default)",+ )++ def _unserved_shared_ingress_warnings(self) -> list:+ """Loud ``not being served`` lines for shared-ingress platforms secondaries enabled while+ NO profile (default included) actually runs them; empty when the default serves the platform."""+ noted = getattr(self, "_unserved_secondary_platforms", None) or ()+ lines = []+ for platform in sorted({p for _n, p in noted}, key=lambda p: p.value):+ if platform in self.adapters or platform in (getattr(self, "_failed_platforms", None) or {}):+ continue # the default owns it: secondaries ARE served through the shared adapter+ profiles = sorted(n for n, p in noted if p is platform)+ lines.append(+ f"{platform.value} is enabled in profile(s) {', '.join(profiles)} but not on the default "+ f"profile — the platform is not being served. Under multiplex {platform.value} is shared "+ "ingress: enable and configure it on the default profile, or disable it in those profiles."+ )+ return lines+async def _start_one_profile_adapters(self, profile_name: str, profile_home: "Path", claimed: Dict[tuple, str]) -> int:@@ -980,7 +1019,9 @@ class GatewayAdapterLifecycleMixin:)continue# Relay/WhatsApp are shared process-level ingress under multiplex; a secondary would retry-loop.+ # Say so: four profiles with WHATSAPP_ENABLED=true and nothing in the log is a silent dead channel.if multiplex and platform in (Platform.RELAY, Platform.WHATSAPP):+ self._note_unserved_secondary_platform(profile_name, platform)continue# api_server / webhook: the default's listener already mirrors them at /p/<profile>/; a second# instance here would fight the default for the port (#100397).diff --git a/gateway/run_startup.py b/gateway/run_startup.pyindex 4ee1d76eb46..e6684c1ca19 100644--- a/gateway/run_startup.py+++ b/gateway/run_startup.py@@ -1159,8 +1159,7 @@ class GatewayStartupMixin:# Startup authority is one phase: from here on every adapter retry is non-evicting.self._platform_lock_takeover_on_start = False# A platform skipped on the primary should have been picked up by a secondary owning the token;- # if none did it is enabled yet silently unserved — say so loudly.- # If none did, the platform is enabled in config.yaml yet silently unserved — surface it loudly so+ # if none did, the platform is enabled in config.yaml yet silently unserved — surface it loudly so# the operator sees a config problem instead of a quiet dead channel (#64674 follow-up).for _skipped in _multiplex_skipped_platforms:if not any(_skipped in _profile_map for _profile_map in self._profile_adapters.values()):@@ -1169,6 +1168,9 @@ class GatewayStartupMixin:"the platform is not being served. Add its token to the profile that should ""own it, or disable the platform.", _skipped.value,)+ # The mirror image: a SECONDARY enabled shared ingress (WhatsApp/Relay) that only the default can run.+ for _line in self._unserved_shared_ingress_warnings():+ logger.warning(_line)return False, connected_countdef _start_handle_no_connections(diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex fd5bd8e25bf..aff93d5bd75 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -1499,6 +1499,22 @@ def _print_served_ingress_urls(profile: str | None = None) -> None:print(line)+def _print_unserved_shared_ingress(profile: str | None) -> None:+ """Shared-ingress platforms (WhatsApp/Relay) this served profile enabled that the multiplexer runs+ only on the default profile — the ``whatsapp: not served under multiplex`` line."""+ try:+ from hermes_cli.gateway_multiplex_served import served_profile_unserved_platforms+ unserved = served_profile_unserved_platforms(profile or "")+ except Exception:+ return+ if not unserved:+ return+ print()+ for platform, reason in sorted(unserved.items()):+ print(f" ⚠ {platform}: {reason}")+ print(" Enable it on the default profile (shared ingress serves every profile), or disable it here.")++def _print_other_profiles_gateway_status() -> None:"""Print other profiles' running gateways at the bottom of ``hermes gateway status``."""try:@@ -6350,6 +6366,7 @@ def _cmd_status(args):print("✓ Gateway is running via the default-profile multiplexer")print(" Manage it from the default profile: hermes gateway status")_print_served_ingress_urls(get_active_profile_name())+ _print_unserved_shared_ingress(get_active_profile_name())elif (kind := _installed_service_kind_for(lambda: _windows_service_installed)) is not None:if kind == "systemd":systemd_status(deep, system=system, full=full)diff --git a/hermes_cli/gateway_multiplex_served.py b/hermes_cli/gateway_multiplex_served.pyindex e69c60e86a6..ace60640877 100644--- a/hermes_cli/gateway_multiplex_served.py+++ b/hermes_cli/gateway_multiplex_served.py@@ -48,6 +48,27 @@ def multiplexer_served_secondaries() -> list[str]:return [p for p in (recorded_served_profiles() or []) if p and p != "default"]+def served_profile_unserved_platforms(profile: str) -> dict[str, str]:+ """``{platform: reason}`` for a served profile's platforms the multiplexer deliberately does not run+ (WhatsApp/Relay are shared ingress owned by the default; ``gateway.run_adapters`` stamps+ ``<profile>:<platform>`` as ``disabled`` with ``error_code=multiplex_shared_ingress``)."""+ from hermes_constants import get_default_hermes_root+ from gateway.status import read_runtime_status+ if not profile or live_default_gateway_pid() is None:+ return {}+ runtime = read_runtime_status(get_default_hermes_root() / "gateway_state.json") or {}+ platforms = runtime.get("platforms")+ if not isinstance(platforms, dict):+ return {}+ prefix = f"{profile}:"+ return {+ key[len(prefix):]: str(entry.get("error_message") or "not served under multiplex")+ for key, entry in platforms.items()+ if isinstance(key, str) and key.startswith(prefix) and isinstance(entry, dict)+ and entry.get("error_code") == "multiplex_shared_ingress"+ }++def served_profile_ingress_urls(profile: Optional[str] = None) -> dict[str, dict[str, str]]:"""``{profile: {platform: url}}`` for every secondary inbound-port platform the live multiplexerserves on its shared listener (``<profile>:<platform>`` entries carrying ``ingress_url``). This isdiff --git a/hermes_cli/relay_plugin_migrate.py b/hermes_cli/relay_plugin_migrate.pynew file mode 100644index 00000000000..bf2606c6735--- /dev/null+++ b/hermes_cli/relay_plugin_migrate.py@@ -0,0 +1,261 @@+"""Migrate legacy ``HERMES_NEMO_RELAY_ATIF_*`` / ``ATOF_*`` exporter vars into a Relay ``plugins.toml``.++The Relay cutover (Aug 2026) stopped honouring the legacy exporter variables: a profile that still+carries them and no ``HERMES_NEMO_RELAY_PLUGINS_TOML`` logs one warning and initialises NO exporters,+so users who followed the earlier docs lost every trace silently. This module turns those variables+into ``<profile home>/relay-plugins.toml`` (built from the ``nemo_relay.observability`` dataclasses so+the file is exactly what Relay validates), points ``HERMES_NEMO_RELAY_PLUGINS_TOML`` at it, and+comments the legacy lines out. It runs from ``hermes update`` for every profile home and from+``hermes relay migrate`` for the active one.+"""++from __future__ import annotations++import logging+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Mapping, Optional++from hermes_cli.relay_plugin_cutover import (+ LEGACY_RELAY_EXPORT_ENV_VARS, RELAY_PLUGINS_CONFIG_ENV, configured_legacy_relay_env_vars)++logger = logging.getLogger(__name__)++RELAY_PLUGINS_TOML_NAME = "relay-plugins.toml"++_TRUE = {"1", "true", "yes", "on"}+++@dataclass+class RelayMigrationResult:+ home: Path+ toml_path: Optional[Path] = None+ migrated_vars: tuple[str, ...] = ()+ skipped_reason: Optional[str] = None+ validation_error: Optional[str] = None+ diagnostics: list = field(default_factory=list)++ @property+ def migrated(self) -> bool:+ return self.toml_path is not None and self.skipped_reason is None+++def _truthy(value: Any) -> bool:+ return str(value or "").strip().lower() in _TRUE+++def _s(env: Mapping[str, Any], name: str, default: str = "") -> str:+ return str(env.get(name) or "").strip() or default+++def relay_plugin_payload_from_legacy_env(env: Mapping[str, Any]) -> dict[str, Any]:+ """The plugins.toml document (as a dict) equivalent to the legacy exporter variables. Defaults+ mirror the removed ``plugins/observability/nemo_relay`` plugin so a migrated user keeps the+ same files in the same places. Built through ``nemo_relay.observability`` so the sink+ discriminator (``type = "file"``) and every field name are the ones Relay validates."""+ from nemo_relay import observability as obs++ atif = atof = None+ if _truthy(env.get("HERMES_NEMO_RELAY_ATIF_ENABLED")):+ kwargs: dict[str, Any] = {+ "enabled": True,+ "agent_name": _s(env, "HERMES_NEMO_RELAY_ATIF_AGENT_NAME", "Hermes Agent"),+ "model_name": _s(env, "HERMES_NEMO_RELAY_ATIF_MODEL_NAME", "unknown"),+ "filename_template": _s(env, "HERMES_NEMO_RELAY_ATIF_FILENAME_TEMPLATE", "hermes-atif-{session_id}.json"),+ }+ if _s(env, "HERMES_NEMO_RELAY_ATIF_OUTPUT_DIRECTORY"):+ kwargs["output_directory"] = _s(env, "HERMES_NEMO_RELAY_ATIF_OUTPUT_DIRECTORY")+ if _s(env, "HERMES_NEMO_RELAY_ATIF_AGENT_VERSION"):+ kwargs["agent_version"] = _s(env, "HERMES_NEMO_RELAY_ATIF_AGENT_VERSION")+ atif = obs.AtifConfig(**kwargs)+ if _truthy(env.get("HERMES_NEMO_RELAY_ATOF_ENABLED")):+ mode = _s(env, "HERMES_NEMO_RELAY_ATOF_MODE", "append").lower()+ sink = obs.AtofFileSinkConfig(+ output_directory=_s(env, "HERMES_NEMO_RELAY_ATOF_OUTPUT_DIRECTORY") or None,+ filename=_s(env, "HERMES_NEMO_RELAY_ATOF_FILENAME", "hermes-atof.jsonl"),+ mode="overwrite" if mode == "overwrite" else "append",+ )+ atof = obs.AtofConfig(enabled=True, sinks=[sink])+ spec = obs.ComponentSpec(config=obs.ObservabilityConfig(atif=atif, atof=atof))+ return {"version": 1, "components": [spec.to_dict()]}+++def _toml_scalar(value: Any) -> str:+ if isinstance(value, bool):+ return "true" if value else "false"+ if isinstance(value, (int, float)):+ return repr(value)+ text = str(value).replace("\\", "\\\\").replace('"', '\\"')+ return f'"{text}"'+++def _emit_table(lines: list[str], path: str, table: Mapping[str, Any], *, array_item: bool = False) -> None:+ """Minimal TOML emitter for the nested-dict/list-of-dict shape ``to_dict()`` produces."""+ scalars = {k: v for k, v in table.items() if not isinstance(v, (dict, list))}+ nested = {k: v for k, v in table.items() if isinstance(v, (dict, list))}+ if path:+ lines.append(f"[[{path}]]" if array_item else f"[{path}]")+ for key, value in scalars.items():+ if value is not None:+ lines.append(f"{key} = {_toml_scalar(value)}")+ for key, value in nested.items():+ child = f"{path}.{key}" if path else key+ if isinstance(value, dict):+ lines.append("")+ _emit_table(lines, child, value)+ else:+ for item in value:+ if isinstance(item, dict):+ lines.append("")+ _emit_table(lines, child, item, array_item=True)+ else:+ raise ValueError(f"unsupported TOML array item at {child}: {item!r}")+++def dumps_toml(document: Mapping[str, Any]) -> str:+ """Serialize via ``tomli_w`` when installed, else the minimal emitter above (nested tables + arrays+ of tables only — exactly the ``ComponentSpec.to_dict()`` shape)."""+ try:+ import tomli_w # type: ignore+ return tomli_w.dumps(dict(document))+ except ImportError:+ lines: list[str] = []+ _emit_table(lines, "", document)+ return "\n".join(lines).strip() + "\n"+++def validate_relay_plugin_payload(payload: Mapping[str, Any]) -> list:+ """Activate the payload once through Relay's own validator and clear it; returns the diagnostics+ (empty = clean). Raises when Relay rejects the document outright."""+ import asyncio+ from nemo_relay import plugin++ async def _probe():+ try:+ report = await plugin.initialize(dict(payload))+ finally:+ await plugin.clear_async()+ return list((report or {}).get("diagnostics") or []) if isinstance(report, dict) else []++ try:+ asyncio.get_running_loop()+ except RuntimeError:+ return asyncio.run(_probe())+ import concurrent.futures+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:+ return pool.submit(lambda: asyncio.run(_probe())).result()+++def _comment_out_legacy_lines(lines: list[str], names: set[str]) -> list[str]:+ from hermes_cli.config import _env_line_defines_key+ out = []+ for line in lines:+ if any(_env_line_defines_key(line, name) for name in names):+ out.append(f"# migrated to {RELAY_PLUGINS_TOML_NAME}: {line.rstrip()}\n")+ else:+ out.append(line)+ return out+++def migrate_profile_relay_env(home: Path, *, validate: bool = True) -> RelayMigrationResult:+ """Migrate ONE profile home's ``.env``. Never raises for a no-op; a Relay import/validation failure+ leaves ``.env`` untouched and is reported in ``validation_error``."""+ from hermes_cli.config import _env_line_defines_key, _quote_env_value, _read_env_lines, _write_env_lines+ result = RelayMigrationResult(home=home)+ env_path = home / ".env"+ if not env_path.is_file():+ result.skipped_reason = "no .env"+ return result+ lines = _read_env_lines(env_path)+ env: dict[str, str] = {}+ for line in lines:+ stripped = line.strip()+ if not stripped or stripped.startswith("#") or "=" not in stripped:+ continue+ key, _, value = stripped.removeprefix("export ").partition("=")+ env[key.strip()] = value.strip().strip("'\"")+ legacy = configured_legacy_relay_env_vars(env)+ if not legacy:+ result.skipped_reason = "no legacy exporter variables"+ return result+ if env.get(RELAY_PLUGINS_CONFIG_ENV, "").strip():+ result.skipped_reason = f"{RELAY_PLUGINS_CONFIG_ENV} already set"+ return result+ if not (_truthy(env.get("HERMES_NEMO_RELAY_ATIF_ENABLED")) or _truthy(env.get("HERMES_NEMO_RELAY_ATOF_ENABLED"))):+ result.skipped_reason = "no exporter enabled by the legacy variables"+ return result+ try:+ payload = relay_plugin_payload_from_legacy_env(env)+ if validate:+ result.diagnostics = validate_relay_plugin_payload(payload)+ except Exception as exc: # nemo_relay missing or rejecting the payload: leave .env alone+ result.validation_error = f"{type(exc).__name__}: {exc}"+ return result+ toml_path = home / RELAY_PLUGINS_TOML_NAME+ header = (+ "# NeMo Relay plugin configuration for Hermes (selected via "+ f"{RELAY_PLUGINS_CONFIG_ENV} in .env).\n"+ "# Generated by `hermes update` from the legacy HERMES_NEMO_RELAY_ATIF_*/ATOF_* variables,\n"+ "# which Relay no longer reads. Edit this file to change exporters.\n"+ )+ toml_path.write_text(header + dumps_toml(payload), encoding="utf-8")+ new_lines = _comment_out_legacy_lines(lines, set(LEGACY_RELAY_EXPORT_ENV_VARS))+ if not any(_env_line_defines_key(line, RELAY_PLUGINS_CONFIG_ENV) for line in new_lines):+ if new_lines and not new_lines[-1].endswith("\n"):+ new_lines[-1] += "\n"+ new_lines.append(f"{RELAY_PLUGINS_CONFIG_ENV}={_quote_env_value(str(toml_path))}\n")+ _write_env_lines(env_path, new_lines, preserve_mode=True)+ result.toml_path = toml_path+ result.migrated_vars = legacy+ return result+++def migrate_all_profile_relay_envs(*, validate: bool = True) -> list[RelayMigrationResult]:+ """Default home + every live named profile (multiplex: each profile keeps its own TOML)."""+ from hermes_cli.profiles import _get_default_hermes_home, _iter_named_profile_dirs+ homes = [_get_default_hermes_home(), *_iter_named_profile_dirs()]+ return [migrate_profile_relay_env(home, validate=validate) for home in homes]+++def print_relay_migration_report(results: list[RelayMigrationResult]) -> None:+ """Loud, actionable notice for `hermes update` / `hermes relay migrate`."""+ migrated = [r for r in results if r.migrated]+ failed = [r for r in results if r.validation_error]+ if not migrated and not failed:+ return+ print()+ if migrated:+ print("\033[1;33m⚠ NeMo Relay exporter configuration migrated\033[0m")+ print(" The legacy HERMES_NEMO_RELAY_ATIF_*/ATOF_* variables stopped producing traces after the")+ print(" Relay cutover. Each profile below now has a generated relay-plugins.toml selected by")+ print(f" {RELAY_PLUGINS_CONFIG_ENV} in its .env (legacy lines commented out, not deleted):")+ for r in migrated:+ extra = f" ({len(r.diagnostics)} Relay diagnostic(s))" if r.diagnostics else ""+ label = r.home.name if r.home.parent.name == "profiles" else "default"+ print(f" • {label}: {r.toml_path}{extra}")+ print(" Restart the gateway to resume exports. Review the file and adjust paths if needed.")+ for r in failed:+ print(f" ✗ {r.home}: could not migrate Relay exporter vars — {r.validation_error}")+ print(f" Write {r.home / RELAY_PLUGINS_TOML_NAME} by hand and set {RELAY_PLUGINS_CONFIG_ENV}.")+++def run_relay_migration_after_update() -> None:+ """`hermes update` hook: migrate every profile home, print the notice. Best-effort by contract."""+ print_relay_migration_report(migrate_all_profile_relay_envs())+++RELAY_MIGRATE_COMMAND = "hermes migrate relay"+++def cmd_migrate_relay(args) -> None:+ """``hermes migrate relay [--all-profiles] [--no-validate]``."""+ from hermes_constants import get_hermes_home+ validate = not getattr(args, "no_validate", False)+ if getattr(args, "all_profiles", False):+ results = migrate_all_profile_relay_envs(validate=validate)+ else:+ results = [migrate_profile_relay_env(get_hermes_home(), validate=validate)]+ print_relay_migration_report(results)+ for r in results:+ if not r.migrated and not r.validation_error:+ print(f" {r.home}: nothing to migrate ({r.skipped_reason}).")diff --git a/hermes_cli/web_routers/status.py b/hermes_cli/web_routers/status.pyindex d4d8b0b6522..9360f5fa781 100644--- a/hermes_cli/web_routers/status.py+++ b/hermes_cli/web_routers/status.py@@ -350,11 +350,14 @@ async def _component_health(gateway: Dict[str, Any]) -> Dict[str, Any]:components["storage"] = {"status": storage_check.get("status", "degraded")}except Exception:components["storage"] = {"status": "degraded"}+ # ``disabled`` entries are platforms the multiplexer deliberately does not run for a served profile+ # (shared ingress owned by the default) — informational, never a degraded verdict.platform_states = [str(value.get("state") or value.get("status") or "").lower()for value in gateway_platforms.values() if isinstance(value, dict)]+ platform_states = [state for state in platform_states if state != "disabled"]connected = sum(1 for state in platform_states if state in _HEALTHY_PLATFORM_STATES)components["platforms"] = {"status": "ok" if connected == len(platform_states) else "degraded",- "configured": len(gateway_platforms), "connected": connected}+ "configured": len(platform_states), "connected": connected}return componentsdiff --git a/tests/gateway/test_multiplex_unserved_shared_ingress.py b/tests/gateway/test_multiplex_unserved_shared_ingress.pynew file mode 100644index 00000000000..515bcdcfbcd--- /dev/null+++ b/tests/gateway/test_multiplex_unserved_shared_ingress.py@@ -0,0 +1,101 @@+"""Multiplex secondaries that enable shared-ingress platforms (WhatsApp/Relay) must not be+silently unserved: one INFO per skipped platform, a stamped ``<profile>:<platform>`` status+entry, and the loud "not being served" WARNING when no profile (default included) runs it."""++from __future__ import annotations++import logging+from contextlib import contextmanager+from pathlib import Path++import pytest++from gateway import run as gateway_run+from gateway.config import GatewayConfig, Platform, PlatformConfig+from gateway.run import GatewayRunner+++def _runner():+ runner = GatewayRunner.__new__(GatewayRunner)+ runner.config = GatewayConfig(multiplex_profiles=True)+ runner._running = True+ runner.adapters = {}+ runner._failed_platforms = {}+ runner._profile_adapters = {}+ runner._profile_failed_platforms = {}+ runner._background_tasks = set()+ runner._snapshot_profile_busy_modes = lambda *a, **k: None+ runner._platform_lock_takeover_on_start = True+ runner._startup_fail_fatal_config = lambda reason: None+ return runner+++def _install_secondary(monkeypatch, runner, stamps):+ @contextmanager+ def fake_scope(profile_home, *, hydrate_secrets=True):+ yield++ monkeypatch.setattr(gateway_run, "_profile_runtime_scope", fake_scope)+ monkeypatch.setattr(gateway_run, "_load_gateway_config", lambda: {})+ monkeypatch.setattr("hermes_cli.env_loader.hydrate_profile_secret_sources", lambda home: {})+ monkeypatch.setattr("hermes_cli.plugins.discover_plugins", lambda: None)+ monkeypatch.setattr(+ "gateway.config.load_gateway_config",+ lambda: GatewayConfig(+ multiplex_profiles=True,+ platforms={Platform.WHATSAPP: PlatformConfig(enabled=True)},+ ),+ )+ monkeypatch.setattr(+ runner, "_update_platform_runtime_status",+ lambda key, **kw: stamps.append((key, kw)),+ )+ runner._create_adapter = lambda platform, config: pytest.fail("shared ingress must never build a secondary adapter")+++async def test_secondary_whatsapp_without_primary_is_reported_unserved(monkeypatch, caplog):+ runner = _runner()+ stamps = []+ _install_secondary(monkeypatch, runner, stamps)++ with caplog.at_level(logging.INFO, logger="gateway.run"):+ assert await runner._start_one_profile_adapters("work", Path("/profiles/work"), {}) == 0+ # The secondary was skipped: the startup phase folds it into the loud warning.+ aborted, _count = await runner._start_secondary_profiles(0, [])++ assert aborted is False+ infos = [r for r in caplog.records if r.levelno == logging.INFO and "not served" in r.getMessage()]+ assert infos and "'work'" in infos[0].getMessage() and "default profile" in infos[0].getMessage()+ warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]+ assert any("whatsapp" in w and "not being served" in w and "work" in w for w in warnings), warnings+ # Stamped so `hermes gateway status --profile work` / the dashboard can show the reason.+ assert ("work:whatsapp", {+ "platform_state": "disabled", "error_code": "multiplex_shared_ingress",+ "error_message": "not served under multiplex (shared ingress owned by default)",+ }) in stamps+ # ...and the CLI reader turns that stamp into the status line.+ from gateway.status import write_runtime_status+ from hermes_cli import gateway_multiplex_served as served+ key, kw = next(s for s in stamps if s[0] == "work:whatsapp")+ write_runtime_status(platform=key, **kw)+ monkeypatch.setattr(served, "live_default_gateway_pid", lambda: 4242)+ assert served.served_profile_unserved_platforms("work") == {+ "whatsapp": "not served under multiplex (shared ingress owned by default)"}+ assert served.served_profile_unserved_platforms("other") == {}+++async def test_secondary_whatsapp_served_by_default_is_not_warned(monkeypatch, caplog):+ """The default owns WhatsApp: the secondary IS served through the shared adapter — no WARNING,+ the INFO line still explains where the channel lives."""+ runner = _runner()+ runner.adapters[Platform.WHATSAPP] = object()+ _install_secondary(monkeypatch, runner, [])++ with caplog.at_level(logging.INFO, logger="gateway.run"):+ await runner._start_one_profile_adapters("work", Path("/profiles/work"), {})+ await runner._start_secondary_profiles(1, [])++ assert not [r for r in caplog.records if r.levelno == logging.WARNING and "not being served" in r.getMessage()]+ assert [r for r in caplog.records if r.levelno == logging.INFO and "not served" in r.getMessage()]diff --git a/tests/hermes_cli/test_relay_plugin_migrate.py b/tests/hermes_cli/test_relay_plugin_migrate.pynew file mode 100644index 00000000000..73209df1a36--- /dev/null+++ b/tests/hermes_cli/test_relay_plugin_migrate.py@@ -0,0 +1,90 @@+"""``hermes update`` / ``hermes migrate relay``: legacy ``HERMES_NEMO_RELAY_ATIF_*``/``ATOF_*`` vars+become a validated ``relay-plugins.toml`` per profile home, selected from ``.env``."""++from __future__ import annotations++import asyncio+import tomllib+from pathlib import Path++import pytest++from hermes_cli.relay_plugin_migrate import (+ RELAY_PLUGINS_TOML_NAME, migrate_all_profile_relay_envs, migrate_profile_relay_env)+from hermes_cli.relay_plugin_cutover import RELAY_PLUGINS_CONFIG_ENV, configured_legacy_relay_env_vars++nemo_relay = pytest.importorskip("nemo_relay")++LEGACY_ENV = """OPENAI_API_KEY=sk-test+HERMES_NEMO_RELAY_ATOF_ENABLED=1+HERMES_NEMO_RELAY_ATOF_OUTPUT_DIRECTORY={home}/telemetry/atof+HERMES_NEMO_RELAY_ATOF_FILENAME=hermes-atof.jsonl+HERMES_NEMO_RELAY_ATOF_MODE=append+HERMES_NEMO_RELAY_ATIF_ENABLED=1+HERMES_NEMO_RELAY_ATIF_OUTPUT_DIRECTORY={home}/telemetry/atif+HERMES_NEMO_RELAY_ATIF_FILENAME_TEMPLATE=trajectory-{{session_id}}.json+HERMES_NEMO_RELAY_ATIF_SUBAGENT_EXPORT_MODE=all+"""+++def _parse_env(path: Path) -> dict[str, str]:+ out = {}+ for line in path.read_text().splitlines():+ if line.strip() and not line.startswith("#") and "=" in line:+ k, _, v = line.partition("=")+ out[k.strip()] = v.strip().strip('"')+ return out+++def profile_env(tmp_path, monkeypatch):+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(home))+ return home+++def test_legacy_env_becomes_validated_toml_selected_from_env(profile_env):+ (profile_env / ".env").write_text(LEGACY_ENV.format(home=profile_env))++ result = migrate_profile_relay_env(profile_env)++ assert result.migrated, (result.skipped_reason, result.validation_error)+ assert result.diagnostics == []+ toml_path = profile_env / RELAY_PLUGINS_TOML_NAME+ document = tomllib.loads(toml_path.read_text())+ sink = document["components"][0]["config"]["atof"]["sinks"][0]+ assert sink["type"] == "file" and sink["filename"] == "hermes-atof.jsonl"+ assert document["components"][0]["config"]["atif"]["filename_template"] == "trajectory-{session_id}.json"+ # Relay itself accepts the file Hermes will load at runtime.+ report = asyncio.run(nemo_relay.plugin.initialize(document))+ asyncio.run(nemo_relay.plugin.clear_async())+ assert report.get("diagnostics") == []+ # .env now selects the file; the legacy lines survive as comments (not deleted), so the+ # runtime warning + doctor finding go quiet and a second run is a no-op.+ env = _parse_env(profile_env / ".env")+ assert env[RELAY_PLUGINS_CONFIG_ENV] == str(toml_path)+ assert env["OPENAI_API_KEY"] == "sk-test"+ assert configured_legacy_relay_env_vars(env) == ()+ assert "# migrated to relay-plugins.toml: HERMES_NEMO_RELAY_ATOF_ENABLED=1" in (profile_env / ".env").read_text()+ assert migrate_profile_relay_env(profile_env).skipped_reason == "no legacy exporter variables"+++def test_update_migrates_every_profile_home_separately(profile_env):+ """Multiplex: each profile keeps its own TOML; a profile without legacy vars is untouched."""+ (profile_env / ".env").write_text("OPENAI_API_KEY=x\n")+ work = profile_env / "profiles" / "work"+ idle = profile_env / "profiles" / "idle"+ for p in (work, idle):+ p.mkdir(parents=True)+ (work / ".env").write_text(LEGACY_ENV.format(home=work))+ (idle / ".env").write_text("SLACK_BOT_TOKEN=y\n")++ results = {r.home: r for r in migrate_all_profile_relay_envs(validate=False)}++ assert results[work].migrated and results[work].toml_path == work / RELAY_PLUGINS_TOML_NAME+ assert not results[idle].migrated and not (idle / RELAY_PLUGINS_TOML_NAME).exists()+ assert not results[profile_env].migrated and not (profile_env / RELAY_PLUGINS_TOML_NAME).exists()+ assert _parse_env(work / ".env")[RELAY_PLUGINS_CONFIG_ENV] == str(work / RELAY_PLUGINS_TOML_NAME)+ assert (idle / ".env").read_text() == "SLACK_BOT_TOKEN=y\n"diff --git a/website/docs/user-guide/multi-profile-gateways.md b/website/docs/user-guide/multi-profile-gateways.mdindex 07bf441f53e..de0d7247a87 100644--- a/website/docs/user-guide/multi-profile-gateways.md+++ b/website/docs/user-guide/multi-profile-gateways.md@@ -179,6 +179,14 @@ no API server is enabled); it serves three kinds of profile-prefixed paths:adapter instance built without a port; the default listener forwards`/p/<profile>/<the adapter's usual path>` to it. See[Inbound-port platforms under the multiplexer](#inbound-port-platforms-under-the-multiplexer).+- **WhatsApp (bridge) and Relay are shared ingress owned by the default profile.**+ The multiplexer never starts them for a secondary: `WHATSAPP_ENABLED=true` in+ `profiles/work/.env` does nothing on its own. Enable and configure them on the+ default profile (their inbound is routed to profiles via `profile_routes`), or+ disable them in the secondary. The gateway logs one INFO line per skipped+ secondary platform, and if **no** profile runs it a WARNING says the platform+ is not being served; `hermes gateway status --profile work` shows+ `whatsapp: not served under multiplex (shared ingress owned by default)`.Authentication follows the profile named in the URL. Unprefixed endpoints keepusing the default listener's existing credentials.