diff --git a/agent/secret_scope.py b/agent/secret_scope.py index 919fe3e27b..86f18f5219 100644 --- a/agent/secret_scope.py +++ b/agent/secret_scope.py @@ -114,6 +114,23 @@ _GLOBAL_ENV_EXACT = frozenset({ # profile-scoped. "API_SERVER_ENABLED", "API_SERVER_HOST", "API_SERVER_PORT", "API_SERVER_CORS_ORIGINS", + # Relay-connector ROUTING stamps — deployment config injected into the + # container/process env by managed deploys (the same shape as the + # API_SERVER listener settings above). The scoped runner reload and the + # relay-exclusive sweep in gateway/config.py must keep seeing them, and + # every reader (gateway.config, gateway.relay.relay_url()/registration/ + # self-provision) must resolve the SAME value — a scope-dependent split + # leaves the adapter registered but the platform absent from config (or + # vice versa). Mirrors the non-secret/secret line drawn by the terminal + # env blocklist (tools/environments/local.py): routing hints are global; + # GATEWAY_RELAY_SECRET / GATEWAY_RELAY_ID / GATEWAY_RELAY_DELIVERY_KEY + # and the IDP_* credentials are auth material and deliberately NOT here — + # they stay profile-scoped with the fail-closed multiplex guard. + "GATEWAY_RELAY_URL", "GATEWAY_RELAY_ENDPOINT", + "GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS", + "GATEWAY_RELAY_PLATFORMS", "GATEWAY_RELAY_BOT_IDS", + "GATEWAY_RELAY_ROUTE_KEYS", "GATEWAY_RELAY_INSTANCE_ID", + "GATEWAY_RELAY_WAKE_URL", "GATEWAY_RELAY_DISPLAY_NAME", }) _GLOBAL_ENV_PREFIXES = ( "HERMES_KANBAN_", diff --git a/gateway/config.py b/gateway/config.py index a00fa0f9a1..fece329595 100644 --- a/gateway/config.py +++ b/gateway/config.py @@ -2751,7 +2751,7 @@ def _apply_env_overrides(config: GatewayConfig) -> None: # config.platforms for start_gateway()'s connect loop to bring it up. The # connected-checker (Platform.RELAY in _PLATFORM_CONNECTED_CHECKERS) keys on # extra["relay_url"], so mirror the URL into extra here. - relay_url_env = os.getenv("GATEWAY_RELAY_URL", "").strip() + relay_url_env = getenv("GATEWAY_RELAY_URL", "").strip() relay_url_yaml = "" existing_relay = config.platforms.get(Platform.RELAY) if existing_relay is not None: @@ -2761,5 +2761,51 @@ def _apply_env_overrides(config: GatewayConfig) -> None: relay_config = _enable_from_env(Platform.RELAY) relay_config.extra["relay_url"] = relay_url_val.rstrip("/") + # Relay-exclusive: a GATEWAY_RELAY_URL env stamp marks a connector-fronted + # deployment where the connector owns every platform connection. Any + # directly-connected messaging adapter in the same process would be a + # second, unmanaged ingress path (duplicate deliveries, split sessions, + # and a live socket that disarms scale-to-zero), so the env stamp disables + # all other messaging platforms — including ones explicitly enabled in + # config.yaml. Non-messaging surfaces (local, api_server, webhook — the + # same exclusion set as the scale-to-zero arm gate) are untouched. + # Deployments that configure relay only via gateway.relay_url in + # config.yaml keep the old additive behavior (relay beside direct + # adapters). + # + # Opt-out: GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS=true keeps direct + # adapters running beside the relay for deployments that intentionally + # mix both ingress paths. Like the trigger, it is a deploy-stamp env var, + # not a config.yaml setting. Both reads go through the profile-scope-aware + # getenv so multiplexed profiles see their own values, not the process + # globals. + allow_direct = is_truthy_value( + getenv("GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS", "") + ) + if relay_url_env and not allow_direct: + non_messaging = {Platform.LOCAL, Platform.API_SERVER, Platform.WEBHOOK} + for platform, platform_config in config.platforms.items(): + if platform is Platform.RELAY or platform in non_messaging: + continue + if not platform_config.enabled: + continue + if platform_config.extra.get("_enabled_explicit"): + logger.warning( + "Relay connector is configured via GATEWAY_RELAY_URL; " + "disabling directly-connected platform '%s' even though " + "it is explicitly enabled in this profile's configuration. " + "All messaging goes through the connector on this " + "deployment. Set GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS=true " + "to keep direct platforms alongside the relay.", + platform.value, + ) + else: + logger.info( + "Relay connector is configured via GATEWAY_RELAY_URL; " + "disabling directly-connected platform '%s'.", + platform.value, + ) + platform_config.enabled = False + for platform_config in config.platforms.values(): platform_config.extra.pop("_enabled_explicit", None) diff --git a/hermes_cli/gateway_enroll.py b/hermes_cli/gateway_enroll.py index d3c5622225..9f529e625c 100644 --- a/hermes_cli/gateway_enroll.py +++ b/hermes_cli/gateway_enroll.py @@ -37,6 +37,7 @@ import sys import urllib.error import urllib.parse import urllib.request +from pathlib import Path from typing import Optional @@ -270,8 +271,80 @@ def cmd_gateway_enroll(args) -> None: if explicit_wake_url: print(f" GATEWAY_RELAY_WAKE_URL={explicit_wake_url.rstrip('/')}") print() - print( - " The gateway now authenticates its relay WS upgrade with the per-gateway\n" - " secret and verifies signed inbound deliveries with the tenant delivery\n" - " key. Restart the gateway to pick up the new env." - ) + # GATEWAY_RELAY_URL / GATEWAY_RELAY_WAKE_URL are process-global deployment + # stamps (agent/secret_scope.py): a multiplexed gateway resolves them from + # the PROCESS environment only, never from a secondary profile's .env + # (which is loaded into an isolated secret scope, not exported). The .env + # write above works for a single-profile gateway and for the profile the + # process is launched under (load_hermes_dotenv exports that .env), so + # warn rather than refuse — but don't let a secondary-profile enroll claim + # a config that will silently never activate. Emitted BEFORE the generic + # restart line so the two don't contradict each other. + warned_secondary = False + if explicit_url or explicit_wake_url: + warned_secondary = _warn_if_secondary_multiplex_profile() + if not warned_secondary: + print( + " The gateway now authenticates its relay WS upgrade with the per-gateway\n" + " secret and verifies signed inbound deliveries with the tenant delivery\n" + " key. Restart the gateway to pick up the new env." + ) + + +def _warn_if_secondary_multiplex_profile() -> bool: + """Warn when relay routing stamps were written to a secondary profile's + .env that a multiplexed gateway will never read them from. Returns True + when the warning fired (the caller suppresses the generic restart text). + + The topology decision is owned by the DEFAULT root, not the active + profile home: ``multiplex_profiles`` normally lives in + ``/config.yaml`` (or the GATEWAY_MULTIPLEX_PROFILES env + override), and the secondary check is the resolved-path relationship to + ``/profiles/`` — mirroring the multiplexer-conflict guard + in hermes_cli/gateway.py. Best-effort: any failure to determine the + topology stays silent (the credential write itself succeeded). + """ + try: + from hermes_constants import get_default_hermes_root + from hermes_cli.config import get_hermes_home + + default_root = Path(get_default_hermes_root()).resolve() + home = Path(get_hermes_home()).resolve() + try: + home.relative_to(default_root / "profiles") + except ValueError: + return False # default profile or custom layout — not a secondary + + # Multiplex flag precedence mirrors gateway.config: recognized env + # override wins, else the DEFAULT root's config.yaml (raw read — the + # active profile's load_gateway_config() is the wrong owner AND runs + # the full enablement pass, including the relay-exclusive sweep's own + # log output, which has no place in enroll output). + from gateway.config import _env_multiplex_profiles_override + env_multiplex = _env_multiplex_profiles_override() + if env_multiplex is False: + return False + if env_multiplex is not True: + cfg_path = default_root / "config.yaml" + if not cfg_path.exists(): + return False + from hermes_cli.config import read_user_config_raw + cfg = read_user_config_raw(cfg_path) or {} + if not bool( + cfg.get("multiplex_profiles") + or (cfg.get("gateway", {}) or {}).get("multiplex_profiles") + ): + return False + + print( + " ⚠ This profile is a SECONDARY profile of a multiplexed gateway.\n" + " GATEWAY_RELAY_URL / GATEWAY_RELAY_WAKE_URL are process-level\n" + " deployment settings: the gateway reads them from the process\n" + " environment (or the default profile's .env), not from this\n" + " profile's .env. Set them in the environment the gateway process\n" + " is launched with, or enroll from the default profile. The\n" + " relay credentials written above are valid either way." + ) + return True + except Exception: + return False diff --git a/tests/agent/test_secret_scope.py b/tests/agent/test_secret_scope.py index f0d76fe654..7e73f12dbc 100644 --- a/tests/agent/test_secret_scope.py +++ b/tests/agent/test_secret_scope.py @@ -287,3 +287,63 @@ class TestApiServerListenerGlobals: finally: ss.reset_secret_scope(token) assert not ss._is_global_env("API_SERVER_KEY") + + +class TestRelayRoutingStampGlobals: + """GATEWAY_RELAY_* ROUTING stamps are deployment config, not profile + secrets: config's relay enablement/sweep and gateway.relay's readers + (relay_url(), registration, self-provision) must resolve the same + process-env value under any scope, or the gateway enters a split-brain + state (adapter registered but Platform.RELAY absent from config, or vice + versa). Auth material (GATEWAY_RELAY_SECRET / _ID / _DELIVERY_KEY and the + IDP_* credentials) stays profile-scoped with the fail-closed guard — + mirroring the API_SERVER_KEY line above and the terminal env blocklist + (tools/environments/local.py).""" + + ROUTING_VARS = ( + "GATEWAY_RELAY_URL", + "GATEWAY_RELAY_ENDPOINT", + "GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS", + "GATEWAY_RELAY_PLATFORMS", + "GATEWAY_RELAY_BOT_IDS", + "GATEWAY_RELAY_ROUTE_KEYS", + "GATEWAY_RELAY_INSTANCE_ID", + "GATEWAY_RELAY_WAKE_URL", + "GATEWAY_RELAY_DISPLAY_NAME", + ) + AUTH_VARS = ( + "GATEWAY_RELAY_SECRET", + "GATEWAY_RELAY_ID", + "GATEWAY_RELAY_DELIVERY_KEY", + "GATEWAY_RELAY_IDP_CLIENT_SECRET", + "GATEWAY_RELAY_IDP_CLIENT_ID", + "GATEWAY_RELAY_IDP_TOKEN_URL", + ) + + def test_routing_stamps_read_environ_even_when_scoped_multiplex(self, monkeypatch): + for name in self.ROUTING_VARS: + monkeypatch.setenv(name, f"deploy-{name.lower()}") + ss.set_multiplex_active(True) + token = ss.set_secret_scope({"TELEGRAM_BOT_TOKEN": "scoped"}) + try: + for name in self.ROUTING_VARS: + assert ss.get_secret(name) == f"deploy-{name.lower()}", name + finally: + ss.reset_secret_scope(token) + ss.set_multiplex_active(False) + + def test_relay_auth_material_stays_profile_scoped(self, monkeypatch): + for name in self.AUTH_VARS: + monkeypatch.setenv(name, "cross-profile-credential") + ss.set_multiplex_active(True) + token = ss.set_secret_scope({"OTHER": "x"}) + try: + for name in self.AUTH_VARS: + # A scoped miss must NOT borrow the (potentially + # cross-profile) environ value: relay auth is a credential. + assert ss.get_secret(name) is None, name + finally: + ss.reset_secret_scope(token) + ss.set_multiplex_active(False) + for name in self.AUTH_VARS: + assert not ss._is_global_env(name), name diff --git a/tests/gateway/relay/test_relay_registration.py b/tests/gateway/relay/test_relay_registration.py index 4aceb269c6..819d4e8049 100644 --- a/tests/gateway/relay/test_relay_registration.py +++ b/tests/gateway/relay/test_relay_registration.py @@ -42,3 +42,99 @@ def test_registers_when_url_configured(monkeypatch): assert platform_registry.is_registered("relay") is True + + +class TestConfigRegistrationAgreementUnderMultiplexScope: + """The config loader and the relay registration path must resolve the SAME + GATEWAY_RELAY_URL under an active multiplex profile scope — the routing + stamp is process-global (agent/secret_scope.py), so neither side may see a + value the other doesn't. Regression for the split-brain states: adapter + registered with Platform.RELAY absent from config (process stamp dropped + by the scoped reload), and enabled RELAY config with no adapter + (profile-only stamp invisible to relay_url()).""" + + def test_process_stamp_agrees_on_both_sides_under_scope( + self, tmp_path, monkeypatch + ): + from agent import secret_scope as ss + from gateway.config import Platform, load_gateway_config + + hermes_home = tmp_path / ".hermes" + hermes_home.mkdir() + (hermes_home / "config.yaml").write_text( + "gateway:\n" + " platforms:\n" + " telegram:\n" + " enabled: true\n" + " bot_token: '123:abc'\n", + encoding="utf-8", + ) + monkeypatch.setenv("HERMES_HOME", str(hermes_home)) + monkeypatch.setenv("GATEWAY_RELAY_URL", "wss://deploy.example/relay") + + profile_dir = tmp_path / "profile-a" + profile_dir.mkdir() + (profile_dir / ".env").write_text("", encoding="utf-8") + + ss.set_multiplex_active(True) + tok = ss.set_secret_scope(ss.build_profile_secret_scope(profile_dir)) + try: + config = load_gateway_config() + # Registration-side reader agrees with the config side. + assert relay_url() == "wss://deploy.example/relay" + assert register_relay_adapter() is True + finally: + ss.reset_secret_scope(tok) + ss.set_multiplex_active(False) + + assert config.platforms[Platform.RELAY].enabled is True + assert config.platforms[Platform.TELEGRAM].enabled is False + # The registered factory actually constructs an adapter with a live + # transport dialing the same URL — the connect loop's contract. + adapter = platform_registry.create_adapter( + "relay", config.platforms[Platform.RELAY] + ) + assert isinstance(adapter, RelayAdapter) + # A URL-configured registration builds a live transport (force=True's + # transport-less posture is the test-only path) — private attr, no + # public accessor on the adapter. + assert adapter._transport is not None + + def test_profile_only_stamp_is_inert_on_both_sides_under_scope( + self, tmp_path, monkeypatch + ): + from agent import secret_scope as ss + from gateway.config import Platform, load_gateway_config + + hermes_home = tmp_path / ".hermes" + hermes_home.mkdir() + (hermes_home / "config.yaml").write_text( + "gateway:\n" + " platforms:\n" + " telegram:\n" + " enabled: true\n" + " bot_token: '123:abc'\n", + encoding="utf-8", + ) + monkeypatch.setenv("HERMES_HOME", str(hermes_home)) + + profile_dir = tmp_path / "profile-a" + profile_dir.mkdir() + (profile_dir / ".env").write_text( + "GATEWAY_RELAY_URL=wss://profile.example/relay\n", encoding="utf-8" + ) + + ss.set_multiplex_active(True) + tok = ss.set_secret_scope(ss.build_profile_secret_scope(profile_dir)) + try: + config = load_gateway_config() + # Both sides agree the stamp is absent: no half-enabled state. + assert relay_url() is None + assert register_relay_adapter() is False + finally: + ss.reset_secret_scope(tok) + ss.set_multiplex_active(False) + + relay_cfg = config.platforms.get(Platform.RELAY) + assert relay_cfg is None or relay_cfg.enabled is False + assert config.platforms[Platform.TELEGRAM].enabled is True diff --git a/tests/gateway/test_config.py b/tests/gateway/test_config.py index 29c71a387b..00ec63e1b5 100644 --- a/tests/gateway/test_config.py +++ b/tests/gateway/test_config.py @@ -686,6 +686,194 @@ class TestLoadGatewayConfig: assert Platform.RELAY in config.get_connected_platforms() + def test_relay_env_url_disables_other_messaging_platforms(self, tmp_path, monkeypatch): + """A GATEWAY_RELAY_URL env stamp means the connector owns all platform + connections: directly-connected messaging platforms must be disabled, + even when explicitly enabled in config.yaml, while non-messaging + surfaces (api_server et al.) survive.""" + hermes_home = tmp_path / ".hermes" + hermes_home.mkdir() + config_path = hermes_home / "config.yaml" + config_path.write_text( + "gateway:\n" + " platforms:\n" + " telegram:\n" + " enabled: true\n" + " bot_token: '123:abc'\n" + " api_server:\n" + " enabled: true\n", + encoding="utf-8", + ) + monkeypatch.setenv("HERMES_HOME", str(hermes_home)) + monkeypatch.setenv("GATEWAY_RELAY_URL", "https://connector.example/relay") + # Credential-based auto-enable path must be suppressed too. + monkeypatch.setenv("DISCORD_BOT_TOKEN", "fake-token-for-test") + + config = load_gateway_config() + + assert config.platforms[Platform.RELAY].enabled is True + assert config.platforms[Platform.TELEGRAM].enabled is False + discord_cfg = config.platforms.get(Platform.DISCORD) + assert discord_cfg is None or discord_cfg.enabled is False + # Non-messaging surfaces are untouched. + assert config.platforms[Platform.API_SERVER].enabled is True + + + def test_relay_yaml_url_keeps_other_platforms_enabled(self, tmp_path, monkeypatch): + """gateway.relay_url in config.yaml (no env stamp) keeps the old + additive behavior: relay runs beside directly-connected platforms.""" + hermes_home = tmp_path / ".hermes" + hermes_home.mkdir() + config_path = hermes_home / "config.yaml" + config_path.write_text( + "gateway:\n" + " platforms:\n" + " relay:\n" + " enabled: true\n" + " extra:\n" + " relay_url: https://connector.example/relay\n" + " telegram:\n" + " enabled: true\n" + " bot_token: '123:abc'\n", + encoding="utf-8", + ) + monkeypatch.setenv("HERMES_HOME", str(hermes_home)) + monkeypatch.delenv("GATEWAY_RELAY_URL", raising=False) + + config = load_gateway_config() + + assert config.platforms[Platform.RELAY].enabled is True + assert config.platforms[Platform.TELEGRAM].enabled is True + + + def test_relay_env_url_opt_out_keeps_direct_platforms(self, tmp_path, monkeypatch): + """GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS=true opts a deployment out of + the relay-exclusive sweep: direct adapters stay enabled beside the + relay even with the GATEWAY_RELAY_URL env stamp present.""" + hermes_home = tmp_path / ".hermes" + hermes_home.mkdir() + config_path = hermes_home / "config.yaml" + config_path.write_text( + "gateway:\n" + " platforms:\n" + " telegram:\n" + " enabled: true\n" + " bot_token: '123:abc'\n", + encoding="utf-8", + ) + monkeypatch.setenv("HERMES_HOME", str(hermes_home)) + monkeypatch.setenv("GATEWAY_RELAY_URL", "https://connector.example/relay") + monkeypatch.setenv("GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS", "true") + + config = load_gateway_config() + + assert config.platforms[Platform.RELAY].enabled is True + assert config.platforms[Platform.TELEGRAM].enabled is True + + + def test_relay_exclusive_reads_profile_scoped_env(self, tmp_path, monkeypatch): + """GATEWAY_RELAY_URL is a process-global deployment stamp (like the + API_SERVER listener vars, #69379): the scoped runner reload in a + multiplexed gateway must keep seeing it, so config's relay enablement + and sweep agree with gateway.relay.relay_url()/register_relay_adapter() + (which read os.environ). A secondary profile's .env stamp does NOT + override the shared process stamp — an isolated multiplex scope is + never consulted for globals. (A single-profile gateway, or the profile + the process is launched under, still activates via its .env because + load_hermes_dotenv exports that file into os.environ at startup.)""" + from agent import secret_scope as ss + + hermes_home = tmp_path / ".hermes" + hermes_home.mkdir() + config_path = hermes_home / "config.yaml" + config_path.write_text( + "gateway:\n" + " platforms:\n" + " telegram:\n" + " enabled: true\n" + " bot_token: '123:abc'\n", + encoding="utf-8", + ) + monkeypatch.setenv("HERMES_HOME", str(hermes_home)) + # Managed-deploy stamp in the process env; the profile .env has none. + monkeypatch.setenv("GATEWAY_RELAY_URL", "https://deploy.example/relay") + + profile_dir = tmp_path / "profile-a" + profile_dir.mkdir() + (profile_dir / ".env").write_text("", encoding="utf-8") + + ss.set_multiplex_active(True) + tok = ss.set_secret_scope(ss.build_profile_secret_scope(profile_dir)) + try: + config = load_gateway_config() + finally: + ss.reset_secret_scope(tok) + ss.set_multiplex_active(False) + + # The deploy stamp survives the profile scope: relay enabled, sweep + # ran — matching what register_relay_adapter() sees in os.environ. + assert config.platforms[Platform.RELAY].enabled is True + assert config.platforms[Platform.TELEGRAM].enabled is False + + # A profile-only stamp does NOT activate relay: globals read only the + # process env, so config and the relay transport can never disagree. + monkeypatch.delenv("GATEWAY_RELAY_URL", raising=False) + (profile_dir / ".env").write_text( + "GATEWAY_RELAY_URL=https://profile.example/relay\n", encoding="utf-8" + ) + ss.set_multiplex_active(True) + tok = ss.set_secret_scope(ss.build_profile_secret_scope(profile_dir)) + try: + config = load_gateway_config() + finally: + ss.reset_secret_scope(tok) + ss.set_multiplex_active(False) + + relay_cfg = config.platforms.get(Platform.RELAY) + assert relay_cfg is None or relay_cfg.enabled is False + assert config.platforms[Platform.TELEGRAM].enabled is True + + + def test_relay_exclusive_sweep_log_levels_and_marker_cleanup(self, tmp_path, monkeypatch, caplog): + """Explicitly-enabled platforms are disabled at WARNING, auto-enabled + ones at INFO, and the _enabled_explicit marker never survives config + load.""" + import logging as _logging + + hermes_home = tmp_path / ".hermes" + hermes_home.mkdir() + config_path = hermes_home / "config.yaml" + config_path.write_text( + "gateway:\n" + " platforms:\n" + " telegram:\n" + " enabled: true\n" + " bot_token: '123:abc'\n", + encoding="utf-8", + ) + monkeypatch.setenv("HERMES_HOME", str(hermes_home)) + monkeypatch.setenv("GATEWAY_RELAY_URL", "https://connector.example/relay") + monkeypatch.setenv("DISCORD_BOT_TOKEN", "fake-token-for-test") + + with caplog.at_level(_logging.INFO, logger="gateway.config"): + config = load_gateway_config() + + warnings = [ + r for r in caplog.records + if r.levelno == _logging.WARNING and "telegram" in r.getMessage() + ] + assert warnings, "explicit platform must be disabled at WARNING" + discord_infos = [ + r for r in caplog.records + if r.levelno == _logging.INFO and "discord" in r.getMessage() + ] + if config.platforms.get(Platform.DISCORD) is not None: + assert discord_infos, "auto-enabled platform must be disabled at INFO" + + for pc in config.platforms.values(): + assert "_enabled_explicit" not in (pc.extra or {}) + + def test_thread_require_mention_yaml_does_not_overwrite_env(self, tmp_path, monkeypatch): """Explicit env var should win over config.yaml (env > yaml precedence).""" hermes_home = tmp_path / ".hermes" diff --git a/tests/hermes_cli/test_gateway_enroll_multiplex_warning.py b/tests/hermes_cli/test_gateway_enroll_multiplex_warning.py new file mode 100644 index 0000000000..31a4d539b5 --- /dev/null +++ b/tests/hermes_cli/test_gateway_enroll_multiplex_warning.py @@ -0,0 +1,117 @@ +"""Gateway enroll: secondary-multiplex-profile warning for relay routing stamps. + +``hermes gateway enroll --connector-url/--wake-url`` persists GATEWAY_RELAY_URL / +GATEWAY_RELAY_WAKE_URL into the active profile's .env. Those are process-global +deployment stamps (agent/secret_scope.py): a multiplexed gateway reads them from +the process environment only, never from a secondary profile's isolated secret +scope — so an enroll run from a secondary profile must WARN that the written +URLs will not activate from there (sol-reviewer round-4: the first cut read +``multiplex_profiles`` from the SECONDARY profile's config.yaml, where it never +lives, and the warning silently never fired in the real topology). + +The topology decision is owned by the DEFAULT root: path relationship to +``/profiles/`` plus the default root's config.yaml (or the +GATEWAY_MULTIPLEX_PROFILES env override). +""" + +from __future__ import annotations + +import io +from contextlib import redirect_stdout + +import pytest + +import hermes_constants +from hermes_cli.gateway_enroll import _warn_if_secondary_multiplex_profile + + +@pytest.fixture() +def topology(tmp_path, monkeypatch): + """Standard multiplex layout: default root + one secondary profile.""" + root = tmp_path / "root" + (root / "profiles" / "alice").mkdir(parents=True) + monkeypatch.setattr(hermes_constants, "get_default_hermes_root", lambda: root) + monkeypatch.delenv("GATEWAY_MULTIPLEX_PROFILES", raising=False) + return root + + +def _run() -> tuple[bool, str]: + buf = io.StringIO() + with redirect_stdout(buf): + fired = _warn_if_secondary_multiplex_profile() + return fired, buf.getvalue() + + +def test_fires_for_secondary_when_default_root_has_multiplex_on(topology, monkeypatch): + """The regression case: flag in the DEFAULT root's config.yaml, absent from + the secondary profile's own config — the warning must still fire.""" + (topology / "config.yaml").write_text( + "gateway:\n multiplex_profiles: true\n", encoding="utf-8" + ) + monkeypatch.setenv("HERMES_HOME", str(topology / "profiles" / "alice")) + + fired, out = _run() + + assert fired is True + assert "SECONDARY profile" in out + + +def test_silent_when_multiplex_off_in_default_root(topology, monkeypatch): + (topology / "config.yaml").write_text( + "gateway:\n multiplex_profiles: false\n", encoding="utf-8" + ) + monkeypatch.setenv("HERMES_HOME", str(topology / "profiles" / "alice")) + + fired, out = _run() + + assert fired is False + assert out == "" + + +def test_silent_for_default_profile_even_with_multiplex_on(topology, monkeypatch): + (topology / "config.yaml").write_text( + "gateway:\n multiplex_profiles: true\n", encoding="utf-8" + ) + monkeypatch.setenv("HERMES_HOME", str(topology)) + + fired, _ = _run() + + assert fired is False + + +def test_env_override_forces_multiplex_on_without_config_flag(topology, monkeypatch): + (topology / "config.yaml").write_text("{}\n", encoding="utf-8") + monkeypatch.setenv("HERMES_HOME", str(topology / "profiles" / "alice")) + monkeypatch.setenv("GATEWAY_MULTIPLEX_PROFILES", "true") + + fired, _ = _run() + + assert fired is True + + +def test_env_override_off_wins_over_config_flag(topology, monkeypatch): + (topology / "config.yaml").write_text( + "gateway:\n multiplex_profiles: true\n", encoding="utf-8" + ) + monkeypatch.setenv("HERMES_HOME", str(topology / "profiles" / "alice")) + monkeypatch.setenv("GATEWAY_MULTIPLEX_PROFILES", "false") + + fired, _ = _run() + + assert fired is False + + +def test_silent_for_unrelated_dir_named_profiles(topology, tmp_path, monkeypatch): + """A directory whose parent happens to be named 'profiles' but is OUTSIDE + the default root is not a secondary profile (sol-reviewer round-4 MINOR: + name-based heuristics false-positive on unrelated layouts).""" + (topology / "config.yaml").write_text( + "gateway:\n multiplex_profiles: true\n", encoding="utf-8" + ) + other = tmp_path / "elsewhere" / "profiles" / "x" + other.mkdir(parents=True) + monkeypatch.setenv("HERMES_HOME", str(other)) + + fired, _ = _run() + + assert fired is False