The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): canonicalize identity first at every adapter ingress path
teknium11654575c6c63
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex ccec3cbdec2..55869af1d63 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -2247,7 +2247,8 @@ class BasePlatformAdapter(ABC):logger.debug("topic recovery hook failed", exc_info=True)returntry:- event.source = dataclasses.replace(source, thread_id=str(recovered))+ from gateway.session_identity import replace_source+ event.source = replace_source(source, thread_id=str(recovered)) # keeps the pinned identityexcept Exception:logger.debug("topic recovery rewrite failed", exc_info=True)@@ -2304,6 +2305,50 @@ class BasePlatformAdapter(ABC)::meth:`_session_key_profile` so adapter-level keys leave ``agent:main:``."""self._owner_profile = None if (name := (profile_name or "").strip() or None) == "default" else name+ def _owner_transport_profile(self) -> Optional[str]:+ """Transport profile for :func:`resolve_identity`: the owner name, or ``None`` = derive it+ from the registry (the primary's identity then spells ``"default"`` out itself)."""+ owner = getattr(self, "_owner_profile", None)+ return owner if isinstance(owner, str) and owner.strip() else None++ def _canonicalize(self, source: Optional["SessionSource"]):+ """Pin the source's :class:`RoutingIdentity` before anything derives a key from it. Every+ ingress path (fresh event, batch merge, busy path, control command, callback) calls this+ FIRST. Returns the identity, or ``None`` when it cannot be resolved (a rejected route under+ multiplexing marks ``source.profile_route_rejected``; ``_drop_unresolved`` reads it) or when+ no runner seam exists (hand-built adapters, restored sources: the legacy readers stay)."""+ if source is None:+ return None+ from gateway.session_identity import canonical_identity, identity_of+ identity = identity_of(source)+ if identity is not None:+ return identity+ runner = getattr(self, "gateway_runner", None)+ if runner is None or not callable(getattr(runner, "_transport_owner", None)):+ return None+ try:+ return canonical_identity(+ source, runner=runner, adapter=self, transport_profile=self._owner_transport_profile())+ except Exception:+ # Duck-typed runners (SimpleNamespace / MagicMock rigs) have no registry to resolve+ # against; the key then falls back to the pre-identity readers instead of failing ingress.+ logger.debug("[%s] identity resolution failed; using legacy key readers", self.name, exc_info=True)+ return None++ def _drop_unresolved(self, event: "MessageEvent") -> bool:+ """True when *event* must be dropped: its identity could not be resolved because the route+ targets an unserved profile. Same disposition as the runner's ingress gate — one WARNING,+ never a fall-through to ``agent:main``."""+ source = getattr(event, "source", None)+ if self._canonicalize(source) is not None:+ return False+ if getattr(source, "profile_route_rejected", False) is not True:+ return False+ logger.warning(+ "[%s] Dropping inbound event for %s: explicit profile route targets an unserved profile",+ self.name, getattr(source, "chat_id", "?"))+ return True+def _session_key_profile(self, source: Optional[Any] = None) -> Optional[str]:"""Profile namespace for an adapter-derived session key. Ingress runs BEFORE the runnerstamps ``source.profile``, so without this every bot in a multiplexed gateway shares one@@ -2344,6 +2389,7 @@ class BasePlatformAdapter(ABC):return self._source_session_key(event.source)def _source_session_key(self, source: "SessionSource") -> str:+ self._canonicalize(source) # identity FIRST; no key derivation before itextra = self.config.extrareturn build_session_key(source, group_sessions_per_user=extra.get("group_sessions_per_user", True),@@ -2356,6 +2402,8 @@ class BasePlatformAdapter(ABC):def _enqueue_text_event(self, event: "MessageEvent") -> None:"""Buffer a text event (merging into a pending one) and restart the flush timer."""+ if self._drop_unresolved(event):+ returnkey = self._text_batch_key(event)existing = self._pending_text_batches.get(key)if existing is None:@@ -3816,6 +3864,9 @@ class BasePlatformAdapter(ABC):if event.allow_gateway_control:coerce_plaintext_gateway_command(event)+ # Identity FIRST: every key below (routing check, guard lookup, batch lane) derives from it.+ if self._drop_unresolved(event):+ returnexpected_session_key = str((event.metadata or {}).get("gateway_session_key") or "").strip()# Explicitly routed events already name their destination; recovering a# different topic would redirect them and yield before the session claim.@@ -3846,6 +3897,7 @@ class BasePlatformAdapter(ABC):# races with the running task (split-brain, see PR #4926).# Certain commands must bypass the active-session guard and be dispatched directly to the gateway# runner. Without this, they are queued as pending messages and either: See #4926.+ self._canonicalize(event.source) # identity FIRST (direct callers may skip handle_message)cmd = event.get_command()from hermes_cli.commands import (is_interrupt_then_dispatch, should_bypass_active_session)if should_bypass_active_session(cmd):diff --git a/gateway/session_identity.py b/gateway/session_identity.pyindex d746cb6e4f6..54e7f81212e 100644--- a/gateway/session_identity.py+++ b/gateway/session_identity.py@@ -15,6 +15,7 @@ receiving bot's own profile — so nothing here changes the wire format or any hfrom __future__ import annotationsimport dataclasses+import loggingimport weakreffrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -23,6 +24,8 @@ from typing import TYPE_CHECKING, Any, Optionalif TYPE_CHECKING:from gateway.session import SessionSource+logger = logging.getLogger(__name__)+_IDENTITY_ATTR = "_identity"# Wire-invisible provenance copied alongside the identity when a source is duplicated._PROVENANCE_ATTRS = ("_transport_adapter_ref", "_authorization_profile_home", _IDENTITY_ATTR)@@ -99,6 +102,26 @@ def _name(value: Any) -> Optional[str]:return text or None+def canonical_identity(+ source: "SessionSource", *, runner: Any, adapter: Any = None,+ transport_profile: Optional[str] = None, primary_home: Optional[Path] = None,+) -> Optional[RoutingIdentity]:+ """The identity already pinned on *source*, else :func:`resolve_identity` — the one call every+ ingress path makes FIRST, before any key is derived. ``None`` = unresolved under multiplexing+ (``source.profile_route_rejected`` is set): the caller drops the event and says so once; it+ must never fall through to ``agent:main``."""+ identity = identity_of(source)+ if identity is not None:+ return identity+ try:+ return resolve_identity(+ source, runner=runner, adapter=adapter, transport_profile=transport_profile,+ primary_home=primary_home)+ except IdentityUnresolved as exc:+ logger.debug("identity unresolved: %s", exc)+ return None++def resolve_identity(source: "SessionSource", *, runner: Any, adapter: Any = None,transport_profile: Optional[str] = None, primary_home: Optional[Path] = None,diff --git a/plugins/platforms/slack/adapter.py b/plugins/platforms/slack/adapter.pyindex 7d39d80b0a3..b377ec3d04d 100644--- a/plugins/platforms/slack/adapter.py+++ b/plugins/platforms/slack/adapter.py@@ -5972,13 +5972,13 @@ class SlackAdapter(BasePlatformAdapter):except Exception:return None- @staticmethoddef _thread_session_source(- channel_id: str, thread_ts: str, user_id: str, team_id: str, chat_type: str) -> Any:- from gateway.session import SessionSource- return SessionSource(- platform=Platform.SLACK, chat_id=channel_id, chat_type=chat_type, user_id=user_id,- thread_id=thread_ts, scope_id=team_id or None)+ self, channel_id: str, thread_ts: str, user_id: str, team_id: str, chat_type: str) -> Any:+ # ``build_source``: transport provenance + profile route, so the thread key canonicalizes+ # like the message that started the thread.+ return self.build_source(+ chat_id=channel_id, chat_type=chat_type, user_id=user_id, thread_id=thread_ts,+ scope_id=team_id or None)def _thread_rehydration_key(self, channel_id: str, thread_ts: str, user_id: str, team_id: str = "") -> str:diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex 1ba65f19252..d8d1999b628 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -6305,6 +6305,8 @@ class TelegramAdapter(BasePlatformAdapter):async def _route_photo_event(self, msg, event: MessageEvent) -> None:"""Album items debounce on media_group_id; singles go through the photo burst batcher."""+ if self._drop_unresolved(event): # identity FIRST: the batch lane is derived from it+ returnmedia_group_id = getattr(msg, "media_group_id", None)if media_group_id:await self._queue_media_group_event(str(media_group_id), event)diff --git a/tests/gateway/test_identity_canonical_ingress.py b/tests/gateway/test_identity_canonical_ingress.pynew file mode 100644index 00000000000..80c49b18447--- /dev/null+++ b/tests/gateway/test_identity_canonical_ingress.py@@ -0,0 +1,181 @@+"""Identity is canonicalized FIRST on every ingress path (#88715 phase 3).++Two Telegram bots on one multiplexed gateway see the same ``chat.id == user.id`` for a DM with the+same human; every adapter-side lane (batch dict, ``_active_sessions``, the busy guard, control+commands, clarify replies) must be keyed by the receiving bot's identity before anything else+derives a key. Real ``GatewayRunner`` resolvers, real ``BasePlatformAdapter`` ingress, temp home.+"""++import asyncio+from types import SimpleNamespace+from unittest.mock import patch++import pytest++from gateway.config import GatewayConfig, Platform, PlatformConfig+from gateway.pairing import PairingStore+from gateway.platforms.base import BasePlatformAdapter, MessageEvent, MessageType+from gateway.profile_routing import parse_profile_routes+from gateway.session_identity import identity_of++UID = "72719239" # Telegram DM: chat.id == user.id, identical for every bot+++class _Stub(BasePlatformAdapter):+ pass+++_Stub.__abstractmethods__ = frozenset()+++def _adapter(runner, owner=None):+ adapter = _Stub.__new__(_Stub)+ BasePlatformAdapter.__init__(adapter, PlatformConfig(enabled=True, extra={}), Platform.TELEGRAM)+ adapter.gateway_runner = runner+ adapter._session_store = SimpleNamespace(_resolve_profile_for_key=lambda s: "default")+ if owner:+ adapter.set_owner_profile(owner)+ return adapter+++def rig(tmp_path, monkeypatch):+ """Default home owns bot A; ``team_b`` owns bot B; satellite ``ops`` is routed through bot A+ for chat 5150; a route to unserved ``ghost`` for chat 4040."""+ from gateway.run import GatewayRunner++ home = tmp_path / "hh"+ for name in ("ops", "team_b"):+ (home / "profiles" / name).mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(home))+ runner = object.__new__(GatewayRunner)+ runner.config = GatewayConfig(multiplex_profiles=True)+ runner.config.platforms = {Platform.TELEGRAM: PlatformConfig(enabled=True, extra={})}+ runner.config.profile_routes = parse_profile_routes([+ {"name": "ops-dm", "platform": "telegram", "profile": "ops", "chat_id": "5150"},+ {"name": "ghost", "platform": "telegram", "profile": "ghost", "chat_id": "4040"},+ ])+ runner.pairing_store = PairingStore(profile="default")+ runner.pairing_stores = {}+ runner._primary_profile_name = "default"+ bot_a, bot_b = _adapter(runner), _adapter(runner, owner="team_b")+ runner.adapters = {Platform.TELEGRAM: bot_a}+ runner._profile_adapters = {"team_b": {Platform.TELEGRAM: bot_b}, "ops": {}}+ served = [("default", home), ("ops", home / "profiles" / "ops"), ("team_b", home / "profiles" / "team_b")]+ with patch("hermes_cli.profiles.profiles_to_serve", return_value=served), \+ patch("hermes_cli.profiles.get_profile_dir", side_effect=lambda n: home if n == "default" else home / "profiles" / n), \+ patch("hermes_cli.profiles.profile_exists", return_value=True):+ yield SimpleNamespace(runner=runner, home=home, bot_a=bot_a, bot_b=bot_b)+++def _event(adapter, chat_id, text, **kw):+ source = adapter.build_source(chat_id=chat_id, chat_type="dm", user_id=chat_id)+ return MessageEvent(text=text, message_type=MessageType.TEXT, source=source, message_id="m", **kw)+++async def _hold(adapter, key):+ guard = asyncio.Event()+ adapter._active_sessions[key] = guard+ adapter._session_tasks[key] = asyncio.create_task(asyncio.sleep(30))+ return guard+++async def test_two_bots_same_chat_have_distinct_lanes_and_stop_cannot_cross(rig):+ """Acceptance row A: the same human DMs both bots. Batching, the active-session guard and a+ ``/stop`` all resolve on the receiving bot's lane; ``/stop`` on A never touches B's run, and the+ clarify reply on A resolves A's pending prompt, not B's."""+ seen = []++ async def handler(event):+ seen.append((identity_of(event.source).transport_profile, event.text))+ return None++ for bot in (rig.bot_a, rig.bot_b):+ bot.set_message_handler(handler)++ ev_a, ev_b = _event(rig.bot_a, UID, "hello A"), _event(rig.bot_b, UID, "hello B")+ rig.bot_a._enqueue_text_event(ev_a)+ rig.bot_b._enqueue_text_event(ev_b)+ key_a, key_b = rig.bot_a._event_session_key(ev_a), rig.bot_b._event_session_key(ev_b)+ assert key_a == f"agent:main:telegram:dm:{UID}" and key_b == f"agent:team_b:telegram:dm:{UID}"+ assert list(rig.bot_a._pending_text_batches) == [key_a] and list(rig.bot_b._pending_text_batches) == [key_b]+ # The identity was pinned BEFORE the key was derived, and the two lanes never share a source.+ assert identity_of(ev_a.source).transport_profile == "default"+ assert identity_of(ev_b.source).transport_profile == "team_b"+ for bot in (rig.bot_a, rig.bot_b):+ for task in list(bot._pending_text_batch_tasks.values()):+ task.cancel()+ bot._pending_text_batches.clear()++ # Both bots busy on "their" chat; /stop on A interrupts A's guard only and B's task survives.+ guard_a, guard_b = await _hold(rig.bot_a, key_a), await _hold(rig.bot_b, key_b)+ task_b = rig.bot_b._session_tasks[key_b]+ await rig.bot_a.handle_message(_event(rig.bot_a, UID, "/stop", allow_gateway_control=True))+ await asyncio.sleep(0)+ assert seen == [("default", "/stop")]+ assert key_a not in rig.bot_a._session_tasks+ assert rig.bot_b._session_tasks[key_b] is task_b and not task_b.cancelled()+ assert rig.bot_b._active_sessions[key_b] is guard_b and not guard_b.is_set()+ assert not guard_a.is_set() # the command path replaced A's guard; the run was cancelled, not flagged++ # Clarify: pending prompts on both lanes; the plain-text answer on A resolves A only.+ from tools import clarify_gateway+ clarify_gateway.register("c-a", key_a, "Which?", ["x", "y"])+ clarify_gateway.register("c-b", key_b, "Which?", ["x", "y"])+ clarify_gateway.mark_awaiting_text("c-a")+ clarify_gateway.mark_awaiting_text("c-b")+ try:+ await _hold(rig.bot_a, key_a)+ await rig.bot_a.handle_message(_event(rig.bot_a, UID, "x", allow_gateway_control=True))+ assert seen[-1] == ("default", "x") # routed through A's inline clarify intercept+ assert clarify_gateway.get_pending_for_session(key_b, include_choice_prompts=True) is not None+ assert key_b not in rig.bot_a._pending_messages and key_a not in rig.bot_b._pending_messages+ finally:+ clarify_gateway.clear_session(key_a)+ clarify_gateway.clear_session(key_b)+ for bot in (rig.bot_a, rig.bot_b):+ for task in bot._session_tasks.values():+ task.cancel()+++async def test_shared_bot_routed_chat_runs_as_satellite_and_unserved_route_is_dropped_everywhere(rig):+ """Acceptance row B: a chat routed through the shared bot to satellite ``ops`` keys into+ ``agent:ops`` on every ingress path (fresh, batch, busy) while the transport stays the receiving+ bot. A route to an unserved profile is dropped at every path — never ``agent:main``."""+ calls = []++ async def handler(event):+ calls.append(event.text)+ return None++ async def busy(event, session_key):+ calls.append(("busy", session_key, identity_of(event.source).runtime_profile))+ return True++ rig.bot_a.set_message_handler(handler)+ rig.bot_a.set_busy_session_handler(busy)++ routed = _event(rig.bot_a, "5150", "hi ops")+ key = rig.bot_a._event_session_key(routed)+ identity = identity_of(routed.source)+ assert key == "agent:ops:telegram:dm:5150"+ assert (identity.transport_profile, identity.runtime_profile) == ("default", "ops")+ assert identity.adapter() is rig.bot_a and identity.runtime_home == rig.home / "profiles" / "ops"++ await _hold(rig.bot_a, key)+ await rig.bot_a.handle_message(_event(rig.bot_a, "5150", "follow-up"))+ assert calls[-1] == ("busy", key, "ops")++ # Unserved route: fresh, batched, busy and control paths all drop; no lane is created or touched.+ main_key = "agent:main:telegram:dm:4040"+ guard = await _hold(rig.bot_a, main_key)+ for text, kw in (("hello", {}), ("/stop", {"allow_gateway_control": True})):+ await rig.bot_a.handle_message(_event(rig.bot_a, "4040", text, **kw))+ rig.bot_a._enqueue_text_event(_event(rig.bot_a, "4040", "chunk"))+ assert calls == [("busy", key, "ops")]+ assert not rig.bot_a._pending_text_batches and main_key not in rig.bot_a._pending_messages+ assert rig.bot_a._active_sessions[main_key] is guard and main_key in rig.bot_a._session_tasks+ for task in rig.bot_a._session_tasks.values():+ task.cancel()