Skip to content

The agent that grows with you

fix(gateway): authored platforms.<plat>.extra wins over the top-level platform block

Victor Kyriazakosde63c6d275be
diff --git a/gateway/config_loader.py b/gateway/config_loader.py
index e367209fa55..1c79079318d 100644
--- a/gateway/config_loader.py
+++ b/gateway/config_loader.py
@@ -252,8 +252,53 @@ def shared_loop_targets(registry) -> list:
return targets
+def snapshot_authored_extra(platforms_data: dict) -> dict:
+ """``{plat_name: extra}`` as the user authored it under ``platforms.<plat>.extra``, captured
+ right after ``merge_platform_sections`` and BEFORE either copy site runs. Reading
+ ``platforms_data`` live at a copy site would mistake values the earlier site bridged from the
+ block's own ``extra:`` sub-dict for authored ones (``telegram: {reply_to_mode: all, extra:
+ {reply_to_mode: off}}`` must still resolve to ``all``). Copies, never creates slots."""
+ return {
+ name: dict(_coerce_dict(plat.get("extra")))
+ for name, plat in platforms_data.items() if isinstance(plat, dict)
+ }
+
+
+def _authored_wins(extra: dict, block: dict, plat_name: str, *, toplevel: bool, warned: Optional[set] = None) -> dict:
+ """Effective ``<plat>:`` block for YAML→extra/env bridging: *block* (top-level or
+ nested) overlaid with the keys the user authored in ``platforms.<plat>.extra``.
+
+ Returns a NEW dict and never mutates *block* or *extra*. For every key present in
+ both with DIFFERENT values, ONE warning logs that the authored extra took precedence
+ (equal values are silent). *warned* dedupes across both copy sites within one
+ ``load_yaml_layer`` pass; ``None`` gives the caller a fresh local set.
+ """
+ if warned is None:
+ warned = set()
+ where = f"the top-level '{plat_name}:' block" if toplevel else f"platforms.{plat_name}"
+
+ def overlay_onto(source: dict) -> dict:
+ overlay = {k: extra[k] for k in source if k in extra}
+ for key, value in overlay.items():
+ if source[key] != value and (plat_name, key) not in warned:
+ warned.add((plat_name, key))
+ logger.warning(
+ "%s set in both %s and platforms.%s.extra; platforms.%s.extra took precedence",
+ key, where, plat_name, plat_name,
+ )
+ return {**source, **overlay}
+
+ effective = overlay_onto(block)
+ # A root block may carry its own ``extra:`` sub-dict (``_bridged_keys`` merges it with
+ # ``PlatformConfig.from_dict`` semantics); the authored extra outranks that too.
+ if isinstance(block.get("extra"), dict):
+ effective["extra"] = overlay_onto(block["extra"])
+ return effective
+
+
def bridge_platform_shared_keys(
- yaml_cfg: dict, gateway_platforms: Any, gw_data: dict, platforms_data: dict, targets: list
+ yaml_cfg: dict, gateway_platforms: Any, gw_data: dict, platforms_data: dict, targets: list,
+ warned: Optional[set] = None, authored: Optional[dict] = None,
) -> None:
"""Copy shared keys (allow_from, require_mention, …) from each platform's YAML section into ``extra``.
@@ -262,13 +307,19 @@ def bridge_platform_shared_keys(
``_enabled_explicit`` so the env pass honors ``enabled: false`` for migrated plugin platforms
instead of re-enabling them on token/SDK presence.
"""
+ if authored is None:
+ authored = snapshot_authored_extra(platforms_data)
for plat in targets:
if plat == Platform.LOCAL:
continue
platform_cfg, cfg_toplevel = platform_section(yaml_cfg, plat.value, gateway_platforms)
if not isinstance(platform_cfg, dict):
continue
- bridged = _bridged_keys(plat, platform_cfg, gw_data, root_block=cfg_toplevel)
+ # An authored ``platforms.<plat>.extra`` key beats the same key in the (top-level or
+ # nested) block, so the shared-key bridge works on the effective block.
+ effective = _authored_wins(
+ authored.get(plat.value, {}), platform_cfg, plat.value, toplevel=cfg_toplevel, warned=warned)
+ bridged = _bridged_keys(plat, effective, gw_data, root_block=cfg_toplevel)
has_channel_overrides = "channel_overrides" in platform_cfg
if has_channel_overrides and isinstance(platform_cfg.get("channel_overrides"), dict):
plat_data = _dict_slot(platforms_data, plat.value)
@@ -289,11 +340,16 @@ def bridge_platform_shared_keys(
extra.update(bridged)
-def apply_plugin_yaml_hooks(yaml_cfg: dict, gateway_platforms: Any, platforms_data: dict, registry) -> None:
+def apply_plugin_yaml_hooks(
+ yaml_cfg: dict, gateway_platforms: Any, platforms_data: dict, registry,
+ warned: Optional[set] = None, authored: Optional[dict] = None,
+) -> None:
"""Plugin-owned YAML→env config bridges (``PlatformEntry.apply_yaml_config_fn``). Order: shared-key
loop → this dispatch → core-only bridges (require_mention/signal) → ``_apply_env_overrides()``."""
if registry is None:
return
+ if authored is None:
+ authored = snapshot_authored_extra(platforms_data)
for entry in registry.all_entries():
# Plugin-owned YAML→env config bridges (#24836). See ``PlatformEntry.apply_yaml_config_fn`` for the
# hook contract. Order: shared-key loop (above) → this dispatch → legacy hardcoded blocks (below;
@@ -301,15 +357,21 @@ def apply_plugin_yaml_hooks(yaml_cfg: dict, gateway_platforms: Any, platforms_da
# ``GatewayConfig.from_dict``.
if entry.apply_yaml_config_fn is None:
continue
- platform_cfg, _ = platform_section(yaml_cfg, entry.name, gateway_platforms)
+ platform_cfg, cfg_toplevel = platform_section(yaml_cfg, entry.name, gateway_platforms)
if not isinstance(platform_cfg, dict):
continue
+ # Overlay the authored extra BEFORE the hook so the block the hook sees — and
+ # therefore the values it bridges to env — already carry the authored nested
+ # value for keys present in both (adapter readers are env-first).
+ effective = _authored_wins(
+ authored.get(entry.name, {}), platform_cfg, entry.name, toplevel=cfg_toplevel, warned=warned)
try:
- seeded = entry.apply_yaml_config_fn(yaml_cfg, platform_cfg)
+ seeded = entry.apply_yaml_config_fn(yaml_cfg, effective)
except Exception as e:
logger.debug("apply_yaml_config_fn for %s raised: %s", entry.name, e)
continue
if isinstance(seeded, dict) and seeded:
+ # Safe: seeded values already equal the authored ones for keys present in both.
_dict_slot(_dict_slot(platforms_data, entry.name), "extra").update(seeded)
@@ -429,6 +491,9 @@ def load_yaml_layer(home: Path, gw_data: dict) -> None:
registry = None
targets = shared_loop_targets(registry)
- bridge_platform_shared_keys(yaml_cfg, gateway_platforms, gw_data, platforms_data, targets)
- apply_plugin_yaml_hooks(yaml_cfg, gateway_platforms, platforms_data, registry)
+ authored = snapshot_authored_extra(platforms_data)
+ warned: set = set() # one warning per conflicting (platform, key) across both copy sites
+ bridge_platform_shared_keys(
+ yaml_cfg, gateway_platforms, gw_data, platforms_data, targets, warned=warned, authored=authored)
+ apply_plugin_yaml_hooks(yaml_cfg, gateway_platforms, platforms_data, registry, warned=warned, authored=authored)
bridge_core_env_settings(yaml_cfg, platforms_data)
diff --git a/tests/gateway/test_config.py b/tests/gateway/test_config.py
index 15d62db3c1f..99ca391539f 100644
--- a/tests/gateway/test_config.py
+++ b/tests/gateway/test_config.py
@@ -2,6 +2,7 @@
import logging
import os
+import re
from pathlib import Path
from unittest.mock import patch
@@ -1618,3 +1619,165 @@ class TestOnAllAdaptersDown:
).on_all_adapters_down == "exit"
monkeypatch.delenv("GATEWAY_ON_ALL_ADAPTERS_DOWN")
assert GatewayConfig.from_dict({}).on_all_adapters_down == "exit"
+
+
+class TestTopLevelBlockVsAuthoredExtra:
+ """An authored ``platforms.<plat>.extra`` key must beat the same key in the
+ top-level ``<plat>:`` block, at BOTH copy sites (shared-key bridge + plugin
+ YAML hooks); top-level values only fill keys the authored extra lacks."""
+
+ _CONFLICT_YAML = (
+ "slack:\n"
+ " require_mention: false\n"
+ " strict_mention: false\n"
+ " thread_require_mention: false\n"
+ " free_response_channels: []\n"
+ " allow_bots: false\n"
+ "platforms:\n"
+ " slack:\n"
+ " enabled: true\n"
+ " extra:\n"
+ " require_mention: true\n"
+ " strict_mention: true\n"
+ " thread_require_mention: true\n"
+ " free_response_channels:\n"
+ " - C0EXAMPLE1\n"
+ " - C0EXAMPLE2\n"
+ )
+
+ def test_authored_extra_wins_and_warns_per_conflicting_key(self, tmp_path, monkeypatch, caplog):
+ hermes_home = tmp_path / ".hermes"
+ hermes_home.mkdir()
+ (hermes_home / "config.yaml").write_text(self._CONFLICT_YAML, encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ for var in [k for k in os.environ if k.startswith("SLACK_")]:
+ monkeypatch.delenv(var, raising=False)
+
+ with caplog.at_level(logging.WARNING, logger="gateway.config"):
+ config = load_gateway_config()
+
+ extra = config.platforms[Platform.SLACK].extra
+ # Authored nested values win at BOTH copy sites.
+ assert extra["require_mention"] is True
+ assert extra["strict_mention"] is True
+ assert extra["thread_require_mention"] is True
+ assert extra["free_response_channels"] == ["C0EXAMPLE1", "C0EXAMPLE2"]
+ # Top-level-only keys (absent from the authored extra) are still filled.
+ assert extra["allow_bots"] is False
+
+ # The env rung carries the authored values too: the plugin hook's YAML→env
+ # bridge runs on the overlaid block, so env-first adapter readers resolve
+ # strict_mention/thread_require_mention/free_response_channels correctly.
+ assert os.environ["SLACK_STRICT_MENTION"] == "true"
+ assert os.environ["SLACK_THREAD_REQUIRE_MENTION"] == "true"
+ assert os.environ["SLACK_FREE_RESPONSE_CHANNELS"] == "C0EXAMPLE1,C0EXAMPLE2"
+
+ # Exactly one warning per conflicting key, naming the key and that the
+ # authored extra took precedence.
+ messages = [r.getMessage() for r in caplog.records
+ if r.levelno == logging.WARNING and "slack" in r.getMessage()]
+ for key in ("require_mention", "strict_mention",
+ "thread_require_mention", "free_response_channels"):
+ pattern = re.compile(rf"\b{re.escape(key)}\b")
+ hits = [m for m in messages
+ if pattern.search(m) and "platforms.slack.extra" in m]
+ assert len(hits) == 1, f"expected exactly 1 warning for {key!r}, got {hits}"
+
+ def test_toplevel_only_key_fills_extra_without_warning(self, tmp_path, monkeypatch, caplog):
+ hermes_home = tmp_path / ".hermes"
+ hermes_home.mkdir()
+ (hermes_home / "config.yaml").write_text(
+ "slack:\n"
+ " allow_bots: true\n"
+ "platforms:\n"
+ " slack:\n"
+ " enabled: true\n"
+ " extra:\n"
+ " strict_mention: true\n",
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ monkeypatch.delenv("SLACK_ALLOW_BOTS", raising=False)
+ monkeypatch.delenv("SLACK_STRICT_MENTION", raising=False)
+
+ with caplog.at_level(logging.WARNING, logger="gateway.config"):
+ config = load_gateway_config()
+
+ extra = config.platforms[Platform.SLACK].extra
+ assert extra["allow_bots"] is True
+ assert extra["strict_mention"] is True
+ warnings = [r for r in caplog.records if r.levelno == logging.WARNING]
+ assert warnings == []
+
+ def test_block_that_bridges_nothing_creates_no_platform_entry(self, tmp_path, monkeypatch):
+ """Reading the authored extra must not materialise ``platforms.<plat>`` for a plugin
+ platform whose block carries no bridged key: byte-identical to a config without the fix."""
+ from gateway.config_loader import load_yaml_layer
+
+ hermes_home = tmp_path / ".hermes"
+ hermes_home.mkdir()
+ (hermes_home / "config.yaml").write_text("slack:\n reply_to_mode: all\n", encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ for var in [k for k in os.environ if k.startswith("SLACK_")]:
+ monkeypatch.delenv(var, raising=False)
+
+ gw_data: dict = {}
+ load_yaml_layer(hermes_home, gw_data)
+
+ assert "slack" not in gw_data.get("platforms", {})
+
+ def test_authored_extra_wins_over_top_level_extra_subdict(self, tmp_path, monkeypatch, caplog):
+ """A root block may carry its own ``extra:`` sub-dict (merged by ``_bridged_keys`` with
+ ``PlatformConfig.from_dict`` semantics). The authored nested extra outranks that shape too,
+ with one warning per conflicting key, while sub-dict-only keys are still retained."""
+ hermes_home = tmp_path / ".hermes"
+ hermes_home.mkdir()
+ (hermes_home / "config.yaml").write_text(
+ "slack:\n"
+ " extra:\n"
+ " strict_mention: false\n"
+ " allow_bots: true\n"
+ "platforms:\n"
+ " slack:\n"
+ " enabled: true\n"
+ " extra:\n"
+ " strict_mention: true\n",
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ for var in [k for k in os.environ if k.startswith("SLACK_")]:
+ monkeypatch.delenv(var, raising=False)
+
+ with caplog.at_level(logging.WARNING, logger="gateway.config"):
+ config = load_gateway_config()
+
+ extra = config.platforms[Platform.SLACK].extra
+ assert extra["strict_mention"] is True
+ assert extra["allow_bots"] is True
+ hits = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING
+ and re.search(r"\bstrict_mention\b", r.getMessage()) and "platforms.slack.extra" in r.getMessage()]
+ assert len(hits) == 1, hits
+
+ def test_block_own_extra_subdict_is_not_mistaken_for_authored_extra(self, tmp_path, monkeypatch, caplog):
+ """With NO ``platforms.<plat>`` section, a block's own ``extra:`` sub-dict must not be
+ promoted to "authored": the direct key keeps winning over the sub-dict (the pre-existing
+ reply_to_mode contract) and nothing warns."""
+ hermes_home = tmp_path / ".hermes"
+ hermes_home.mkdir()
+ (hermes_home / "config.yaml").write_text(
+ "slack:\n"
+ " strict_mention: true\n"
+ " extra:\n"
+ " strict_mention: false\n",
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ for var in [k for k in os.environ if k.startswith("SLACK_")]:
+ monkeypatch.delenv(var, raising=False)
+
+ with caplog.at_level(logging.WARNING, logger="gateway.config"):
+ config = load_gateway_config()
+
+ assert config.platforms[Platform.SLACK].extra["strict_mention"] is True
+ assert os.environ["SLACK_STRICT_MENTION"] == "true"
+ assert [r for r in caplog.records if r.levelno == logging.WARNING] == []
diff --git a/website/docs/user-guide/messaging/slack.md b/website/docs/user-guide/messaging/slack.md
index d70a3e4ead2..f1541a69a67 100644
--- a/website/docs/user-guide/messaging/slack.md
+++ b/website/docs/user-guide/messaging/slack.md
@@ -680,7 +680,7 @@ When the bot answers a human message with only a [silence token](index.md#intent
:::
:::info
-Slack supports both patterns: `@mention` required to start a conversation by default, but you can opt specific channels out via `SLACK_FREE_RESPONSE_CHANNELS` (comma-separated channel IDs) or `slack.free_response_channels` in `config.yaml`. Once the bot has an active session in a thread, subsequent thread replies do not require a mention. In **1:1 DMs** the bot always responds without needing a mention.
+Slack supports both patterns: `@mention` required to start a conversation by default, but you can opt specific channels out via `SLACK_FREE_RESPONSE_CHANNELS` (comma-separated channel IDs) or `slack.free_response_channels` in `config.yaml`. Once the bot has an active session in a thread, subsequent thread replies do not require a mention. In **1:1 DMs** the bot always responds without needing a mention. These gating keys can be set in the top-level `slack:` block or under `platforms.slack.extra`; when the same key is set in both, `platforms.slack.extra` wins and the gateway logs a warning.
:::
:::caution Group DMs (MPIMs) are shared surfaces, not 1:1 DMs