Skip to content

The agent that grows with you

feat(gateway): RoutingIdentity — one frozen identity per inbound event

teknium1ad651b825076
diff --git a/gateway/AGENTS.md b/gateway/AGENTS.md
index 3f7fc691c9c..d41911e2d24 100644
--- a/gateway/AGENTS.md
+++ b/gateway/AGENTS.md
@@ -133,6 +133,15 @@ gateway under the backend, and do NOT "fix" update locks by widening the tree-ki
## Profile scope (adapters, turns, and everything between turns)
+- **One identity per inbound event.** `gateway/session_identity.py::resolve_identity` answers
+ "which bot received it / who may admit it / where does it run" ONCE per event and pins a frozen
+ `RoutingIdentity` on the source (wire-invisible, like `_transport_adapter_ref`);
+ `_transport_owner`, `_authorization_home_for_source`, `_resolve_profile_home_for_source`,
+ `_session_key_profile` and `_resolve_profile_for_key` read it when present and fall back to
+ their old chain only for sources nothing resolved (restored rows, hand-built sources). Never
+ derive a second answer next to the identity; extend the object. `transport_profile` ≠
+ `runtime_profile` is normal (shared bot → routed satellite). A source copy goes through
+ `session_identity.replace_source` so the identity travels with it.
- **Token locks.** An adapter that connects with a unique credential (bot token, API key) calls
`acquire_scoped_lock()` from `gateway.status` in `connect()`/`start()` and `release_scoped_lock()`
in `disconnect()`/`stop()`, so two profiles cannot share one credential. Canonical:
diff --git a/gateway/authz_mixin.py b/gateway/authz_mixin.py
index 6ea612b7bd0..dc9a98af876 100644
--- a/gateway/authz_mixin.py
+++ b/gateway/authz_mixin.py
@@ -293,13 +293,18 @@ class GatewayAuthorizationMixin:
return (adapter, profile) if registered else None
def _authorization_home_for_source(self, source: SessionSource):
- """HERMES_HOME whose allowlist admits *source*: the ingress-stamped transport home, else the home of
- the profile owning the adapter that delivers it. ``None`` = authorize in the ambient scope
- (multiplex off, or no live adapter — the check then fails closed on its own).
+ """HERMES_HOME whose allowlist admits *source*: the identity's transport home (or the
+ ingress-stamped one), else the home of the profile owning the adapter that delivers it.
+ ``None`` = authorize in the ambient scope (multiplex off, or no live adapter — the check then
+ fails closed on its own).
Inside a routed satellite's turn the ambient scope is the satellite's, whose ``.env`` has no
token/allowlist; every authorization decision made mid-turn (``/topic``, sibling ``/stop``, plugin
injection, voice, auto-resume) must read the admitting bot's allowlist instead."""
+ from gateway.session_identity import identity_of
+ identity = identity_of(source)
+ if identity is not None:
+ return identity.authorization_home if identity.multiplexed else None
stamped = getattr(source, "_authorization_profile_home", None)
if stamped is not None:
return Path(stamped)
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index 83b8a03985b..0aeadcf2fe4 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -2307,9 +2307,13 @@ class BasePlatformAdapter(ABC):
def _session_key_profile(self, source: Optional[Any] = None) -> Optional[str]:
"""Profile namespace for an adapter-derived session key. Ingress runs BEFORE the runner
stamps ``source.profile``, so without this every bot in a multiplexed gateway shares one
- ``agent:main:`` lane. Order: ``source.profile`` → ``_owner_profile`` → session-store
- resolver; getattr-guarded (object.__new__ in tests), type-checked (no MagicMock in the
- key)."""
+ ``agent:main:`` lane. Order: pinned ``RoutingIdentity`` → ``source.profile`` →
+ ``_owner_profile`` → session-store resolver; getattr-guarded (object.__new__ in tests),
+ type-checked (no MagicMock in the key)."""
+ from gateway.session_identity import identity_of
+ identity = identity_of(source)
+ if identity is not None:
+ return identity.session_key_profile
for candidate in (
getattr(source, "profile", None) if source is not None else None,
getattr(self, "_owner_profile", None)):
diff --git a/gateway/run.py b/gateway/run.py
index cbfff36c695..080420bb5dd 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -4336,11 +4336,16 @@ class GatewayRunner(
return None
def _resolve_profile_home_for_source(self, source: SessionSource) -> "Path":
- """Resolve which profile's HERMES_HOME serves this source: ``source.profile``, then
- ``_profile_name_for_source`` (sources bypassing ``build_source``), then the active profile."""
+ """Resolve which profile's HERMES_HOME serves this source: the pinned identity's runtime
+ home, else ``source.profile``, then ``_profile_name_for_source`` (sources bypassing
+ ``build_source``), then the active profile."""
from gateway.profile_routing import ProfileRouteRejected
+ from gateway.session_identity import identity_of
from hermes_cli.profiles import get_active_profile_name, get_profile_dir, profile_exists
from hermes_constants import get_hermes_home
+ identity = identity_of(source)
+ if identity is not None:
+ return identity.runtime_home
explicit_profile = None # explicitly requested (source or routing) vs. default fallback
try:
name = (source.profile or "").strip() or self._profile_name_for_source(source)
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.py
index bb9aa3b9e93..bedf66a8520 100644
--- a/gateway/run_adapters.py
+++ b/gateway/run_adapters.py
@@ -1348,12 +1348,18 @@ class GatewayAdapterLifecycleMixin:
"""``scope_factory(profile_home)`` or a nullcontext when the profile home is unknown."""
return scope_factory(profile_home) if profile_home is not None else contextlib.nullcontext()
- @staticmethod
- def _stamp_event_profile(event, profile_name: str) -> None:
- """Best-effort: stamp ``source.profile`` on an inbound event that has none yet."""
+ def _stamp_event_profile(self, event, profile_name: str) -> None:
+ """Best-effort: pin the secondary's identity on an inbound event (stamps ``source.profile``
+ when none yet). A source that cannot resolve keeps today's fallback readers."""
+ source = getattr(event, "source", None)
+ if source is None:
+ return
with suppress(Exception):
- if getattr(event, "source", None) is not None and not event.source.profile:
- event.source.profile = profile_name
+ from gateway.session_identity import resolve_identity
+ resolve_identity(source, runner=self, transport_profile=profile_name)
+ with suppress(Exception):
+ if not source.profile:
+ source.profile = profile_name
def _make_profile_message_handler(self, profile_name: str):
"""Message handler that stamps source.profile, then delegates under the profile scope
@@ -1415,23 +1421,14 @@ class GatewayAdapterLifecycleMixin:
return _handler
def _admit_primary_source(self, source, default_home: Path) -> Optional[Path]:
- """Stamp the transport home (authorization) and routed profile on a primary-adapter source and
- return the runtime home to scope the turn under; ``None`` when the route targets an unserved
- profile. ``_authorization_profile_home`` is in-process only (serialization ignores dynamic attrs);
- route ≠ admitting bot."""
- source._authorization_profile_home = default_home
- if (
- not getattr(source, "profile", None)
- and getattr(source, "profile_route_rejected", False) is not True
- and not self._stamp_routed_profile(source)
- ):
- source.profile_route_rejected = True
- if getattr(source, "profile_route_rejected", False) is True:
+ """Resolve the primary-adapter source's identity (transport home for authorization, routed
+ profile for the runtime) and return the runtime home to scope the turn under; ``None`` when
+ the route targets an unserved profile. Route ≠ admitting bot."""
+ from gateway.session_identity import IdentityUnresolved, resolve_identity
+ try:
+ return resolve_identity(source, runner=self, primary_home=default_home).runtime_home
+ except IdentityUnresolved:
return None
- return (
- self._resolve_profile_home_for_source(source)
- if getattr(source, "profile", None) else default_home
- )
def _stamp_routed_profile(self, source) -> bool:
"""Stamp ``source.profile`` from ``profile_routes``; False when the route is rejected."""
diff --git a/gateway/run_topics.py b/gateway/run_topics.py
index 05b6abf70ab..cc467c1b43b 100644
--- a/gateway/run_topics.py
+++ b/gateway/run_topics.py
@@ -5,7 +5,6 @@
from __future__ import annotations
import asyncio
-import dataclasses
import logging
import re
import time
@@ -434,12 +433,10 @@ class GatewayTopicThreadsMixin:
return
copied_source = source
with suppress(Exception):
- copied_source = dataclasses.replace(source)
- # Keep the live transport owner; multiplex routes may run under a
+ # Keep the live transport owner and identity; multiplex routes may run under a
# profile that does not own the Discord adapter/token.
- transport_ref = getattr(source, "_transport_adapter_ref", None)
- if transport_ref is not None:
- setattr(copied_source, "_transport_adapter_ref", transport_ref)
+ from gateway.session_identity import replace_source
+ copied_source = replace_source(source)
future = safe_schedule_threadsafe(
make_coro(copied_source), loop, logger=logger, log_message=f"{label} failed to schedule",
)
diff --git a/gateway/session_identity.py b/gateway/session_identity.py
new file mode 100644
index 00000000000..d746cb6e4f6
--- /dev/null
+++ b/gateway/session_identity.py
@@ -0,0 +1,183 @@
+"""One frozen routing identity per inbound gateway event.
+
+A multiplexed gateway answers three questions about every event, and until now answered them in
+three places that only agreed because they read the same fallback chain: WHICH bot received it
+(``_transport_owner``), WHO may admit it (``_authorization_home_for_source``) and WHERE the turn
+runs (``_resolve_profile_home_for_source`` / ``_session_key_profile``). :func:`resolve_identity`
+answers all three once and pins the result on the source as a wire-invisible dynamic attribute
+(like ``_transport_adapter_ref``); the existing helpers read it when present and keep their
+fallback chain when absent, so a source built outside the runner still resolves as before.
+
+``SessionSource.profile`` stays the serialized runtime profile — ``None`` on the wire means the
+receiving bot's own profile — so nothing here changes the wire format or any historical
+``agent:main`` key.
+"""
+from __future__ import annotations
+
+import dataclasses
+import weakref
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Optional
+
+if TYPE_CHECKING:
+ from gateway.session import SessionSource
+
+_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)
+
+
+class IdentityUnresolved(RuntimeError):
+ """Under multiplexing the event's runtime profile could not be established (an explicit
+ ``profile_routes`` entry targets a profile this gateway does not serve). Callers drop the
+ event; it must never fall through to the default profile."""
+
+
+@dataclass(frozen=True)
+class RoutingIdentity:
+ """Everything a turn needs to know about who it is, resolved once at ingress.
+
+ ``transport_profile`` owns the receiving adapter (its credential and allowlist);
+ ``runtime_profile`` is the profile that executes the turn — the same name unless a
+ ``profile_routes`` entry re-homed the event. Both are explicit (``"default"`` is spelled out);
+ ``None`` never means default here. ``multiplexed`` is False for a standalone gateway, whose
+ keys stay in the legacy ``agent:main`` namespace whatever profile it was launched with.
+ """
+
+ transport_profile: str
+ runtime_profile: str
+ authorization_home: Path
+ runtime_home: Path
+ multiplexed: bool = True
+ # Receiving adapter; None for restored/synthetic sources (no live provenance → fail closed).
+ # Provenance, not identity: two events from the same bot share one identity.
+ transport: Optional[weakref.ref] = field(default=None, compare=False, hash=False)
+
+ @property
+ def namespace(self) -> str:
+ """``agent:<ns>`` prefix for this identity's session keys — byte-identical to
+ :func:`gateway.session._session_key_namespace` for every historical key."""
+ from gateway.session import _session_key_namespace
+ return _session_key_namespace(self.session_key_profile)
+
+ @property
+ def store_path(self) -> Path:
+ return self.runtime_home / "state.db"
+
+ @property
+ def session_key_profile(self) -> Optional[str]:
+ """The ``profile=`` argument :func:`gateway.session.build_session_key` expects for this
+ identity: the runtime profile under multiplexing, else ``None`` (legacy namespace)."""
+ return self.runtime_profile if self.multiplexed else None
+
+ def adapter(self) -> Any:
+ """The live receiving adapter, or None when it is gone or was never known."""
+ return self.transport() if self.transport is not None else None
+
+
+def identity_of(source: Any) -> Optional[RoutingIdentity]:
+ """The identity pinned on *source* by :func:`resolve_identity`, if any."""
+ identity = getattr(source, _IDENTITY_ATTR, None)
+ return identity if isinstance(identity, RoutingIdentity) else None
+
+
+def replace_source(source: "SessionSource", **changes: Any) -> "SessionSource":
+ """:func:`dataclasses.replace` that keeps the wire-invisible provenance (transport ref,
+ authorization home, identity). A plain ``replace`` silently produces a source the runner
+ can only route through heuristics."""
+ copied = dataclasses.replace(source, **changes)
+ for name in _PROVENANCE_ATTRS:
+ value = getattr(source, name, None)
+ if value is not None:
+ setattr(copied, name, value)
+ return copied
+
+
+def _name(value: Any) -> Optional[str]:
+ text = value.strip() if isinstance(value, str) else ""
+ return text or None
+
+
+def resolve_identity(
+ source: "SessionSource", *, runner: Any, adapter: Any = None,
+ transport_profile: Optional[str] = None, primary_home: Optional[Path] = None,
+) -> RoutingIdentity:
+ """Resolve and pin the :class:`RoutingIdentity` of an inbound *source*.
+
+ *adapter* is the receiving adapter when the caller holds it; otherwise the source's own
+ transport provenance is consulted. *transport_profile* names the receiving bot's owning
+ profile when the caller knows it by construction (the runner's per-profile handlers);
+ ``None`` = derive it from the adapter registry, primary when unknown. *primary_home* is the
+ primary bot's home for authorization (default: the process home, never a per-turn override).
+
+ Stamps ``source.profile`` the way the ingress handlers always did (routed name, else a
+ secondary's own name; ``None`` stays ``None`` for the primary so the wire is unchanged) and
+ ``_authorization_profile_home`` for the existing authorization readers.
+
+ Raises :class:`IdentityUnresolved` under multiplexing when the route is rejected.
+ """
+ from gateway.profile_routing import ProfileRouteRejected
+ from hermes_constants import get_hermes_home, get_process_hermes_home
+
+ multiplexed = bool(getattr(getattr(runner, "config", None), "multiplex_profiles", False))
+ primary_profile = _name(getattr(runner, "_primary_profile_name", None))
+ if primary_profile is None:
+ active = getattr(runner, "_active_profile_name", None)
+ primary_profile = (_name(active()) if callable(active) else None) or "default"
+ platform = getattr(source, "platform", None)
+
+ owner_profile: Optional[str] = None
+ if adapter is None:
+ owner = runner._transport_owner(source)
+ if owner is not None:
+ adapter, owner_profile = owner
+ else:
+ if getattr(source, "_transport_adapter_ref", None) is None:
+ source._transport_adapter_ref = weakref.ref(adapter)
+ _registered, owner_profile = runner._owning_profile(adapter, platform)
+ transport_name = _name(transport_profile) or _name(owner_profile) or primary_profile
+ transport_ref = weakref.ref(adapter) if adapter is not None else None
+
+ if not multiplexed:
+ home = Path(get_hermes_home())
+ identity = RoutingIdentity(
+ transport_profile=primary_profile, runtime_profile=primary_profile,
+ authorization_home=home, runtime_home=home, multiplexed=False, transport=transport_ref)
+ setattr(source, _IDENTITY_ATTR, identity)
+ return identity
+
+ if transport_name == primary_profile:
+ authorization_home = Path(primary_home) if primary_home is not None else Path(get_process_hermes_home())
+ else:
+ from hermes_cli.profiles import get_profile_dir
+ authorization_home = get_profile_dir(transport_name)
+ source._authorization_profile_home = authorization_home
+
+ where = f"{getattr(platform, 'value', platform)}/{getattr(source, 'chat_id', '')}"
+ if getattr(source, "profile_route_rejected", False) is True:
+ raise IdentityUnresolved(f"{where}: profile route rejected")
+ if _name(getattr(source, "profile", None)) is None:
+ adapter_profile = None if transport_name == primary_profile else transport_name
+ try:
+ # The primary keeps the historical one-argument call (its adapter profile is None).
+ routed = (
+ runner._profile_name_for_source(source) if adapter_profile is None
+ else runner._profile_name_for_source(source, adapter_profile=adapter_profile))
+ except ProfileRouteRejected as exc:
+ source.profile_route_rejected = True
+ raise IdentityUnresolved(f"{where}: {exc}") from exc
+ source.profile = routed or adapter_profile
+
+ runtime_name = _name(source.profile) or primary_profile
+ # A routed runtime goes through the runner's resolver (missing-profile fallback + warning);
+ # a bot serving its own profile runs where it authorizes.
+ runtime_home = (
+ authorization_home if runtime_name == transport_name
+ else Path(runner._resolve_profile_home_for_source(source)))
+ identity = RoutingIdentity(
+ transport_profile=transport_name, runtime_profile=runtime_name,
+ authorization_home=authorization_home, runtime_home=runtime_home,
+ multiplexed=True, transport=transport_ref)
+ setattr(source, _IDENTITY_ATTR, identity)
+ return identity
diff --git a/gateway/session_recovery.py b/gateway/session_recovery.py
index cdc13acd43d..770f69295a0 100644
--- a/gateway/session_recovery.py
+++ b/gateway/session_recovery.py
@@ -35,9 +35,14 @@ class SessionRecoveryMixin:
def _resolve_profile_for_key(self, source: Optional[SessionSource] = None) -> Optional[str]:
"""Profile namespace for session keys: None when multiplexing is off (legacy
- ``agent:main``), else ``source.profile`` or the active profile."""
+ ``agent:main``), else the pinned identity's runtime profile, ``source.profile`` or the
+ active profile."""
if not getattr(self.config, "multiplex_profiles", False):
return None
+ from gateway.session_identity import identity_of
+ identity = identity_of(source)
+ if identity is not None:
+ return identity.session_key_profile
if source is not None and source.profile:
return source.profile
try:
diff --git a/tests/gateway/test_session_identity.py b/tests/gateway/test_session_identity.py
new file mode 100644
index 00000000000..201d551b76d
--- /dev/null
+++ b/tests/gateway/test_session_identity.py
@@ -0,0 +1,147 @@
+"""Invariants for ``gateway/session_identity.py`` (#88715 phase 1).
+
+One frozen ``RoutingIdentity`` per inbound event, resolved by the real ``GatewayRunner`` resolvers
+(no patched predicates) against a temp ``HERMES_HOME`` with two served profiles.
+"""
+
+import dataclasses
+import weakref
+from pathlib import Path
+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
+from gateway.profile_routing import parse_profile_routes
+from gateway.session import SessionSource, build_session_key
+from gateway.session_identity import (
+ IdentityUnresolved, RoutingIdentity, identity_of, replace_source, resolve_identity,
+)
+
+
+class _Stub(BasePlatformAdapter):
+ pass
+
+
+_Stub.__abstractmethods__ = frozenset()
+
+
+def _stub(platform, runner, label):
+ adapter = _Stub.__new__(_Stub)
+ adapter.platform, adapter.gateway_runner, adapter.label = platform, runner, label
+ adapter.config = PlatformConfig(enabled=True, extra={})
+ adapter._pending_messages, adapter._active_sessions = {}, {}
+ return adapter
+
+
+def _runner(home, *, multiplex, routes=()):
+ from gateway.run import GatewayRunner
+
+ runner = object.__new__(GatewayRunner)
+ runner.config = GatewayConfig(multiplex_profiles=multiplex)
+ runner.config.platforms = {Platform.TELEGRAM: PlatformConfig(enabled=True, extra={})}
+ runner.config.profile_routes = parse_profile_routes(list(routes))
+ runner.pairing_store = PairingStore(profile="default")
+ runner.pairing_stores = {}
+ runner._primary_profile_name = "default"
+ primary = _stub(Platform.TELEGRAM, runner, "PRIMARY")
+ team_b = _stub(Platform.TELEGRAM, runner, "TEAM_B")
+ team_b.set_owner_profile("team_b")
+ runner.adapters = {Platform.TELEGRAM: primary}
+ runner._profile_adapters = {"team_b": {Platform.TELEGRAM: team_b}, "ops": {}}
+ return SimpleNamespace(runner=runner, home=home, primary=primary, team_b=team_b)
+
+
+def mux(tmp_path, monkeypatch):
+ """Default home + satellite ``ops`` (routed through the shared bot for chat 72719239) + ``team_b``
+ owning its own Telegram bot; a route to unserved ``ghost`` for chat 4040."""
+ home = tmp_path / "hh"
+ for name in ("ops", "team_b"):
+ (home / "profiles" / name).mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ served = [("default", home), ("ops", home / "profiles" / "ops"), ("team_b", home / "profiles" / "team_b")]
+ rig = _runner(home, multiplex=True, routes=[
+ {"name": "admin-dm", "platform": "telegram", "profile": "ops", "chat_id": "72719239"},
+ {"name": "ghost", "platform": "telegram", "profile": "ghost", "chat_id": "4040"},
+ ])
+ 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 rig
+
+
+def test_identity_is_one_frozen_value_that_every_reader_agrees_on(mux):
+ """Shared bot → routed satellite: transport stays default (authorization), runtime is ``ops``;
+ the pinned identity is frozen, equal by value, and the legacy readers all report the same
+ answer it does. A dedicated secondary resolves to itself on both axes."""
+ routed = mux.primary.build_source(chat_id="72719239", chat_type="dm", user_id="72719239")
+ identity = resolve_identity(routed, runner=mux.runner)
+
+ assert identity == RoutingIdentity(
+ transport_profile="default", runtime_profile="ops", authorization_home=mux.home,
+ runtime_home=mux.home / "profiles" / "ops")
+ assert identity.namespace == "agent:ops" and identity.store_path == mux.home / "profiles" / "ops" / "state.db"
+ assert identity.adapter() is mux.primary
+ with pytest.raises(dataclasses.FrozenInstanceError):
+ identity.runtime_profile = "default"
+ assert identity_of(routed) is identity
+ # Thin readers: same object, same answers — no second derivation.
+ assert mux.runner._authorization_home_for_source(routed) == mux.home
+ assert mux.runner._resolve_profile_home_for_source(routed) == mux.home / "profiles" / "ops"
+ assert mux.runner._transport_owner(routed) == (mux.primary, None)
+ assert mux.primary._source_session_key(routed) == "agent:ops:telegram:dm:72719239"
+ assert mux.runner._session_key_for_source(routed) == mux.primary._source_session_key(routed)
+
+ own = mux.team_b.build_source(chat_id="72719239", chat_type="dm", user_id="72719239")
+ own_identity = resolve_identity(own, runner=mux.runner, transport_profile="team_b")
+ assert (own_identity.transport_profile, own_identity.runtime_profile) == ("team_b", "team_b")
+ assert own_identity.authorization_home == own_identity.runtime_home == mux.home / "profiles" / "team_b"
+ assert own_identity != identity
+ # Provenance is not identity: a second event from the same bot has the same identity.
+ again = mux.primary.build_source(chat_id="72719239", chat_type="dm", user_id="72719239")
+ assert resolve_identity(again, runner=mux.runner) == identity
+ assert hash(resolve_identity(again, runner=mux.runner)) == hash(identity)
+
+
+def test_unresolved_under_multiplex_raises_and_never_means_default(mux, tmp_path, monkeypatch):
+ """A route to an unserved profile raises ``IdentityUnresolved`` (the runner drops the event);
+ outside multiplexing the same source resolves to an explicit default identity whose keys stay
+ byte-identical to the legacy ``agent:main`` namespace."""
+ rejected = mux.primary.build_source(chat_id="4040", chat_type="dm", user_id="4040")
+ with pytest.raises(IdentityUnresolved):
+ resolve_identity(rejected, runner=mux.runner)
+ assert identity_of(rejected) is None
+ assert mux.runner._admit_primary_source(rejected, mux.home) is None
+
+ solo_home = tmp_path / "solo"
+ solo_home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(solo_home))
+ solo = _runner(solo_home, multiplex=False)
+ source = solo.primary.build_source(chat_id="4040", chat_type="dm", user_id="4040")
+ identity = resolve_identity(source, runner=solo.runner)
+ assert (identity.transport_profile, identity.runtime_profile, identity.multiplexed) == ("default", "default", False)
+ assert identity.runtime_home == solo_home
+ assert identity.namespace == "agent:main"
+ assert solo.primary._source_session_key(source) == build_session_key(source) == "agent:main:telegram:dm:4040"
+ assert source.profile is None # wire format untouched
+ assert solo.runner._authorization_home_for_source(source) is None # ambient scope, as before
+
+
+def test_replace_source_keeps_identity_and_transport_where_dataclasses_replace_drops_them(mux):
+ routed = mux.primary.build_source(chat_id="72719239", chat_type="dm", user_id="72719239")
+ identity = resolve_identity(routed, runner=mux.runner)
+
+ bare = dataclasses.replace(routed)
+ assert identity_of(bare) is None and mux.runner._transport_owner(bare) is None
+
+ copied = replace_source(routed, thread_id="7")
+ assert copied.thread_id == "7" and copied is not routed
+ assert identity_of(copied) is identity
+ assert mux.runner._transport_owner(copied) == (mux.primary, None)
+ assert isinstance(copied._transport_adapter_ref, weakref.ref)
+ assert Path(copied._authorization_profile_home) == mux.home
+ assert mux.primary._source_session_key(copied) == "agent:ops:telegram:dm:72719239:7"
diff --git a/website/docs/developer-guide/multiplexing-gateway.md b/website/docs/developer-guide/multiplexing-gateway.md
index 613f4891f9a..2d6c91e74e2 100644
--- a/website/docs/developer-guide/multiplexing-gateway.md
+++ b/website/docs/developer-guide/multiplexing-gateway.md
@@ -168,13 +168,23 @@ Pairing stores are constructed per served profile.
## Per-bot session lanes
Session keys are namespaced by profile (`agent:main` for default,
-`agent:<name>` for named profiles). Adapters carry `_owner_profile`
-(installed at adapter configuration time, before any inbound event) because
-adapter ingress runs before `SessionSource.profile` is stamped;
-`_session_key_profile` resolves source stamp → owner profile → store
-resolver. Text/media batching, active-session tracking, and the busy-session
-guard are all keyed per lane, so two bots sharing a chat do not share a
-session lane.
+`agent:<name>` for named profiles). Every inbound event carries ONE frozen
+`RoutingIdentity` (`gateway/session_identity.py`), resolved by
+`resolve_identity()` at the runner's ingress handlers and pinned on the source
+as a wire-invisible attribute: `transport_profile` (the bot that received it —
+credential, allowlist, `authorization_home`), `runtime_profile` (the routed
+profile that executes — `runtime_home`, key `namespace`, `store_path`) and a
+weak `transport` ref to the receiving adapter. `"default"` is spelled out;
+`None` never means default. Under multiplexing a route to an unserved profile
+raises `IdentityUnresolved` and the event is dropped.
+
+Adapters also carry `_owner_profile` (installed at adapter configuration time,
+before any inbound event) because adapter ingress runs before the runner pins
+the identity; `_session_key_profile` resolves identity → source stamp → owner
+profile → store resolver. Text/media batching, active-session tracking, and the
+busy-session guard are all keyed per lane, so two bots sharing a chat do not
+share a session lane. Copy a source with `session_identity.replace_source`, not
+`dataclasses.replace`, or the copy loses its transport and identity.
## Control plane