Skip to content

The agent that grows with you

fix(gateway): slash dispatch binds the routed profile's scope once for every handler

KoNit-K5b635064b8aa
diff --git a/gateway/run_busy.py b/gateway/run_busy.py
index aecd7b23472..537d4344136 100644
--- a/gateway/run_busy.py
+++ b/gateway/run_busy.py
@@ -940,7 +940,8 @@ class GatewayBusySessionMixin:
if policy in ("dispatch", "interrupt_then_dispatch"):
plain = self._gateway_plain_command_handlers().get(name)
if plain is not None:
- return await plain(event)
+ async with self._async_profile_scope_for_source(source):
+ return await plain(event)
logger.warning(
"busy_policy=%s for /%s has no mid-run handler — "
"falling back to busy-reject", policy, name,
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.py
index 614434de50b..e893dab2725 100644
--- a/gateway/run_inbound.py
+++ b/gateway/run_inbound.py
@@ -995,7 +995,8 @@ class GatewayInboundMixin:
or self._gateway_idle_command_handlers().get(canonical)
)
if plain_handler is not None:
- return True, await plain_handler(event)
+ async with self._async_profile_scope_for_source(source):
+ return True, await plain_handler(event)
if canonical in self._HM_CANONICAL_COMMANDS:
return await getattr(self, f"_hm_cmd_{canonical}")(event, source, _quick_key)
return False, None
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index 7f33d8d8159..6b436aedc2d 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -2282,6 +2282,19 @@ class GatewayTurnMixin:
return self._resolve_profile_home_for_source(source)
return None
+ def _async_profile_scope_for_source(self, source: SessionSource):
+ """``async with`` twin of :meth:`_profile_scope_for_source` (secret hydration off-loop).
+
+ Slash dispatch runs under the RECEIVING bot's scope (auth needs its ``.env``), which is not
+ the routed runtime when a bot serves another profile's chat; every handler reading
+ home-relative state (pending writes, memory store, config) binds the runtime here (#119915)."""
+ from gateway.run import _async_profile_runtime_scope
+ home = self._profile_scope_key_for_source(source)
+ if home is not None:
+ return _async_profile_runtime_scope(home)
+ from tui_gateway.launch_profile_policy import async_launch_profile_scope_if_multiplexed
+ return async_launch_profile_scope_if_multiplexed()
+
@staticmethod
def _standalone_launch_scope():
"""Scope for a standalone gateway's own (launch-profile) work: a no-op until the process hosts
diff --git a/tests/gateway/test_slash_config_writes_routed_profile.py b/tests/gateway/test_slash_config_writes_routed_profile.py
index c1893156f52..3135e2469c0 100644
--- a/tests/gateway/test_slash_config_writes_routed_profile.py
+++ b/tests/gateway/test_slash_config_writes_routed_profile.py
@@ -15,13 +15,17 @@ import pytest
import yaml
import gateway.run as gateway_run
+from gateway.config import GatewayConfig
from gateway.run import GatewayRunner, _profile_runtime_scope
-from gateway.slash_commands import GatewaySlashCommandsMixin
+from tools import write_approval as wa
-class _Runner(GatewaySlashCommandsMixin):
- _run_in_executor_with_context = GatewayRunner._run_in_executor_with_context
- _get_executor = GatewayRunner._get_executor
+class _Runner(GatewayRunner):
+ """Bare runner (no __init__): the dispatcher binds the routed runtime scope ONCE around every
+ table handler (#119915), so drive the handlers through it rather than calling them directly."""
+
+ def __init__(self): # skip GatewayRunner.__init__: only the dispatcher + slash mixins are exercised
+ self.config = GatewayConfig(multiplex_profiles=True)
def _session_key_for_source(self, _source):
return "k"
@@ -29,11 +33,21 @@ class _Runner(GatewaySlashCommandsMixin):
def _evict_cached_agent(self, _session_key):
pass
+ def _resolve_profile_home_for_source(self, _source):
+ return getattr(self, "routed_home", gateway_run._gateway_config_home())
+
+ async def slash(self, name: str, args: str) -> str:
+ """``/<name> <args>`` through the real dispatcher (ambient scope = the receiving bot's)."""
+ event = _Event(args)
+ handled, reply = await self._hm_dispatch_canonical_command(event, event.source, "k", name)
+ assert handled
+ return reply
+
class _Event:
def __init__(self, args: str = ""):
self._args = args
- self.source = None
+ self.source = object()
def get_command_args(self) -> str:
return self._args
@@ -68,3 +82,50 @@ async def test_slash_config_writes_hit_routed_profile_and_leave_default_untouche
assert routed["memory"]["write_approval"] is True
assert routed["skills"]["write_approval"] is True
assert (default_home / "config.yaml").read_bytes() == default_before
+
+
+async def test_memory_and_skills_review_commands_use_routed_profile_from_dispatch(homes):
+ """The dispatcher binds the routed runtime around the handlers (the ambient scope is the
+ receiving bot's = the default home here), including destructive actions."""
+ default_home, routed_home = homes
+ default_before = (default_home / "config.yaml").read_bytes()
+ runner = _Runner()
+ runner.routed_home = routed_home
+
+ with _profile_runtime_scope(routed_home):
+ memory_approve = wa.stage_write(
+ wa.MEMORY, {"action": "add", "target": "memory", "content": "routed approved"},
+ summary="routed-memory-approve", origin="foreground")
+ memory_reject = wa.stage_write(
+ wa.MEMORY, {"action": "add", "target": "memory", "content": "routed rejected"},
+ summary="routed-memory-reject", origin="foreground")
+ skill_reject = wa.stage_write(
+ wa.SKILLS, {"action": "create", "name": "routed-skill", "content": "---\nname: routed-skill\n---\n"},
+ summary="routed-skill-reject", origin="foreground")
+ skill_approve = wa.stage_write(
+ wa.SKILLS, {"action": "create", "name": "routed-approved-skill",
+ "content": "---\nname: routed-approved-skill\ndescription: Use when testing routed approval.\n---\n\nVerify the routed profile.\n"},
+ summary="routed-skill-approve", origin="foreground")
+
+ with _profile_runtime_scope(default_home):
+ assert "routed-memory-approve" in await runner.slash("memory", "pending")
+ assert "Approved 1 memory write(s)." in await runner.slash("memory", f"approve {memory_approve['id']}")
+ assert "routed approved" in (routed_home / "memories" / "MEMORY.md").read_text()
+ assert "Rejected pending memory write" in await runner.slash("memory", f"reject {memory_reject['id']}")
+ assert "routed-skill-reject" in await runner.slash("skills", "pending")
+ assert "Pending skill write" in await runner.slash("skills", f"diff {skill_reject['id']}")
+ assert "Rejected pending skills write" in await runner.slash("skills", f"reject {skill_reject['id']}")
+ assert "Approved 1 skills write(s)." in await runner.slash("skills", f"approve {skill_approve['id']}")
+ assert (routed_home / "skills" / "routed-approved-skill" / "SKILL.md").exists()
+ assert "set to 'on'" in await runner.slash("memory", "approval on")
+ assert "set to 'on'" in await runner.slash("skills", "approval on")
+ assert gateway_run._gateway_config_home() == default_home # ambient scope restored per dispatch
+
+ routed = yaml.safe_load((routed_home / "config.yaml").read_text())
+ assert routed["memory"]["write_approval"] is True
+ assert routed["skills"]["write_approval"] is True
+ assert not (default_home / "pending").exists()
+ assert not (default_home / "memories").exists()
+ assert not (default_home / "skills").exists()
+ assert (default_home / "config.yaml").read_bytes() == default_before
diff --git a/tests/gateway/test_slash_dispatch_routed_scope.py b/tests/gateway/test_slash_dispatch_routed_scope.py
new file mode 100644
index 00000000000..5612257fc4b
--- /dev/null
+++ b/tests/gateway/test_slash_dispatch_routed_scope.py
@@ -0,0 +1,80 @@
+"""Slash dispatch binds the ROUTED profile's runtime scope around every table handler (#119915).
+
+Under multiplex the message handler runs under the RECEIVING bot's scope so authorization can read
+its ``.env``; a chat that bot serves for ANOTHER profile (``profile_routes`` / ``bot_profile``) has a
+different runtime home. Handlers reading home-relative state (``/memory`` and ``/skills`` pending
+records, the on-disk memory store, config write-back) must see the runtime home, so the dispatcher
+binds it once for the whole table instead of each handler re-entering the scope.
+"""
+
+import pytest
+
+from gateway.config import GatewayConfig, Platform
+from gateway.platforms.base import MessageEvent, MessageType
+from gateway.run import GatewayRunner, _profile_runtime_scope
+from gateway.session import SessionSource
+from hermes_constants import get_hermes_home
+from tools import write_approval as wa
+
+
+def homes(tmp_path, monkeypatch):
+ launch = tmp_path / "launch"
+ routed = tmp_path / "profiles" / "beta"
+ (launch / "pending" / "memory").mkdir(parents=True)
+ (routed / "pending" / "memory").mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(launch))
+ return launch, routed
+
+
+def _runner(routed_home):
+ runner = object.__new__(GatewayRunner)
+ runner.config = GatewayConfig(multiplex_profiles=True)
+ runner._resolve_profile_home_for_source = lambda _source: routed_home
+ runner._session_key_for_source = lambda _source: "k"
+ runner._evict_cached_agent = lambda _key: None
+ return runner
+
+
+def _event(text):
+ source = SessionSource(platform=Platform.TELEGRAM, user_id="u", user_name="u",
+ chat_id="c", chat_type="dm", profile="beta")
+ return MessageEvent(text=text, message_type=MessageType.TEXT, source=source, message_id="m")
+
+
+async def test_idle_dispatch_runs_table_handlers_under_the_routed_runtime(homes):
+ launch, routed = homes
+ with _profile_runtime_scope(routed):
+ staged = wa.stage_write(wa.MEMORY, {"action": "add", "target": "memory", "content": "beta"},
+ summary="beta-only", origin="foreground")
+ runner = _runner(routed)
+ event = _event("/memory pending")
+
+ # Ambient scope is the LAUNCH home (what the receiving bot's handler binds); the dispatcher
+ # must still resolve the routed runtime for the handler.
+ with _profile_runtime_scope(launch):
+ handled, reply = await runner._hm_dispatch_canonical_command(event, event.source, "k", "memory")
+ assert get_hermes_home() == launch # scope restored after dispatch
+
+ assert handled and staged["id"] in reply
+ assert not list((launch / "pending" / "memory").glob("*.json"))
+
+
+async def test_busy_dispatch_binds_the_same_runtime_scope(homes):
+ launch, routed = homes
+ from hermes_cli.commands import resolve_command
+ seen = {}
+
+ async def _probe(_event):
+ seen["home"] = get_hermes_home()
+ return "ok"
+
+ runner = _runner(routed)
+ runner._handle_restart_command = _probe
+ event = _event("/restart")
+ with _profile_runtime_scope(launch):
+ assert await runner._dispatch_busy_slash_command(
+ event, resolve_command("restart"), "k", event.source) == "ok"
+ assert seen["home"] == routed