Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
perf(rooms): stop holding a DB connection across Matrix calls, and collapse the @mention fan-out (#354)
Louis Amaudruz11ec7e2159da
diff --git a/core/switch_core/bridges/agent/commands.py b/core/switch_core/bridges/agent/commands.pyindex a49f6f1d1..3449d6fa6 100644--- a/core/switch_core/bridges/agent/commands.py+++ b/core/switch_core/bridges/agent/commands.py@@ -74,9 +74,10 @@ async def _addressed_by_name_or_role(return Trueif client._args_tag_my_name(args):return True- if await client._text_tags_my_alias(args, room_id):- return True- return await client._text_tags_my_role(args, room_id)+ async with client.session_factory() as session:+ if await client._text_tags_my_alias(session, args, room_id):+ return True+ return await client._text_tags_my_role(session, args, room_id)async def _addressed_by_first_mention(@@ -120,9 +121,10 @@ async def _first_token_is_me(client: AgentClient, first: str, room_id: str) -> b"""Whether `@first` names this agent — by name, room alias, or a held role."""if client._args_tag_my_name(f"@{first}"):return True- if await client._text_tags_my_alias(f"@{first}", room_id):- return True- return await client._text_tags_my_role(f"@{first}", room_id)+ async with client.session_factory() as session:+ if await client._text_tags_my_alias(session, f"@{first}", room_id):+ return True+ return await client._text_tags_my_role(session, f"@{first}", room_id)async def _check_control_target(@@ -291,7 +293,8 @@ async def _dispatch_control_command(the room at all (`no_live_session_msg`) vs. a live session that can't becontrolled from here — e.g. not started from Switch Console (`no_session_msg`)."""- agent = await client._fresh_agent()+ async with client.session_factory() as session:+ agent = await client._fresh_agent(session)profile = agent.integration_profile or {}level = (profile.get("command_capabilities") or {}).get(command, "unsupported")@@ -956,19 +959,20 @@ async def _cmd_run_cmd(# started session lands in the room AND assumes the role in one command.# An unknown role is NOT folded in — we warn instead of silently dropping.role = _role_arg(event.args)- role_known = False- if role is not None:- async with client.session_factory() as session:- role_obj = await client._room_role_store.get_role(- session, meta.room_id, role- )- role_known = role_obj is not None+ async with client.session_factory() as session:+ role_obj = (+ await client._room_role_store.get_role(session, meta.room_id, role)+ if role is not None+ else None+ )+ owner_handle = await client.owner_handle_in(session, agent, meta.bridge_id)+ role_known = role_obj is not Nonemsg = spec.start_session_instructions(options,agent,meta.name,- await client.owner_handle_in(agent, meta.bridge_id),+ owner_handle,assume_role=role if role_known else None,)if msg is None:diff --git a/core/switch_core/bridges/collaboration/telegram/adapter.py b/core/switch_core/bridges/collaboration/telegram/adapter.pyindex 4bbe2ed96..688e7d2a5 100644--- a/core/switch_core/bridges/collaboration/telegram/adapter.py+++ b/core/switch_core/bridges/collaboration/telegram/adapter.py@@ -177,6 +177,11 @@ class TelegramAdapter(CollaborationAdapter):# people who address by numeric id rather than handle.self._user_names: dict[int, str] = {}self._username_to_id: dict[str, int] = {}+ # chat id -> its public `@name`, or None for a chat that resolved and+ # has none. A deeplink is built once per room on every dashboard read,+ # inside the request's transaction, and getChat is a network round trip+ # — uncached, that is a pool slot held for it per room, per page load.+ self._chat_usernames: dict[str, str | None] = {}# Whether BotFather's privacy mode is off for this bot, read from getMe# at startup. It is a global setting and says nothing about any one# chat, so it is only half of what _chat_visibility decides.@@ -1087,9 +1092,13 @@ class TelegramAdapter(CollaborationAdapter):"""The chat's public `@name`, if it has one.Best effort: a failed lookup falls through to the id-derived link- rather than costing the caller its button."""+ rather than costing the caller its button, and is not cached — only a+ chat that answered is, so a transient failure does not stick.+ """if self._bot is None:return None+ if channel_id in self._chat_usernames:+ return self._chat_usernames[channel_id]try:chat = await self._bot.get_chat(self._chat_id(channel_id))except Exception:@@ -1100,7 +1109,9 @@ class TelegramAdapter(CollaborationAdapter):)return Noneusername = getattr(chat, "username", None)- return str(username) if username else None+ resolved = str(username) if username else None+ self._chat_usernames[channel_id] = resolved+ return resolvedasync def home_deeplink(self) -> str | None:"""`https://t.me/<bot username>` — the bot's own chat, which is thediff --git a/core/switch_core/clients/agent_client.py b/core/switch_core/clients/agent_client.pyindex 5cc0e7430..92439c734 100644--- a/core/switch_core/clients/agent_client.py+++ b/core/switch_core/clients/agent_client.py@@ -232,6 +232,15 @@ class _AddressingDecision(NamedTuple):refusal: str+class _GateOutcome(NamedTuple):+ """Whether a message that tags this agent really addresses it, plus the+ refusal to post when it does not. The refusal is returned rather than sent+ so the caller can close its database session before talking to Matrix."""++ addressed: bool+ refusal: str | None++# Shown to an agent addressed here while it holds a role in THIS room but the# session that assumed the role has hopped away to other room(s) (the lease# still routes here). `room_names` lists where that session is now active.@@ -299,7 +308,7 @@ class AgentClient(ClientBase[ClientConfig]):raise RuntimeError("Agent not loaded — call start() first")return self._agent- async def _fresh_agent(self) -> Agent:+ async def _fresh_agent(self, session: AsyncSession) -> Agent:"""Re-read the agent row and refresh the cached snapshot.`self.agent` is loaded once in `start()`. An operator can edit the@@ -307,9 +316,12 @@ class AgentClient(ClientBase[ClientConfig]):`auto_session`) via the gateway while this client runs, so any branchon `connection_model` must read fresh rather than trust the boot-timesnapshot.++ Reads through the caller's session: one inbound message asks several+ questions of this row, and each one opening a session of its own is+ several pool slots taken to answer a single event."""- async with self.session_factory() as session:- fresh = await self._agent_store.get(session, self.agent.id)+ fresh = await self._agent_store.get(session, self.agent.id)if fresh is not None:self._agent = freshreturn self.agent@@ -388,7 +400,6 @@ class AgentClient(ClientBase[ClientConfig]):meta = await self._resolve_room_meta(room.room_id)if meta is None:return- is_addressed = await self._compute_addressed(event, meta)thread_id: str | None = Nonerelates = event.source.get("content", {}).get("m.relates_to") or {}@@ -397,47 +408,54 @@ class AgentClient(ClientBase[ClientConfig]):reply_thread_root = thread_id if thread_id is not None else event.event_id- is_addressed = await self._gate_addressed(- room, event, meta, reply_thread_root, is_addressed- )-- if is_addressed:- triggered_by_auto_reply = bool(- event.source.get("content", {}).get(AUTO_REPLY_FLAG)+ # Every database read this message needs happens in one session, and+ # nothing is posted to Matrix while it is open. A busy room fans one+ # inbound event out to every agent client in it at once, so a client+ # that took a slot per question would multiply a single message into+ # dozens of concurrent checkouts.+ is_addressed = False+ refusal: str | None = None+ unavailable: str | None = None+ if self._addressed_without_lookup(event, meta) is not False:+ async with self.session_factory() as session:+ is_addressed = await self._compute_addressed(session, event, meta)+ if is_addressed:+ agent = await self._fresh_agent(session)+ gate = await self._gate_addressed(session, agent, event, meta)+ is_addressed = gate.addressed+ refusal = gate.refusal+ if (+ is_addressed+ and not self._triggered_by_auto_reply(event)+ and not await self._is_available(session, agent, meta.room_id)+ ):+ unavailable = await self._reply_when_unavailable_here(+ session, agent, meta, self._sender_handle(event)+ )++ if refusal is not None:+ await self._post_auto_reply(room.room_id, event, refusal, reply_thread_root)+ if unavailable is not None:+ await self._post_auto_reply(+ room.room_id,+ event,+ unavailable,+ # Where this lands depends on whether an answer follows it.+ #+ # "Starting a session" is a preamble: the real answer arrives+ # after it, in the room the question was asked in. Threading it+ # off the trigger buries the notice away from the answer it+ # introduces, so it goes where the question was — `thread_id`,+ # which is None for a message at the root (CHOO-2173).+ #+ # Everything else here is the whole reply and nothing follows+ # it, so it threads off the triggering message: an owner mention+ # and a paste-ready command are a wall of text to drop into a+ # channel for something only one person can act on (CHOO-2344).+ thread_id+ if unavailable == _STARTING_SESSION_MESSAGE+ else reply_thread_root,)- if not triggered_by_auto_reply and not await self._is_available(- meta.room_id- ):- handle = self._sender_handle(event)- msg = await self._reply_when_unavailable_here(meta, handle)- already_tagged = _mention_regex(handle).search(msg) is not None- body = msg if already_tagged else f"@{handle} {msg}"- await self.send_message(- room.room_id,- body,- format="markdown",- mentions=[event.sender],- # Where this lands depends on whether an answer follows it.- #- # "Starting a session" is a preamble: the real answer arrives- # after it, in the room the question was asked in. Threading- # it off the trigger buries the notice away from the answer- # it introduces, so it goes where the question was —- # `thread_id`, which is None for a message at the root- # (CHOO-2173).- #- # Everything else here is the whole reply and nothing- # follows it, so it threads off the triggering message: an- # owner mention and a paste-ready command are a wall of text- # to drop into a channel for something only one person can- # act on (CHOO-2344).- thread_root_id=(- thread_id- if msg == _STARTING_SESSION_MESSAGE- else reply_thread_root- ),- extra_content={AUTO_REPLY_FLAG: True},- )text = event.body@@ -476,7 +494,7 @@ class AgentClient(ClientBase[ClientConfig]):meta = await self._resolve_room_meta(room.room_id)if meta is None:return- is_addressed = await self._compute_addressed(event, meta)+ is_addressed = await self._addressed(event, meta)content = event.source.get("content", {})info = content.get("info", {}) or {}@@ -642,9 +660,15 @@ class AgentClient(ClientBase[ClientConfig]):body: str,) -> None:reply_thread_root = thread_id if thread_id is not None else event.event_id- is_addressed = await self._gate_addressed(- room, event, meta, reply_thread_root, is_addressed- )+ if is_addressed:+ async with self.session_factory() as session:+ agent = await self._fresh_agent(session)+ gate = await self._gate_addressed(session, agent, event, meta)+ is_addressed = gate.addressed+ if gate.refusal is not None:+ await self._post_auto_reply(+ room.room_id, event, gate.refusal, reply_thread_root+ )agent_event = AgentEvent(type="message",@@ -712,7 +736,9 @@ class AgentClient(ClientBase[ClientConfig]):),)- async def _command_targets_me_explicitly(self, args: str, room_id: str) -> bool:+ async def _command_targets_me_explicitly(+ self, session: AsyncSession, args: str, room_id: str+ ) -> bool:"""Whether the command names this agent, rather than reaching it as partof a room-wide fan-out (`!reset-all-agents`, or a bare command with no`@` token)."""@@ -720,9 +746,9 @@ class AgentClient(ClientBase[ClientConfig]):return Falseif self._args_tag_my_name(args):return True- if await self._text_tags_my_alias(args, room_id):+ if await self._text_tags_my_alias(session, args, room_id):return True- return await self._text_tags_my_role(args, room_id)+ return await self._text_tags_my_role(session, args, room_id)async def _gate_command(self, room: MatrixRoom, event: CommandEvent, meta: RoomMeta@@ -739,10 +765,17 @@ class AgentClient(ClientBase[ClientConfig]):would flood a room holding several restricted agents; those are declinedquietly, with a warning in the log."""- decision = await self._addressing_allowed(event.user_id, meta.room_id)- if decision.allowed:- return True- if await self._command_targets_me_explicitly(event.args, meta.room_id):+ async with self.session_factory() as session:+ agent = await self._fresh_agent(session)+ decision = await self._addressing_allowed(+ session, agent, event.user_id, meta.room_id+ )+ if decision.allowed:+ return True+ targets_me = await self._command_targets_me_explicitly(+ session, event.args, meta.room_id+ )+ if targets_me:await self.reply_command(room.room_id,decision.refusal,@@ -807,7 +840,7 @@ class AgentClient(ClientBase[ClientConfig]):return metaasync def _reply_when_unavailable_here(- self, meta: RoomMeta, asker_handle: str+ self, session: AsyncSession, agent: Agent, meta: RoomMeta, asker_handle: str) -> str:"""Message for an agent addressed here but not live in this room.@@ -828,7 +861,6 @@ class AgentClient(ClientBase[ClientConfig]):not live here (and no live session in a distinct room), the reply saysso and tells the operator to relaunch with live channels."""- agent = await self._fresh_agent()connection_model = (agent.integration_profile or {}).get("connection_model", "session_passive")@@ -847,48 +879,46 @@ class AgentClient(ClientBase[ClientConfig]):return _STARTING_SESSION_MESSAGEif connection_model == "auto_session":- async with self.session_factory() as session:- watching = await self._agent_session_store.get_live_agent_ids(- session, [self.agent.id], None- )+ watching = await self._agent_session_store.get_live_agent_ids(+ session, [self.agent.id], None+ )if self.agent.id in watching or self._connections.is_live(self.agent.id):return _STARTING_SESSION_MESSAGE- async with self.session_factory() as session:- room_ids = await self._agent_session_store.live_connected_rooms(- session, self.agent.id- )- # A connection covering a room is a session in it, whether or not- # anything wrote an agent_sessions row for it.- room_ids = sorted(- set(room_ids)- | {- room- for conn in self._connections.for_agent(self.agent.id)- for room in conn.rooms- }- )- bound_here = await self._agent_session_store.has_room_binding(- session, self.agent.id, meta.room_id- ) or self._connections.has_session_in(self.agent.id, meta.room_id)- names: list[str] = []- holds_role_here = False- other_room_ids = [rid for rid in room_ids if rid != meta.room_id]- if other_room_ids:- for rid in other_room_ids:- room = await self._room_store.get(session, rid)- name = room.name if room is not None else rid- if name != meta.name:- names.append(name)- holds_role_here = (- await self._room_role_store.agent_room_role(- session,- meta.room_id,- self.agent.id,- self._connections.live_agent_ids(),- )- is not None+ room_ids = await self._agent_session_store.live_connected_rooms(+ session, self.agent.id+ )+ # A connection covering a room is a session in it, whether or not+ # anything wrote an agent_sessions row for it.+ room_ids = sorted(+ set(room_ids)+ | {+ room+ for conn in self._connections.for_agent(self.agent.id)+ for room in conn.rooms+ }+ )+ bound_here = await self._agent_session_store.has_room_binding(+ session, self.agent.id, meta.room_id+ ) or self._connections.has_session_in(self.agent.id, meta.room_id)+ names: list[str] = []+ holds_role_here = False+ other_room_ids = [rid for rid in room_ids if rid != meta.room_id]+ if other_room_ids:+ for rid in other_room_ids:+ room = await self._room_store.get(session, rid)+ name = room.name if room is not None else rid+ if name != meta.name:+ names.append(name)+ holds_role_here = (+ await self._room_role_store.agent_room_role(+ session,+ meta.room_id,+ self.agent.id,+ self._connections.live_agent_ids(),)+ is not None+ )if names:if holds_role_here:@@ -897,7 +927,7 @@ class AgentClient(ClientBase[ClientConfig]):# known-agent reply so the operator gets the paste-ready# connect command alongside the "ask me there" alternative.return await self._unavailable_reply(- meta, agent, asker_handle, other_room_names=names+ session, meta, agent, asker_handle, other_room_names=names)# No live session in a distinct room. A session_addressable agent bound@@ -906,11 +936,13 @@ class AgentClient(ClientBase[ClientConfig]):# there is none.if connection_model == "session_addressable" and bound_here:return await self._unavailable_reply(- meta, agent, asker_handle, connected_not_live=True+ session, meta, agent, asker_handle, connected_not_live=True)- return await self._unavailable_reply(meta, agent, asker_handle)+ return await self._unavailable_reply(session, meta, agent, asker_handle)- async def owner_handle_in(self, agent: Agent, bridge_id: str | None) -> str | None:+ async def owner_handle_in(+ self, session: AsyncSession, agent: Agent, bridge_id: str | None+ ) -> str | None:"""The agent owner's account on the platform this room is bridged to,for @-mentioning them (CHOO-2137).@@ -926,10 +958,7 @@ class AgentClient(ClientBase[ClientConfig]):"""if agent.owner_id is None or bridge_id is None:return None- async with self.session_factory() as session:- claimed = await self._external_user_store.get_by_user(- session, agent.owner_id- )+ claimed = await self._external_user_store.get_by_user(session, agent.owner_id)# Claiming is not exclusive and one person may hold several accounts on# a bridge. Sorted so a second account cannot change who gets mentioned# between one message and the next.@@ -938,6 +967,7 @@ class AgentClient(ClientBase[ClientConfig]):async def _unavailable_reply(self,+ session: AsyncSession,meta: RoomMeta,agent: Agent,asker_handle: str,@@ -978,7 +1008,7 @@ class AgentClient(ClientBase[ClientConfig]):else None)return _offline_owner_message(- await self.owner_handle_in(agent, meta.bridge_id),+ await self.owner_handle_in(session, agent, meta.bridge_id),asker_handle,cmd,)@@ -988,7 +1018,7 @@ class AgentClient(ClientBase[ClientConfig]):options,agent,meta.name,- await self.owner_handle_in(agent, meta.bridge_id),+ await self.owner_handle_in(session, agent, meta.bridge_id),other_room_names=other_room_names,connected_not_live=connected_not_live,)@@ -1000,14 +1030,15 @@ class AgentClient(ClientBase[ClientConfig]):connection_model, _UNAVAILABLE_MESSAGES["session_passive"])- async def _is_available(self, room_id: str) -> bool:+ async def _is_available(+ self, session: AsyncSession, agent: Agent, room_id: str+ ) -> bool:"""Return True if this agent has a live session for `room_id`.always_on agents heartbeat against `room_id=None`; session_addressableagents heartbeat against the specific room; session_passive agentshave no heartbeat and are never considered live in real time."""- agent = await self._fresh_agent()connection_model = (agent.integration_profile or {}).get("connection_model", "session_passive")@@ -1025,10 +1056,9 @@ class AgentClient(ClientBase[ClientConfig]):return Trueheartbeat_room = None if connection_model == "always_on" else room_id- async with self.session_factory() as session:- live = await self._agent_session_store.get_live_agent_ids(- session, [self.agent.id], heartbeat_room- )+ live = await self._agent_session_store.get_live_agent_ids(+ session, [self.agent.id], heartbeat_room+ )return self.agent.id in liveasync def _is_direct_room(self, matrix_room_id: str) -> bool:@@ -1201,7 +1231,37 @@ class AgentClient(ClientBase[ClientConfig]):# ── Mention detection ─────────────────────────────────────────────────────- async def _compute_addressed(self, event: RoomMessage, meta: RoomMeta) -> bool:+ def _addressed_without_lookup(+ self, event: RoomMessage, meta: RoomMeta+ ) -> bool | None:+ """The addressing answer that needs no database read, or None when the+ room's aliases and role leases have to be consulted.++ Callers use it to decide whether to take a pool slot at all: most room+ chatter carries no `@` and is answered here, and a room fans every+ message out to all of its agent clients at once.+ """+ if ADMIN_MARKER in (event.source.get("content") or {}):+ return False+ if meta.channel_type == "direct":+ return True+ if self._is_mentioned(event):+ return True+ if "@" not in (getattr(event, "body", "") or ""):+ return False+ return None++ async def _addressed(self, event: RoomMessage, meta: RoomMeta) -> bool:+ """`_compute_addressed`, in a session of its own when it needs one."""+ decided = self._addressed_without_lookup(event, meta)+ if decided is not None:+ return decided+ async with self.session_factory() as session:+ return await self._compute_addressed(session, event, meta)++ async def _compute_addressed(+ self, session: AsyncSession, event: RoomMessage, meta: RoomMeta+ ) -> bool:"""Whether this message addresses this agent (expects a response).Direct rooms always address. Otherwise the agent is addressed by an@@ -1218,15 +1278,12 @@ class AgentClient(ClientBase[ClientConfig]):which tagged every one of them. The marker exists to say "generated bySwitch"; this is it being honoured."""- if ADMIN_MARKER in (event.source.get("content") or {}):- return False- if meta.channel_type == "direct":- return True- if self._is_mentioned(event):+ decided = self._addressed_without_lookup(event, meta)+ if decided is not None:+ return decided+ if await self._is_mentioned_via_alias(session, event, meta.room_id):return True- if await self._is_mentioned_via_alias(event, meta.room_id):- return True- return await self._is_mentioned_via_role(event, meta.room_id)+ return await self._is_mentioned_via_role(session, event, meta.room_id)async def _resolve_sender_principal(self, session: AsyncSession, matrix_user_id: str@@ -1261,7 +1318,7 @@ class AgentClient(ClientBase[ClientConfig]):return Noneasync def _addressing_allowed(- self, matrix_sender: str, room_id: str+ self, session: AsyncSession, agent: Agent, matrix_sender: str, room_id: str) -> _AddressingDecision:"""Whether `matrix_sender` may address this agent in `room_id`, per theagent's scoped addressing policy.@@ -1272,13 +1329,11 @@ class AgentClient(ClientBase[ClientConfig]):wording to send back, which differs when the sender looks like someonewhose platform identity simply has not been claimed yet."""- agent = await self._fresh_agent()policy = parse_policy(agent.addressing_policy)if policy.is_open():return _AddressingDecision(allowed=True, refusal="")- async with self.session_factory() as session:- principal = await self._resolve_sender_principal(session, matrix_sender)- room = await self._room_store.get(session, room_id)+ principal = await self._resolve_sender_principal(session, matrix_sender)+ room = await self._room_store.get(session, room_id)if principal is None:logger.warning("Addressing denied for %s: unresolvable sender %s in room %s",@@ -1340,50 +1395,60 @@ class AgentClient(ClientBase[ClientConfig]):async def _gate_addressed(self,- room: MatrixRoom,+ session: AsyncSession,+ agent: Agent,event: RoomMessage,meta: RoomMeta,- reply_thread_root: str,- is_addressed: bool,- ) -> bool:- """Apply the scoped addressing policy to a would-be-addressed message.-- When the message tags this agent but the sender is not permitted by the- agent's policy, demote it to unaddressed room chatter and (once, guarded- by AUTO_REPLY_FLAG so two agents can't ping-pong) reply to the sender- explaining they can't address it here. Returns the effective addressed- flag. Zero cost for the common case: only messages that already tag this- agent are ever checked, and open policies short-circuit.+ ) -> _GateOutcome:+ """Apply the scoped addressing policy to a message that tags this agent.++ When the sender is not permitted by the agent's policy, the message is+ demoted to unaddressed room chatter and the caller is handed a refusal+ to post (once, guarded by AUTO_REPLY_FLAG so two agents can't+ ping-pong). Zero cost for the common case: only messages that already+ tag this agent are ever checked, and open policies short-circuit."""- if not is_addressed:- return False- decision = await self._addressing_allowed(event.sender, meta.room_id)+ decision = await self._addressing_allowed(+ session, agent, event.sender, meta.room_id+ )if decision.allowed:- return True- triggered_by_auto_reply = bool(- event.source.get("content", {}).get(AUTO_REPLY_FLAG)+ return _GateOutcome(addressed=True, refusal=None)+ if self._triggered_by_auto_reply(event):+ return _GateOutcome(addressed=False, refusal=None)+ return _GateOutcome(addressed=False, refusal=decision.refusal)++ @staticmethod+ def _triggered_by_auto_reply(event: RoomMessage) -> bool:+ return bool(event.source.get("content", {}).get(AUTO_REPLY_FLAG))++ async def _post_auto_reply(+ self,+ matrix_room_id: str,+ event: RoomMessage,+ msg: str,+ thread_root_id: str | None,+ ) -> None:+ """Post a reply addressed at the sender and flagged as an auto-reply, so+ another offline agent it tags does not answer it in turn."""+ handle = self._sender_handle(event)+ already_tagged = _mention_regex(handle).search(msg) is not None+ await self.send_message(+ matrix_room_id,+ msg if already_tagged else f"@{handle} {msg}",+ format="markdown",+ mentions=[event.sender],+ thread_root_id=thread_root_id,+ extra_content={AUTO_REPLY_FLAG: True},)- if not triggered_by_auto_reply:- handle = self._sender_handle(event)- msg = decision.refusal- already_tagged = _mention_regex(handle).search(msg) is not None- body = msg if already_tagged else f"@{handle} {msg}"- await self.send_message(- room.room_id,- body,- format="markdown",- mentions=[event.sender],- thread_root_id=reply_thread_root,- extra_content={AUTO_REPLY_FLAG: True},- )- return Falsedef _args_tag_my_name(self, text: str) -> bool:"""True when `text` contains our own `@name` at a full-token boundary(so a name that is a prefix of a longer one is not falsely matched)."""return _mention_regex(self.agent.name).search(_strip_emphasis(text)) is not None- async def _text_tags_my_alias(self, text: str, room_id: str) -> bool:+ async def _text_tags_my_alias(+ self, session: AsyncSession, text: str, room_id: str+ ) -> bool:"""True when `text` `@`-tags this agent's room alias at a token boundary.The alias is looked up live (like a role lease) so a change takes effect@@ -1391,21 +1456,26 @@ class AgentClient(ClientBase[ClientConfig]):"""if "@" not in text:return False- async with self.session_factory() as session:- alias = await self._room_store.get_alias(session, room_id, self.agent.id)+ alias = await self._room_store.get_alias(session, room_id, self.agent.id)if not alias:return Falsereturn _mention_regex(alias).search(text) is not None- async def _is_mentioned_via_alias(self, event: RoomMessage, room_id: str) -> bool:+ async def _is_mentioned_via_alias(+ self, session: AsyncSession, event: RoomMessage, room_id: str+ ) -> bool:"""True when the message body tags this agent's room alias.A room alias addresses the agent exactly like its real name, so an`@<alias>` mention routes here just as `@<name>` does."""- return await self._text_tags_my_alias(getattr(event, "body", "") or "", room_id)+ return await self._text_tags_my_alias(+ session, getattr(event, "body", "") or "", room_id+ )- async def _text_tags_my_role(self, text: str, room_id: str) -> bool:+ async def _text_tags_my_role(+ self, session: AsyncSession, text: str, room_id: str+ ) -> bool:"""True when `text` `@`-tags a room-role this agent LIVE-holds.Only a live lease counts, so "held" means the same thing here as in@@ -1417,22 +1487,25 @@ class AgentClient(ClientBase[ClientConfig]):"""if "@" not in text:return False- async with self.session_factory() as session:- role_name = await self._room_role_store.agent_room_role(- session, room_id, self.agent.id, self._connections.live_agent_ids()- )+ role_name = await self._room_role_store.agent_room_role(+ session, room_id, self.agent.id, self._connections.live_agent_ids()+ )if not role_name:return Falsereturn _mention_regex(role_name).search(_strip_emphasis(text)) is not None- async def _is_mentioned_via_role(self, event: RoomMessage, room_id: str) -> bool:+ async def _is_mentioned_via_role(+ self, session: AsyncSession, event: RoomMessage, room_id: str+ ) -> bool:"""True when the message body tags a room-role this agent holds.Tagging `@<role>` addresses whichever agent holds that role, so aninterchangeable agent can be reached by responsibility rather than byname."""- return await self._text_tags_my_role(getattr(event, "body", "") or "", room_id)+ return await self._text_tags_my_role(+ session, getattr(event, "body", "") or "", room_id+ )def _sender_handle(self, event: RoomMessage) -> str:"""The @-handle to tag the message sender with.diff --git a/core/switch_core/db/stores/room_store.py b/core/switch_core/db/stores/room_store.pyindex 789d84253..a0b45854b 100644--- a/core/switch_core/db/stores/room_store.py+++ b/core/switch_core/db/stores/room_store.py@@ -4,7 +4,14 @@ from sqlalchemy import delete, insert, or_, select, updatefrom sqlalchemy import func as sa_funcfrom sqlalchemy.ext.asyncio import AsyncSession-from switch_core.db.models import ClientRoom, Room, RoomGroup, room_agents+from switch_core.db.models import (+ Agent,+ Client,+ ClientRoom,+ Room,+ RoomGroup,+ room_agents,+)class RoomStore:@@ -296,6 +303,23 @@ class RoomStore:)return list(result.scalars().all())+ async def get_member_agent_clients(+ self, session: AsyncSession, room_id: str+ ) -> dict[str, str]:+ """`{client_id: matrix_user_id}` for the agents this room has as members.++ Resolved from the database rather than from the running client+ registry, so it answers correctly before the agent clients have+ finished booting.+ """+ result = await session.execute(+ select(Client.id, Client.matrix_user_id)+ .join(Agent, Agent.client_id == Client.id)+ .join(room_agents, room_agents.c.agent_id == Agent.id)+ .where(room_agents.c.room_id == room_id)+ )+ return {client_id: matrix_user_id for client_id, matrix_user_id in result.all()}+async def get_by_bridge(self, session: AsyncSession, bridge_id: str) -> list[Room]:result = await session.execute(select(Room).where(Room.bridge_id == bridge_id))return list(result.scalars().all())diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex 78beffb6c..5da5e89a7 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -429,9 +429,10 @@ async def run() -> None:await client_lifecycle.start_all()await collab_lifecycle.start_all()- # Backfill system clients (e.g. the admin client) into rooms created before- # they existed; the just-started clients auto-accept the invites.- await room_service.reconcile_system_clients()+ # Backfill room membership: system clients (e.g. the admin client) added+ # after a room was created, and any agent whose invite did not land. The+ # just-started clients accept the invites on their first sync.+ await room_service.reconcile_room_clients()logger.info("Switch is running on http://%s:%d", config.server_host, config.server_portdiff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.pyindex a53e8dd99..770c15e7f 100644--- a/core/switch_core/room_service.py+++ b/core/switch_core/room_service.py@@ -1,3 +1,18 @@+"""Room lifecycle: provisioning, membership, and bridge binding.++Matrix calls here run with no database session open, so a slow invite or kick+cannot hold a connection-pool slot while it waits. That splits atomicity, and+the split has a deliberate direction: **Matrix membership must never exceed+what the database records.** Write the membership row before inviting; revoke+the Matrix membership before dropping the row. A crash in the window then+leaves an agent Switch believes is a member but which cannot see the room —+under-privileged, visible, and repairable — rather than one silently reading a+room Switch has no record of it being in.++`reconcile_room_clients` closes that window at startup: a member with no+`room_clients` row is (re-)invited, invites being idempotent.+"""+from __future__ import annotationsimport logging@@ -634,15 +649,16 @@ class RoomService:client_ids = await self._room_store.get_client_ids(session, room_id)- for client_id in client_ids:- client = self._client_lifecycle.get(client_id)- if client:- await self._matrix_admin.kick_user(- room.matrix_room_id, client.matrix_user_id- )+ for client_id in client_ids:+ client = self._client_lifecycle.get(client_id)+ if client:+ await self._matrix_admin.kick_user(+ room.matrix_room_id, client.matrix_user_id+ )- await self._matrix_admin.delete_room(room.matrix_room_id)+ await self._matrix_admin.delete_room(room.matrix_room_id)+ async with self._session_factory() as session:await self._room_store.delete(session, room_id)await session.commit()@@ -693,29 +709,33 @@ class RoomService:raise ValueError(f"Room not found: {room_id}")existing = await self._room_store.get_agent_ids(session, room.id)- new_agent_ids = [aid for aid in agent_ids if aid not in existing]- if not new_agent_ids:- logger.debug(- "All agents are already part of the room, existing %s, new agent ids %s, agent ids %s",- existing,- new_agent_ids,- agent_ids,- )- return- agent_clients = self._resolve_agent_clients(new_agent_ids)+ new_agent_ids = [aid for aid in agent_ids if aid not in existing]+ if not new_agent_ids:+ logger.debug(+ "All agents are already part of the room, existing %s, new agent ids %s, agent ids %s",+ existing,+ new_agent_ids,+ agent_ids,+ )+ return- await self._invite_clients(room.matrix_room_id, agent_clients)+ agent_clients = self._resolve_agent_clients(new_agent_ids)+ async with self._session_factory() as session:await self._room_store.add_agents(session,room.id,new_agent_ids,join_event_listeners={aid for aid in new_agent_ids if aid in listeners},)+ await session.commit()++ await self._invite_clients(room.matrix_room_id, agent_clients)++ async with self._session_factory() as session:for client_id in agent_clients:await self._room_store.add_client(session, client_id, room.id)-await session.commit()if room.bridge_id and room.external_channel_id:@@ -734,12 +754,14 @@ class RoomService:if room is None:raise ValueError(f"Room not found: {room_id}")- agent_clients = self._resolve_agent_clients(agent_ids)+ agent_clients = self._resolve_agent_clients(agent_ids)- for client_id, matrix_user_id in agent_clients.items():- await self._matrix_admin.kick_user(room.matrix_room_id, matrix_user_id)- await self._room_store.remove_client(session, client_id, room_id)+ for matrix_user_id in agent_clients.values():+ await self._matrix_admin.kick_user(room.matrix_room_id, matrix_user_id)+ async with self._session_factory() as session:+ for client_id in agent_clients:+ await self._room_store.remove_client(session, client_id, room_id)await self._room_store.remove_agents(session, room_id, agent_ids)await session.commit()@@ -1076,26 +1098,33 @@ class RoomService:for matrix_user_id in client_ids.values():await self._matrix_admin.invite_to_room(matrix_room_id, matrix_user_id)- async def reconcile_system_clients(self) -> None:- """Ensure every running system client is a member of every room.-- Rooms created before a system-client type existed (e.g. the admin- client) have no membership for it. Run once at startup, after the- clients are running so they auto-accept the invites. Idempotent:- `invite_to_room` is a no-op for an already-joined user, and DB- membership is only recorded where it is missing.+ async def reconcile_room_clients(self) -> None:+ """Ensure every room's clients are actually in it, on Matrix.++ Two sources of drift. Rooms created before a system-client type existed+ (e.g. the admin client) have no membership for it. And a membership+ change writes the `room_agents` row, invites, then records+ `room_clients` — so a crash in that window leaves a member the invite+ may never have reached, with the absent `room_clients` row as the+ marker.++ Run once at startup. The clients are starting concurrently, so agent+ clients are resolved from the database rather than from the running+ registry; a pending invite is accepted on the client's first sync.+ Idempotent: `invite_to_room` is a no-op for an already-joined user, and+ DB membership is only recorded where it is missing."""system_clients = self._resolve_system_clients()- if not system_clients:- returnasync with self._session_factory() as session:rooms = await self._room_store.get_all(session, include_archived=True)for room in rooms:async with self._session_factory() as session:existing = set(await self._room_store.get_client_ids(session, room.id))- missing = {- cid: uid for cid, uid in system_clients.items() if cid not in existing- }+ expected = await self._room_store.get_member_agent_clients(+ session, room.id+ )+ expected.update(system_clients)+ missing = {cid: uid for cid, uid in expected.items() if cid not in existing}if not missing:continueawait self._invite_clients(room.matrix_room_id, missing)@@ -1103,9 +1132,7 @@ class RoomService:for client_id in missing:await self._room_store.add_client(session, client_id, room.id)await session.commit()- logger.info(- "Reconciled %d system client(s) into room %s", len(missing), room.id- )+ logger.info("Reconciled %d client(s) into room %s", len(missing), room.id)async def ensure_client_in_room(self, room_id: str, client_id: str) -> None:"""Invite a single running client to the room (it auto-joins) and recorddiff --git a/core/tests/switch_core/bridges/agent/test_commands_run_cmd.py b/core/tests/switch_core/bridges/agent/test_commands_run_cmd.pyindex 5822460ee..a7a1cfb00 100644--- a/core/tests/switch_core/bridges/agent/test_commands_run_cmd.py+++ b/core/tests/switch_core/bridges/agent/test_commands_run_cmd.py@@ -16,6 +16,11 @@ from switch_core.bridges.agent.commands import (from switch_core.events import CommandEvent+@asynccontextmanager+async def _session_factory(): # type: ignore[no-untyped-def]+ yield object()++class TestRoleArg:"""The role to name in the output is the SECOND @token; the first targetsthe agent (see _addressed_by_first_mention)."""@@ -44,14 +49,15 @@ def _addr_client(name: str, held_role: str | None = None) -> SimpleNamespace:def _args_tag_my_name(text: str) -> bool:return _tag(name, text)- async def _text_tags_my_role(text: str, _room_id: str) -> bool:+ async def _text_tags_my_role(_session: Any, text: str, _room_id: str) -> bool:return held_role is not None and _tag(held_role, text)- async def _text_tags_my_alias(_text: str, _room_id: str) -> bool:+ async def _text_tags_my_alias(_session: Any, _text: str, _room_id: str) -> bool:return Falsereturn SimpleNamespace(agent=SimpleNamespace(name=name),+ session_factory=_session_factory,_args_tag_my_name=_args_tag_my_name,_text_tags_my_role=_text_tags_my_role,_text_tags_my_alias=_text_tags_my_alias,@@ -186,10 +192,6 @@ def _event(args: str) -> CommandEvent:def _fake_client(*, role_exists: bool) -> SimpleNamespace:sent: list[str] = []- @asynccontextmanager- async def _session_factory(): # type: ignore[no-untyped-def]- yield object()-async def _resolve_room_meta(_matrix_room_id: str): # type: ignore[no-untyped-def]return SimpleNamespace(room_id="room-1", name="Feature Room", bridge_id=None)@@ -202,7 +204,7 @@ def _fake_client(*, role_exists: bool) -> SimpleNamespace:async def _send_message(_room_id, body, **_kw): # type: ignore[no-untyped-def]sent.append(body)- async def _owner_handle_in(_agent, _bridge_id): # type: ignore[no-untyped-def]+ async def _owner_handle_in(_session, _agent, _bridge_id): # type: ignore[no-untyped-def]# No linked owner: these cover the connect command, not the mention.return Nonediff --git a/core/tests/switch_core/bridges/agent/test_control_commands.py b/core/tests/switch_core/bridges/agent/test_control_commands.pyindex d57ea48dc..0822136d8 100644--- a/core/tests/switch_core/bridges/agent/test_control_commands.py+++ b/core/tests/switch_core/bridges/agent/test_control_commands.py@@ -46,7 +46,7 @@ def _client(integration_profile={"command_capabilities": {"reset": command_level}},)- async def _fresh_agent() -> SimpleNamespace:+ async def _fresh_agent(_session: Any) -> SimpleNamespace:return agentasync def _resolve_room_meta(_matrix_room_id: str) -> SimpleNamespace:diff --git a/core/tests/switch_core/bridges/collaboration/test_telegram_provisioning.py b/core/tests/switch_core/bridges/collaboration/test_telegram_provisioning.pyindex b9f0cb69f..9937fddf3 100644--- a/core/tests/switch_core/bridges/collaboration/test_telegram_provisioning.py+++ b/core/tests/switch_core/bridges/collaboration/test_telegram_provisioning.py@@ -43,8 +43,10 @@ class _FakeChat:class _FakeBot:def __init__(self, chat: _FakeChat) -> None:self._chat = chat+ self.get_chat_calls = 0async def get_chat(self, chat_id: Any) -> _FakeChat:+ self.get_chat_calls += 1return self._chat@@ -172,6 +174,50 @@ def test_a_public_chat_uses_its_real_address() -> None:assert _run(adapter.channel_deeplink(SUPERGROUP_ID)) == "https://t.me/acme_public"+def test_a_resolved_chat_is_only_looked_up_once() -> None:+ # A deeplink is built per room on every dashboard read, inside the+ # request's transaction. Uncached, a getChat round trip per room is a pool+ # slot held for the network, per room, per page load.+ adapter = _adapter(_FakeChat("supergroup", username="acme_public"))++ for _ in range(3):+ assert (+ _run(adapter.channel_deeplink(SUPERGROUP_ID)) == "https://t.me/acme_public"+ )++ assert adapter._bot.get_chat_calls == 1 # type: ignore[union-attr]+++def test_a_chat_with_no_username_is_not_looked_up_again_either() -> None:+ adapter = _adapter(_FakeChat("supergroup"))++ for _ in range(3):+ assert (+ _run(adapter.channel_deeplink(SUPERGROUP_ID))+ == "https://t.me/c/1234567890/1"+ )++ assert adapter._bot.get_chat_calls == 1 # type: ignore[union-attr]+++def test_a_failed_lookup_is_not_cached() -> None:+ # A transient outage must not cost the chat its real address for the life+ # of the process.+ adapter = _adapter(_FakeChat("supergroup", username="acme_public"))+ working = adapter._bot.get_chat # type: ignore[union-attr]++ async def _fail(_chat_id: Any) -> _FakeChat:+ raise RuntimeError("telegram unreachable")++ adapter._bot.get_chat = _fail # type: ignore[union-attr]+ assert (+ _run(adapter.channel_deeplink(SUPERGROUP_ID)) == "https://t.me/c/1234567890/1"+ )++ adapter._bot.get_chat = working # type: ignore[union-attr]+ assert _run(adapter.channel_deeplink(SUPERGROUP_ID)) == "https://t.me/acme_public"++def test_a_failed_lookup_still_yields_the_internal_link() -> None:# Losing the button because one API call failed is worse than the link the# chat id alone can produce.diff --git a/core/tests/switch_core/clients/test_addressing_enforcement.py b/core/tests/switch_core/clients/test_addressing_enforcement.pyindex 0e07d4f58..c7e6081d6 100644--- a/core/tests/switch_core/clients/test_addressing_enforcement.py+++ b/core/tests/switch_core/clients/test_addressing_enforcement.py@@ -145,9 +145,6 @@ def _allowed_client(agent = SimpleNamespace(name="fixer", addressing_policy=policy, owner_id=owner_id)- async def _fresh_agent(): # type: ignore[no-untyped-def]- return agent-async def _resolve(_session, _mxid): # type: ignore[no-untyped-def]if principal is None:return None@@ -159,7 +156,6 @@ def _allowed_client(return SimpleNamespace(agent=agent,- _fresh_agent=_fresh_agent,session_factory=_session_factory,_resolve_sender_principal=_resolve,_room_store=SimpleNamespace(get=_get_room),@@ -167,7 +163,9 @@ def _allowed_client(async def _decide(client: SimpleNamespace, room_id: str = "room-1"): # type: ignore[no-untyped-def]- return await AgentClient._addressing_allowed(client, "@u:switch.local", room_id)+ return await AgentClient._addressing_allowed(+ client, None, client.agent, "@u:switch.local", room_id+ )class TestAddressingAllowed:@@ -363,10 +361,10 @@ class TestOwnerAgentsAddressing:def _gate_client(*, allowed: bool, refusal: str = _ADDRESSING_DENIED_MESSAGE): # type: ignore[no-untyped-def]- """Fake client for _gate_addressed: records any auto-reply sent."""+ """Fake client for _gate_addressed and the auto-reply it hands back."""sent: list[dict] = []- async def _addressing_allowed(_matrix_sender, _room_id): # type: ignore[no-untyped-def]+ async def _addressing_allowed(_session, _agent, _matrix_sender, _room_id): # type: ignore[no-untyped-def]return _AddressingDecision(allowed=allowed, refusal="" if allowed else refusal)async def _send_message(room_id, body, **kwargs): # type: ignore[no-untyped-def]@@ -376,10 +374,13 @@ def _gate_client(*, allowed: bool, refusal: str = _ADDRESSING_DENIED_MESSAGE):return "human"client = SimpleNamespace(+ agent=SimpleNamespace(name="fixer"),_addressing_allowed=_addressing_allowed,send_message=_send_message,_sender_handle=_sender_handle,+ _triggered_by_auto_reply=AgentClient._triggered_by_auto_reply,)+ client._post_auto_reply = AgentClient._post_auto_reply.__get__(client)client.sent = sent # type: ignore[attr-defined]return client@@ -388,29 +389,32 @@ def _room() -> SimpleNamespace:return SimpleNamespace(room_id="!matrix:switch.local")-class TestGateAddressed:- async def test_not_addressed_short_circuits(self) -> None:- client = _gate_client(allowed=False)- result = await AgentClient._gate_addressed(- client, _room(), _event(), _meta(), "$root", False+async def _gate(client: SimpleNamespace, event: SimpleNamespace): # type: ignore[no-untyped-def]+ """Run the gate and post whatever refusal it hands back, the way on_message+ does — the gate itself never touches Matrix, so that its caller can close+ the database session first."""+ outcome = await AgentClient._gate_addressed(+ client, None, client.agent, event, _meta()+ )+ if outcome.refusal is not None:+ await client._post_auto_reply(+ "!matrix:switch.local", event, outcome.refusal, "$root")- assert result is False- assert client.sent == [] # no reply for an untagged message+ return outcome++class TestGateAddressed:async def test_allowed_stays_addressed(self) -> None:client = _gate_client(allowed=True)- result = await AgentClient._gate_addressed(- client, _room(), _event(), _meta(), "$root", True- )- assert result is True+ outcome = await _gate(client, _event())+ assert outcome.addressed is True+ assert outcome.refusal is Noneassert client.sent == []async def test_denied_demotes_and_replies(self) -> None:client = _gate_client(allowed=False)- result = await AgentClient._gate_addressed(- client, _room(), _event(), _meta(), "$root", True- )- assert result is False+ outcome = await _gate(client, _event())+ assert outcome.addressed is Falseassert len(client.sent) == 1reply = client.sent[0]assert _ADDRESSING_DENIED_MESSAGE in reply["body"]@@ -422,21 +426,29 @@ class TestGateAddressed:async def test_denied_auto_reply_does_not_ping_pong(self) -> None:# If the tagging message was itself an auto-reply, do not reply again.client = _gate_client(allowed=False)- result = await AgentClient._gate_addressed(- client, _room(), _event(auto_reply=True), _meta(), "$root", True- )- assert result is False+ outcome = await _gate(client, _event(auto_reply=True))+ assert outcome.addressed is False+ assert outcome.refusal is Noneassert client.sent == []async def test_reply_carries_the_decision_wording(self) -> None:# The refusal the decision chose is what the sender sees, not a# re-derived generic one.client = _gate_client(allowed=False, refusal=_ADDRESSING_UNCLAIMED_MESSAGE)- await AgentClient._gate_addressed(- client, _room(), _event(), _meta(), "$root", True- )+ await _gate(client, _event())assert _ADDRESSING_UNCLAIMED_MESSAGE in client.sent[0]["body"]+ async def test_nothing_is_posted_from_inside_the_gate(self) -> None:+ # The point of returning the refusal: the caller holds a database+ # session while the gate runs and must close it before talking to+ # Matrix.+ client = _gate_client(allowed=False)+ outcome = await AgentClient._gate_addressed(+ client, None, client.agent, _event(), _meta()+ )+ assert outcome.refusal == _ADDRESSING_DENIED_MESSAGE+ assert client.sent == []+def _command(args: str = "", user_id: str = "@u:switch.local", command: str = "reset"@@ -450,19 +462,26 @@ def _command_client(*, allowed: bool, targets_me: bool): # type: ignore[no-unty"""Fake client for _gate_command: records any command reply posted."""replies: list[dict] = []- async def _addressing_allowed(_matrix_sender, _room_id): # type: ignore[no-untyped-def]+ async def _addressing_allowed(_session, _agent, _matrix_sender, _room_id): # type: ignore[no-untyped-def]return _AddressingDecision(allowed=allowed, refusal="" if allowed else _ADDRESSING_DENIED_MESSAGE)- async def _targets_me(_args, _room_id): # type: ignore[no-untyped-def]+ async def _targets_me(_session, _args, _room_id): # type: ignore[no-untyped-def]return targets_measync def _reply_command(room_id, body, **kwargs): # type: ignore[no-untyped-def]replies.append({"room_id": room_id, "body": body, **kwargs})+ agent = SimpleNamespace(name="fixer")++ async def _fresh_agent(_session): # type: ignore[no-untyped-def]+ return agent+client = SimpleNamespace(- agent=SimpleNamespace(name="fixer"),+ agent=agent,+ session_factory=_session_factory,+ _fresh_agent=_fresh_agent,_addressing_allowed=_addressing_allowed,_command_targets_me_explicitly=_targets_me,reply_command=_reply_command,@@ -511,10 +530,10 @@ class TestCommandTargetsMeExplicitly:counts as explicit targeting."""def _client(self, *, name: str = "fixer", alias: bool = False, role: bool = False): # type: ignore[no-untyped-def]- async def _tags_alias(_text, _room_id): # type: ignore[no-untyped-def]+ async def _tags_alias(_session, _text, _room_id): # type: ignore[no-untyped-def]return alias- async def _tags_role(_text, _room_id): # type: ignore[no-untyped-def]+ async def _tags_role(_session, _text, _room_id): # type: ignore[no-untyped-def]return roleclient = SimpleNamespace(@@ -530,14 +549,16 @@ class TestCommandTargetsMeExplicitly:async def test_no_at_token_is_not_explicit(self) -> None:client = self._client()assert (- await AgentClient._command_targets_me_explicitly(client, "", "room-1")+ await AgentClient._command_targets_me_explicitly(client, None, "", "room-1")is False)async def test_own_name_is_explicit(self) -> None:client = self._client()assert (- await AgentClient._command_targets_me_explicitly(client, "@fixer", "room-1")+ await AgentClient._command_targets_me_explicitly(+ client, None, "@fixer", "room-1"+ )is True)@@ -545,7 +566,7 @@ class TestCommandTargetsMeExplicitly:client = self._client()assert (await AgentClient._command_targets_me_explicitly(- client, "@someone-else", "room-1"+ client, None, "@someone-else", "room-1")is False)@@ -554,7 +575,7 @@ class TestCommandTargetsMeExplicitly:client = self._client(alias=True)assert (await AgentClient._command_targets_me_explicitly(- client, "@nickname", "room-1"+ client, None, "@nickname", "room-1")is True)@@ -563,7 +584,7 @@ class TestCommandTargetsMeExplicitly:client = self._client(role=True)assert (await AgentClient._command_targets_me_explicitly(- client, "@manager", "room-1"+ client, None, "@manager", "room-1")is True)diff --git a/core/tests/switch_core/clients/test_agent_client_attachment_groups.py b/core/tests/switch_core/clients/test_agent_client_attachment_groups.pyindex 9ba4570b9..4ef41d558 100644--- a/core/tests/switch_core/clients/test_agent_client_attachment_groups.py+++ b/core/tests/switch_core/clients/test_agent_client_attachment_groups.py@@ -1,13 +1,14 @@from __future__ import annotationsimport asyncio+from contextlib import asynccontextmanagerfrom types import SimpleNamespacefrom typing import Anyimport nioimport switch_core.clients.agent_client as ac-from switch_core.clients.agent_client import AgentClient+from switch_core.clients.agent_client import AgentClient, _GateOutcomefrom switch_core.clients.room_meta import RoomMeta@@ -43,6 +44,11 @@ def _media_event()+@asynccontextmanager+async def _session_factory(): # type: ignore[no-untyped-def]+ yield object()++class _FakeQueue:def __init__(self) -> None:self.events: list[Any] = []@@ -58,25 +64,30 @@ def _fake_client() -> SimpleNamespace:async def _resolve_room_meta(_matrix_room_id: str) -> RoomMeta:return meta- async def _compute_addressed(event: Any, _meta: RoomMeta) -> bool:+ async def _addressed(event: Any, _meta: RoomMeta) -> bool:# Mirrors production, where addressing is read off the message text.# Standing in a constant `True` here is what let the coalescing bug# through: every part looked addressed, including the caption-less ones# that in reality address nobody.return f"@{ns.agent.name}" in getattr(event, "body", "")+ async def _fresh_agent(_session: Any) -> Any:+ return ns.agent+async def _gate_addressed(- _room: Any, _event: Any, _meta: Any, _root: Any, is_addressed: bool- ) -> bool:- return is_addressed+ _session: Any, _agent: Any, _event: Any, _meta: Any+ ) -> _GateOutcome:+ return _GateOutcome(addressed=True, refusal=None)ns = SimpleNamespace(agent=SimpleNamespace(id="agent-1", name="agent-a"),+ session_factory=_session_factory,_event_buffer=queue,_attachment_groups={},_attachment_group_timers={},_resolve_room_meta=_resolve_room_meta,- _compute_addressed=_compute_addressed,+ _addressed=_addressed,+ _fresh_agent=_fresh_agent,_gate_addressed=_gate_addressed,queue=queue,)diff --git a/core/tests/switch_core/clients/test_agent_client_pool_checkouts.py b/core/tests/switch_core/clients/test_agent_client_pool_checkouts.pynew file mode 100644index 000000000..b8cee49ae--- /dev/null+++ b/core/tests/switch_core/clients/test_agent_client_pool_checkouts.py@@ -0,0 +1,273 @@+"""How many pool checkouts one inbound room message costs an agent client.++A room fans every Matrix message out to *all* of its agent clients at once, in+a single event-loop tick. So this number is multiplied by the size of the room+before it ever reaches the pool: at two checkouts per client, a ten-agent room+turned one Slack message into twenty concurrent checkouts out of forty, and the+addressed client alone took up to nine more. That is the burst that pushed the+pool to its ceiling and started failing heartbeats.++The contract is one checkout per client per message, and none at all for a+message that needs no lookup — plus, as with the room service, no session held+open while the client posts to Matrix.+"""++from __future__ import annotations++from types import SimpleNamespace+from typing import Any++from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.bridges.agent.protocol.connections import ConnectionRegistry+from switch_core.clients.agent_client import AgentClient+from switch_core.clients.room_meta import RoomMeta+from switch_core.db.models import Agent, ApiKey, Client, Room, User+from switch_core.db.stores.agent_session_store import AgentSessionStore+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.client_store import ClientStore+from switch_core.db.stores.external_user_store import ExternalUserStore+from switch_core.db.stores.room_role_store import RoomRoleStore+from switch_core.db.stores.room_store import RoomStore++MATRIX_ROOM_ID = "!r:test"+++class _CountingSessionFactory:+ """The real factory, counting sessions opened and tracking how many are+ open right now. One session is one pool checkout."""++ def __init__(self, inner: async_sessionmaker[AsyncSession]) -> None:+ self._inner = inner+ self.opened = 0+ self.live = 0++ def __call__(self) -> Any:+ self.opened += 1+ return _Tracked(self, self._inner())+++class _Tracked:+ def __init__(self, tracker: _CountingSessionFactory, inner: Any) -> None:+ self._tracker = tracker+ self._inner = inner++ async def __aenter__(self) -> AsyncSession:+ self._tracker.live += 1+ return await self._inner.__aenter__() # type: ignore[no-any-return]++ async def __aexit__(self, *exc: object) -> bool:+ self._tracker.live -= 1+ return await self._inner.__aexit__(*exc) # type: ignore[no-any-return]+++async def _seed(+ session_factory: async_sessionmaker[AsyncSession], *, names: list[str]+) -> tuple[str, dict[str, Agent]]:+ async with session_factory() as session:+ user = User(name="o", email="o@test", role="user", password_hash="x")+ session.add(user)+ await session.flush()+ agents: dict[str, Agent] = {}+ for name in names:+ key = ApiKey(+ user_id=user.id,+ key_hash=f"hash-{name}",+ encrypted_key="enc",+ label=name,+ type="agent",+ )+ client = Client(+ matrix_user_id=f"@{name}:test",+ display_name=name,+ type="agent",+ password="x",+ )+ session.add_all([key, client])+ await session.flush()+ agent = Agent(+ name=name,+ description="d",+ agent_type="session_addressable",+ connector_type="claude_code",+ integration_profile={"connection_model": "session_addressable"},+ client_id=client.id,+ api_key_id=key.id,+ owner_id=user.id,+ )+ session.add(agent)+ await session.flush()+ agents[name] = agent+ room = Room(matrix_room_id=MATRIX_ROOM_ID, name="room", description="d")+ session.add(room)+ await session.flush()+ await RoomStore().add_agents(session, room.id, [a.id for a in agents.values()])+ await session.commit()+ return room.id, agents+++def _client(+ counting: _CountingSessionFactory, agent: Agent, room_id: str+) -> AgentClient:+ """An AgentClient wired to the real stores, with its room-meta cache warm.++ The cache is warm because that is the steady state: a client resolves a+ room once and then answers every later message in it from memory.+ """+ client = object.__new__(AgentClient)+ client.session_factory = counting # type: ignore[assignment]+ client.client_store = ClientStore()+ client.matrix_user_id = f"@{agent.name}:test"+ client.client_id = agent.client_id+ client._agent = agent+ client._agent_store = AgentStore()+ client._room_store = RoomStore()+ client._room_role_store = RoomRoleStore()+ client._agent_session_store = AgentSessionStore()+ client._external_user_store = ExternalUserStore()+ client._connections = ConnectionRegistry()+ client._frontend_base_url = None+ client._room_meta = {+ MATRIX_ROOM_ID: RoomMeta(+ room_id=room_id,+ name="room",+ bridge_id=None,+ channel_type="channel_public",+ )+ }+ client._attachment_groups = {}+ client._attachment_group_timers = {}+ client.sent = [] # type: ignore[attr-defined]++ async def _send_message(matrix_room_id: str, body: str, **kwargs: Any) -> str:+ client.sent.append((body, counting.live)) # type: ignore[attr-defined]+ return "$sent"++ client.send_message = _send_message # type: ignore[assignment, method-assign]+ client._event_buffer = SimpleNamespace( # type: ignore[assignment]+ enqueue=lambda *_a, **_k: None+ )+ return client+++def _message(body: str, sender: str = "@switch-slack-louisa:test") -> Any:+ return SimpleNamespace(+ body=body,+ formatted_body=None,+ sender=sender,+ event_id="$trigger",+ server_timestamp=0,+ source={"content": {"body": body, "sender_name": "louisa"}},+ )+++def _room() -> Any:+ return SimpleNamespace(room_id=MATRIX_ROOM_ID)+++class TestInboundMessageCheckouts:+ async def test_chatter_with_no_at_costs_nothing(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # The common case in a busy room, and the one multiplied by every agent+ # in it: no `@`, so there is nothing an alias or a role lease could+ # match and no reason to touch the database at all.+ room_id, agents = await _seed(session_factory, names=["member"])+ counting = _CountingSessionFactory(session_factory)+ client = _client(counting, agents["member"], room_id)++ await client.on_message(_room(), _message("just talking amongst ourselves"))++ assert counting.opened == 0++ async def test_an_at_message_for_somebody_else_costs_one(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # Was two: the room alias and the role lease each took a session.+ room_id, agents = await _seed(session_factory, names=["member", "other"])+ counting = _CountingSessionFactory(session_factory)+ client = _client(counting, agents["member"], room_id)++ await client.on_message(_room(), _message("@other can you look at this"))++ assert counting.opened == 1++ async def test_being_addressed_and_offline_still_costs_one(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # The expensive path: addressing policy, liveness, and the whole+ # offline-reply derivation. Was up to nine checkouts.+ room_id, agents = await _seed(session_factory, names=["member"])+ counting = _CountingSessionFactory(session_factory)+ client = _client(counting, agents["member"], room_id)++ await client.on_message(_room(), _message("@member can you look at this"))++ assert counting.opened == 1+ assert len(client.sent) == 1 # type: ignore[attr-defined]++ async def test_no_session_is_open_while_the_auto_reply_is_posted(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # Posting to Matrix is an unbounded wait as far as the pool is+ # concerned; doing it inside the transaction is how a slot ends up+ # idle-in-transaction for seconds.+ room_id, agents = await _seed(session_factory, names=["member"])+ counting = _CountingSessionFactory(session_factory)+ client = _client(counting, agents["member"], room_id)++ await client.on_message(_room(), _message("@member you there?"))++ assert [live for _body, live in client.sent] == [0] # type: ignore[attr-defined]++ async def test_a_restricted_agent_refusing_a_sender_costs_one(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ room_id, agents = await _seed(session_factory, names=["member"])+ async with session_factory() as session:+ await AgentStore().update(+ session,+ agents["member"].id,+ addressing_policy={"rules": [{"agents": ["nobody"], "users": []}]},+ )+ await session.commit()+ counting = _CountingSessionFactory(session_factory)+ client = _client(counting, agents["member"], room_id)++ await client.on_message(_room(), _message("@member you there?"))++ assert counting.opened == 1+ assert [live for _body, live in client.sent] == [0] # type: ignore[attr-defined]++ async def test_an_alias_tag_costs_one(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # Reached only after the alias lookup misses on name, so this is the+ # path where alias and role used to be two separate checkouts.+ room_id, agents = await _seed(session_factory, names=["member"])+ async with session_factory() as session:+ await RoomStore().set_alias(session, room_id, agents["member"].id, "fixer")+ await session.commit()+ counting = _CountingSessionFactory(session_factory)+ client = _client(counting, agents["member"], room_id)++ await client.on_message(_room(), _message("@fixer please look"))++ assert counting.opened == 1+ assert len(client.sent) == 1 # type: ignore[attr-defined]++ async def test_a_ten_agent_room_costs_ten(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # The burst, end to end. One message, every client in the room handling+ # it at once: ten slots out of forty, where it used to be twenty plus+ # the addressed client's own handful.+ names = [f"a{i}" for i in range(10)]+ room_id, agents = await _seed(session_factory, names=names)+ counting = _CountingSessionFactory(session_factory)+ clients = [_client(counting, agents[name], room_id) for name in names]++ for client in clients:+ await client.on_message(_room(), _message("@a3 can you take this"))++ assert counting.opened == 10diff --git a/core/tests/switch_core/clients/test_mention_routing.py b/core/tests/switch_core/clients/test_mention_routing.pyindex a45103b67..c30b36c61 100644--- a/core/tests/switch_core/clients/test_mention_routing.py+++ b/core/tests/switch_core/clients/test_mention_routing.py@@ -10,6 +10,11 @@ from switch_core.clients.agent_client import ()+@asynccontextmanager+async def _session_factory(): # type: ignore[no-untyped-def]+ yield object()++def _no_connections() -> SimpleNamespace:"""A connection registry with nothing live.@@ -47,10 +52,12 @@ def _is_mentioned(name: str, body: str) -> bool:async def _command_addresses(name: str, args: str) -> bool:# Exercise the real default command-targeting predicate with a client that# holds no role, so this reflects pure name-boundary matching.- client = SimpleNamespace(agent=SimpleNamespace(name=name))+ client = SimpleNamespace(+ agent=SimpleNamespace(name=name), session_factory=_session_factory+ )client._args_tag_my_name = lambda text: AgentClient._args_tag_my_name(client, text)- async def _no(_text: str, _room_id: str) -> bool:+ async def _no(_session: object, _text: str, _room_id: str) -> bool:return Falseclient._text_tags_my_role = _no@@ -150,10 +157,6 @@ def _role_client(agent_name: str, held_role: str | None) -> SimpleNamespace:"""A fake client for role tagging: its agent LIVE-holds `held_role` (orNone) — agent_room_role just returns that, ignoring the DB."""- @asynccontextmanager- async def _session_factory(): # type: ignore[no-untyped-def]- yield object()-async def _agent_room_role(_session, _room_id, _agent_id, _alive=()): # type: ignore[no-untyped-def]return held_role@@ -175,7 +178,9 @@ class TestRoleMentionRouting:async def test_role_holder_is_addressed(self) -> None:client = _role_client("ephemeral-cc", held_role="manager")assert (- await AgentClient._text_tags_my_role(client, "@manager review", "room-1")+ await AgentClient._text_tags_my_role(+ client, None, "@manager review", "room-1"+ )is True)@@ -183,7 +188,9 @@ class TestRoleMentionRouting:# This agent holds no role, so an @manager tag does not reach it.client = _role_client("ephemeral-cc", held_role=None)assert (- await AgentClient._text_tags_my_role(client, "@manager review", "room-1")+ await AgentClient._text_tags_my_role(+ client, None, "@manager review", "room-1"+ )is False)@@ -191,7 +198,9 @@ class TestRoleMentionRouting:# Holds "worker" but "@manager" is tagged → not addressed.client = _role_client("ephemeral-cc", held_role="worker")assert (- await AgentClient._text_tags_my_role(client, "@manager review", "room-1")+ await AgentClient._text_tags_my_role(+ client, None, "@manager review", "room-1"+ )is False)@@ -199,14 +208,16 @@ class TestRoleMentionRouting:# Boundary safety: holding "lead" must not match "@lead-dev".client = _role_client("ephemeral-cc", held_role="lead")assert (- await AgentClient._text_tags_my_role(client, "@lead-dev ping", "room-1")+ await AgentClient._text_tags_my_role(+ client, None, "@lead-dev ping", "room-1"+ )is False)async def test_no_at_short_circuits(self) -> None:client = _role_client("ephemeral-cc", held_role="manager")assert (- await AgentClient._text_tags_my_role(client, "no at here", "room-1")+ await AgentClient._text_tags_my_role(client, None, "no at here", "room-1")is False)@@ -215,10 +226,6 @@ def _alias_client(agent_name: str, alias_by_room: dict[str, str]) -> SimpleNames"""A fake client whose room alias is looked up from `alias_by_room`(room_id -> alias), mirroring RoomStore.get_alias scoped per room."""- @asynccontextmanager- async def _session_factory(): # type: ignore[no-untyped-def]- yield object()-async def _get_alias(_session, room_id, _agent_id): # type: ignore[no-untyped-def]return alias_by_room.get(room_id)@@ -238,7 +245,7 @@ class TestAliasMentionRouting:client = _alias_client("claude-code.aq-switch-2", {"room-1": "fixer"})assert (await AgentClient._text_tags_my_alias(- client, "@fixer please look", "room-1"+ client, None, "@fixer please look", "room-1")is True)@@ -246,21 +253,22 @@ class TestAliasMentionRouting:async def test_alias_case_insensitive(self) -> None:client = _alias_client("claude-code.aq-switch-2", {"room-1": "fixer"})assert (- await AgentClient._text_tags_my_alias(client, "@FIXER hi", "room-1") is True+ await AgentClient._text_tags_my_alias(client, None, "@FIXER hi", "room-1")+ is True)async def test_alias_is_room_scoped(self) -> None:# Alias set in room-1 only — tagging it in room-2 does not address us.client = _alias_client("claude-code.aq-switch-2", {"room-1": "fixer"})assert (- await AgentClient._text_tags_my_alias(client, "@fixer hi", "room-2")+ await AgentClient._text_tags_my_alias(client, None, "@fixer hi", "room-2")is False)async def test_no_alias_not_addressed(self) -> None:client = _alias_client("claude-code.aq-switch-2", {})assert (- await AgentClient._text_tags_my_alias(client, "@fixer hi", "room-1")+ await AgentClient._text_tags_my_alias(client, None, "@fixer hi", "room-1")is False)@@ -268,14 +276,14 @@ class TestAliasMentionRouting:# Boundary safety: alias "fix" must not match "@fixer".client = _alias_client("claude-code.aq-switch-2", {"room-1": "fix"})assert (- await AgentClient._text_tags_my_alias(client, "@fixer ping", "room-1")+ await AgentClient._text_tags_my_alias(client, None, "@fixer ping", "room-1")is False)async def test_no_at_short_circuits(self) -> None:client = _alias_client("claude-code.aq-switch-2", {"room-1": "fixer"})assert (- await AgentClient._text_tags_my_alias(client, "no at here", "room-1")+ await AgentClient._text_tags_my_alias(client, None, "no at here", "room-1")is False)@@ -290,19 +298,22 @@ class TestCommandRoleTargeting:async def test_holder_targeted_by_role(self) -> None:client = _role_client("ephemeral-cc", held_role="manager")assert (- await AgentClient._text_tags_my_role(client, "@manager", "room-1") is True+ await AgentClient._text_tags_my_role(client, None, "@manager", "room-1")+ is True)async def test_non_holder_not_targeted(self) -> None:client = _role_client("ephemeral-cc", held_role=None)assert (- await AgentClient._text_tags_my_role(client, "@manager", "room-1") is False+ await AgentClient._text_tags_my_role(client, None, "@manager", "room-1")+ is False)async def test_role_prefix_not_targeted(self) -> None:client = _role_client("ephemeral-cc", held_role="lead")assert (- await AgentClient._text_tags_my_role(client, "@lead-dev", "room-1") is False+ await AgentClient._text_tags_my_role(client, None, "@lead-dev", "room-1")+ is False)@@ -323,10 +334,6 @@ def _unavailable_client(returns the sentinel "OFFLINE"."""- @asynccontextmanager- async def _session_factory(): # type: ignore[no-untyped-def]- yield object()-async def _live_connected_rooms(_session, _agent_id): # type: ignore[no-untyped-def]return list(live_rooms)@@ -337,6 +344,7 @@ def _unavailable_client(return bound_hereasync def _unavailable_reply( # type: ignore[no-untyped-def]+ _session,_room_name,_agent,_asker_handle,@@ -357,12 +365,8 @@ def _unavailable_client(integration_profile={"connection_model": connection_model},)- async def _fresh_agent(): # type: ignore[no-untyped-def]- return agent-return SimpleNamespace(agent=agent,- _fresh_agent=_fresh_agent,session_factory=_session_factory,_connections=_no_connections(),_room_role_store=SimpleNamespace(agent_room_role=_agent_room_role),@@ -386,7 +390,9 @@ class TestUnavailableHereReply:async def test_role_holder_session_elsewhere_says_role_elsewhere(self) -> None:# Holds a role here, but its assuming session is attending room-B.client = _unavailable_client(live_rooms=["room-B"], role_here=True)- msg = await AgentClient._reply_when_unavailable_here(client, _here(), "asker")+ msg = await AgentClient._reply_when_unavailable_here(+ client, None, client.agent, _here(), "asker"+ )assert msg == _role_elsewhere_message("Room room-B")assert "Room room-B" in msg@@ -395,21 +401,27 @@ class TestUnavailableHereReply:# Defers to the known-agent reply (paste-ready connect command) with# the other rooms threaded in, rather than the role-flavoured wording.client = _unavailable_client(live_rooms=["room-B", "room-C"], role_here=False)- msg = await AgentClient._reply_when_unavailable_here(client, _here(), "asker")+ msg = await AgentClient._reply_when_unavailable_here(+ client, None, client.agent, _here(), "asker"+ )assert msg == "ELSEWHERE: Room room-B, Room room-C"async def test_only_session_is_here_falls_back_to_offline(self) -> None:# The only live session is the addressed room itself → nothing elsewhere.client = _unavailable_client(live_rooms=["room-A"], role_here=False)assert (- await AgentClient._reply_when_unavailable_here(client, _here(), "asker")+ await AgentClient._reply_when_unavailable_here(+ client, None, client.agent, _here(), "asker"+ )== "OFFLINE")async def test_no_live_sessions_is_offline(self) -> None:client = _unavailable_client(live_rooms=[], role_here=False)assert (- await AgentClient._reply_when_unavailable_here(client, _here(), "asker")+ await AgentClient._reply_when_unavailable_here(+ client, None, client.agent, _here(), "asker"+ )== "OFFLINE")@@ -420,12 +432,16 @@ class TestConnectedNotLive:async def test_bound_but_not_live_says_connected_not_live(self) -> None:client = _unavailable_client(live_rooms=[], role_here=False, bound_here=True)- msg = await AgentClient._reply_when_unavailable_here(client, _here(), "asker")+ msg = await AgentClient._reply_when_unavailable_here(+ client, None, client.agent, _here(), "asker"+ )assert msg == "NOT_LIVE"async def test_no_binding_is_offline(self) -> None:client = _unavailable_client(live_rooms=[], role_here=False, bound_here=False)- msg = await AgentClient._reply_when_unavailable_here(client, _here(), "asker")+ msg = await AgentClient._reply_when_unavailable_here(+ client, None, client.agent, _here(), "asker"+ )assert msg == "OFFLINE"async def test_passive_never_says_connected_not_live(self) -> None:@@ -436,7 +452,9 @@ class TestConnectedNotLive:connection_model="session_passive",bound_here=True,)- msg = await AgentClient._reply_when_unavailable_here(client, _here(), "asker")+ msg = await AgentClient._reply_when_unavailable_here(+ client, None, client.agent, _here(), "asker"+ )assert msg == "OFFLINE"async def test_same_named_live_room_not_offered_as_elsewhere(self) -> None:@@ -445,7 +463,9 @@ class TestConnectedNotLive:# not live → connected-not-live, not a confusing same-name pointer.# _here() is room-A / "Room A"; room id "A" → name "Room A" (collision).client = _unavailable_client(live_rooms=["A"], role_here=False, bound_here=True)- msg = await AgentClient._reply_when_unavailable_here(client, _here(), "asker")+ msg = await AgentClient._reply_when_unavailable_here(+ client, None, client.agent, _here(), "asker"+ )assert msg == "NOT_LIVE"async def test_distinct_named_live_room_still_points_elsewhere(self) -> None:@@ -453,5 +473,7 @@ class TestConnectedNotLive:client = _unavailable_client(live_rooms=["room-B"], role_here=False, bound_here=True)- msg = await AgentClient._reply_when_unavailable_here(client, _here(), "asker")+ msg = await AgentClient._reply_when_unavailable_here(+ client, None, client.agent, _here(), "asker"+ )assert msg == "ELSEWHERE: Room room-B"diff --git a/core/tests/switch_core/clients/test_no_session_reply_threading.py b/core/tests/switch_core/clients/test_no_session_reply_threading.pyindex 5edf2d770..63abfc56b 100644--- a/core/tests/switch_core/clients/test_no_session_reply_threading.py+++ b/core/tests/switch_core/clients/test_no_session_reply_threading.py@@ -1,5 +1,6 @@from __future__ import annotations+from contextlib import asynccontextmanagerfrom types import SimpleNamespaceimport pytest@@ -8,9 +9,15 @@ from switch_core.clients.agent_client import (_STARTING_SESSION_MESSAGE,AUTO_REPLY_FLAG,AgentClient,+ _GateOutcome,)+@asynccontextmanager+async def _session_factory(): # type: ignore[no-untyped-def]+ yield object()++class _Recorder:"""Captures the send_message call so we can assert on thread_root_id."""@@ -40,37 +47,48 @@ def _fake_self(async def _resolve_room_meta(_matrix_room_id: str) -> SimpleNamespace:return _meta()- async def _compute_addressed(_event: object, _meta: object) -> bool:+ def _addressed_without_lookup(_event: object, _meta: object) -> bool:+ return True++ async def _compute_addressed(+ _session: object, _event: object, _meta: object+ ) -> bool:return True # addressed → the offline auto-reply path runs+ async def _fresh_agent(_session: object) -> object:+ return ns.agent+async def _gate_addressed(- _room: object,- _event: object,- _meta: object,- _reply_thread_root: str,- is_addressed: bool,- ) -> bool:- # No addressing policy in these tests — pass the addressed flag through.- return is_addressed+ _session: object, _agent: object, _event: object, _meta: object+ ) -> _GateOutcome:+ # No addressing policy in these tests — the message stays addressed.+ return _GateOutcome(addressed=True, refusal=None)- async def _is_available(_room_id: str) -> bool:+ async def _is_available(_session: object, _agent: object, _room_id: str) -> bool:return False # no live session → triggers the auto-reply- async def _reply_when_unavailable_here(_meta: object, _asker_handle: str) -> str:+ async def _reply_when_unavailable_here(+ _session: object, _agent: object, _meta: object, _asker_handle: str+ ) -> str:return unavailable_replyns = SimpleNamespace(agent=SimpleNamespace(id="agent-1", name="cc-bug-fixing"),+ session_factory=_session_factory,_resolve_room_meta=_resolve_room_meta,+ _addressed_without_lookup=_addressed_without_lookup,_compute_addressed=_compute_addressed,+ _fresh_agent=_fresh_agent,_gate_addressed=_gate_addressed,_is_available=_is_available,_reply_when_unavailable_here=_reply_when_unavailable_here,+ _triggered_by_auto_reply=AgentClient._triggered_by_auto_reply,send_message=send_message,_event_buffer=SimpleNamespace(enqueue=lambda *a, **k: None),)- # Exercise the real sender-tagging helper.+ # Exercise the real sender-tagging and auto-reply helpers.ns._sender_handle = AgentClient._sender_handle.__get__(ns)+ ns._post_auto_reply = AgentClient._post_auto_reply.__get__(ns)return nsdiff --git a/core/tests/switch_core/clients/test_offline_owner_reply.py b/core/tests/switch_core/clients/test_offline_owner_reply.pyindex 2a6a1bc42..20d5f8b03 100644--- a/core/tests/switch_core/clients/test_offline_owner_reply.py+++ b/core/tests/switch_core/clients/test_offline_owner_reply.py@@ -43,7 +43,9 @@ def _auto_session_claude_agent() -> SimpleNamespace:def _client(owner_handle: str | None) -> SimpleNamespace:- async def _owner_handle_in(_agent: object, _bridge_id: object) -> str | None:+ async def _owner_handle_in(+ _session: object, _agent: object, _bridge_id: object+ ) -> str | None:return owner_handlereturn SimpleNamespace(owner_handle_in=_owner_handle_in)@@ -54,6 +56,7 @@ async def _reply() -> str:return await AgentClient._unavailable_reply(client,+ None,_meta(),agent,"louisa",diff --git a/core/tests/switch_core/clients/test_owner_notification_handle.py b/core/tests/switch_core/clients/test_owner_notification_handle.pyindex c11d42f4a..1eb0b4610 100644--- a/core/tests/switch_core/clients/test_owner_notification_handle.py+++ b/core/tests/switch_core/clients/test_owner_notification_handle.py@@ -12,17 +12,11 @@ which is exactly the granularity a handle needs.from __future__ import annotations-from contextlib import asynccontextmanagerfrom types import SimpleNamespacefrom switch_core.clients.agent_client import AgentClient-@asynccontextmanager-async def _session_factory(): # type: ignore[no-untyped-def]- yield object()--def _claimed(bridge_id: str, username: str) -> SimpleNamespace:"""An `ExternalUser` row, with only the fields the resolver reads."""return SimpleNamespace(bridge_id=bridge_id, external_username=username)@@ -33,7 +27,6 @@ def _client(claimed: list[SimpleNamespace]) -> SimpleNamespace:return claimedreturn SimpleNamespace(- session_factory=_session_factory,_external_user_store=SimpleNamespace(get_by_user=_get_by_user),)@@ -46,7 +39,9 @@ class TestResolvingTheOwnersHandle:async def test_the_owners_account_on_this_bridge(self) -> None:client = _client([_claimed("slack-1", "louis.amaudruz")])- handle = await AgentClient.owner_handle_in(client, _agent("u1"), "slack-1")+ handle = await AgentClient.owner_handle_in(+ client, None, _agent("u1"), "slack-1"+ )assert handle == "louis.amaudruz"@@ -58,7 +53,7 @@ class TestResolvingTheOwnersHandle:)assert (- await AgentClient.owner_handle_in(client, _agent("u1"), "telegram-1")+ await AgentClient.owner_handle_in(client, None, _agent("u1"), "telegram-1")== "louisa")@@ -68,7 +63,7 @@ class TestResolvingTheOwnersHandle:client = _client([_claimed("slack-1", "louis.amaudruz")])assert (- await AgentClient.owner_handle_in(client, _agent("u1"), "telegram-1")+ await AgentClient.owner_handle_in(client, None, _agent("u1"), "telegram-1")is None)@@ -76,21 +71,26 @@ class TestResolvingTheOwnersHandle:client = _client([_claimed("slack-1", "louis.amaudruz")])assert (- await AgentClient.owner_handle_in(client, _agent(None), "slack-1") is None+ await AgentClient.owner_handle_in(client, None, _agent(None), "slack-1")+ is None)async def test_nobody_for_a_room_with_no_bridge(self) -> None:# An internal-only room has no platform to mention anyone on.client = _client([_claimed("slack-1", "louis.amaudruz")])- assert await AgentClient.owner_handle_in(client, _agent("u1"), None) is None+ assert (+ await AgentClient.owner_handle_in(client, None, _agent("u1"), None) is None+ )async def test_the_same_account_every_time_when_they_hold_several(self) -> None:# Claiming is not exclusive. Whichever is picked, it must not change# between one message and the next.client = _client([_claimed("slack-1", "zoe"), _claimed("slack-1", "adam")])- first = await AgentClient.owner_handle_in(client, _agent("u1"), "slack-1")- second = await AgentClient.owner_handle_in(client, _agent("u1"), "slack-1")+ first = await AgentClient.owner_handle_in(client, None, _agent("u1"), "slack-1")+ second = await AgentClient.owner_handle_in(+ client, None, _agent("u1"), "slack-1"+ )assert first == second == "adam"diff --git a/core/tests/switch_core/clients/test_system_message_never_addresses.py b/core/tests/switch_core/clients/test_system_message_never_addresses.pyindex ec6a4e3ac..6eec62196 100644--- a/core/tests/switch_core/clients/test_system_message_never_addresses.py+++ b/core/tests/switch_core/clients/test_system_message_never_addresses.py@@ -51,13 +51,16 @@ def _client(name: str = "flintai-sdk.ts") -> SimpleNamespace:return Falseclient._is_mentioned = lambda event: AgentClient._is_mentioned(client, event)+ client._addressed_without_lookup = lambda event, meta: (+ AgentClient._addressed_without_lookup(client, event, meta)+ )client._is_mentioned_via_alias = _noclient._is_mentioned_via_role = _noreturn clientasync def _addressed(client: SimpleNamespace, event: object, meta: RoomMeta) -> bool:- return await AgentClient._compute_addressed(client, event, meta)+ return await AgentClient._compute_addressed(client, None, event, meta)@pytest.mark.asynciodiff --git a/core/tests/switch_core/test_room_service_pool_holds.py b/core/tests/switch_core/test_room_service_pool_holds.pynew file mode 100644index 000000000..e26d6340f--- /dev/null+++ b/core/tests/switch_core/test_room_service_pool_holds.py@@ -0,0 +1,286 @@+"""No database session is open while `RoomService` talks to Matrix.++An invite or a kick can take the full 10 s the Matrix admin client allows. Held+inside a transaction, that is a connection-pool slot removed from circulation+for ten seconds, and enough of them at once exhaust the pool and start failing+heartbeats fleet-wide. So the contract these tests pin is not a count: it is+that the number of *live* sessions is zero at the moment the Matrix call runs.++They also pin the ordering the split depends on — Matrix membership must never+exceed what the database records — because that is what makes the resulting+inconsistency recoverable rather than a silent over-permission.+"""++from __future__ import annotations++from typing import Any++import pytest+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.models import Agent, ApiKey, Client, Room, User+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.room_service import RoomService+++class _TrackingSessionFactory:+ """The real factory, tracking how many sessions are open right now."""++ def __init__(self, inner: async_sessionmaker[AsyncSession]) -> None:+ self._inner = inner+ self.live = 0+ self.opened = 0++ def __call__(self) -> Any:+ return _TrackedSession(self, self._inner())+++class _TrackedSession:+ def __init__(self, tracker: _TrackingSessionFactory, inner: Any) -> None:+ self._tracker = tracker+ self._inner = inner++ async def __aenter__(self) -> AsyncSession:+ self._tracker.live += 1+ self._tracker.opened += 1+ return await self._inner.__aenter__() # type: ignore[no-any-return]++ async def __aexit__(self, *exc: object) -> bool:+ self._tracker.live -= 1+ return await self._inner.__aexit__(*exc) # type: ignore[no-any-return]+++class _RecordingMatrix:+ """Records each Matrix call together with the sessions open at the time."""++ def __init__(self, tracker: _TrackingSessionFactory) -> None:+ self._tracker = tracker+ self.calls: list[tuple[str, str, int]] = []++ async def invite_to_room(self, matrix_room_id: str, matrix_user_id: str) -> None:+ self.calls.append(("invite", matrix_user_id, self._tracker.live))++ async def kick_user(self, matrix_room_id: str, matrix_user_id: str) -> None:+ self.calls.append(("kick", matrix_user_id, self._tracker.live))++ async def delete_room(self, matrix_room_id: str) -> None:+ self.calls.append(("delete_room", matrix_room_id, self._tracker.live))+++class _RunningClients:+ def __init__(self, by_agent: dict[str, Any]) -> None:+ self._by_agent = by_agent+ self._by_id = {c.client_id: c for c in by_agent.values()}++ def get_by_agent_id(self, agent_id: str) -> Any:+ return self._by_agent.get(agent_id)++ def get(self, client_id: str) -> Any:+ return self._by_id.get(client_id)++ def get_by_type(self, client_type: str) -> list[Any]:+ return []+++class _RunningClient:+ def __init__(self, client_id: str, matrix_user_id: str) -> None:+ self.client_id = client_id+ self.matrix_user_id = matrix_user_id+++async def _seed(+ session_factory: async_sessionmaker[AsyncSession], *, agents: int+) -> tuple[str, list[str], dict[str, Any]]:+ """A room plus `agents` agents that are NOT yet members of it."""+ async with session_factory() as session:+ user = User(name="o", email="o@test", role="user", password_hash="x")+ session.add(user)+ await session.flush()+ agent_ids: list[str] = []+ running: dict[str, Any] = {}+ for i in range(agents):+ key = ApiKey(+ user_id=user.id,+ key_hash=f"hash-{i}",+ encrypted_key="enc",+ label=f"a{i}",+ type="agent",+ )+ client = Client(+ matrix_user_id=f"@a{i}:test",+ display_name=f"a{i}",+ type="agent",+ password="x",+ )+ session.add_all([key, client])+ await session.flush()+ agent = Agent(+ name=f"a{i}",+ description="d",+ agent_type="session_addressable",+ connector_type="claude_code",+ integration_profile={},+ client_id=client.id,+ api_key_id=key.id,+ owner_id=user.id,+ )+ session.add(agent)+ await session.flush()+ agent_ids.append(agent.id)+ running[agent.id] = _RunningClient(client.id, client.matrix_user_id)+ room = Room(matrix_room_id="!r:test", name="room", description="d")+ session.add(room)+ await session.flush()+ await session.commit()+ return room.id, agent_ids, running+++def _service(+ tracker: _TrackingSessionFactory, running: dict[str, Any]+) -> tuple[RoomService, _RecordingMatrix]:+ matrix = _RecordingMatrix(tracker)+ svc = object.__new__(RoomService)+ svc._session_factory = tracker # type: ignore[assignment]+ svc._room_store = RoomStore() # type: ignore[assignment]+ svc._agent_store = AgentStore() # type: ignore[assignment]+ svc._matrix_admin = matrix # type: ignore[assignment]+ svc._client_lifecycle = _RunningClients(running) # type: ignore[assignment]+ svc._collab_lifecycle = _RunningClients({}) # type: ignore[assignment]+ return svc, matrix+++class TestAddAgentsToRoom:+ async def test_no_session_is_open_across_the_invites(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ room_id, agent_ids, running = await _seed(session_factory, agents=3)+ tracker = _TrackingSessionFactory(session_factory)+ svc, matrix = _service(tracker, running)++ await svc.add_agents_to_room(room_id, agent_ids=agent_ids)++ assert len(matrix.calls) == 3+ assert [live for _kind, _who, live in matrix.calls] == [0, 0, 0]++ async def test_membership_is_recorded_before_the_invite(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # The window this opens must be "member in Switch, not yet on Matrix" —+ # under-privileged and visible. The other order leaves an agent reading+ # a room Switch has no record of it being in.+ room_id, agent_ids, running = await _seed(session_factory, agents=1)+ tracker = _TrackingSessionFactory(session_factory)+ svc, matrix = _service(tracker, running)+ seen_at_invite: list[list[str]] = []++ async def _invite(matrix_room_id: str, matrix_user_id: str) -> None:+ async with session_factory() as session:+ seen_at_invite.append(await RoomStore().get_agent_ids(session, room_id))++ matrix.invite_to_room = _invite # type: ignore[method-assign]++ await svc.add_agents_to_room(room_id, agent_ids=agent_ids)++ assert seen_at_invite == [agent_ids]++ async def test_room_clients_is_only_recorded_after_the_invite(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # `reconcile_room_clients` treats a member with no `room_clients` row as+ # "the invite may not have landed", so the row must not be written until+ # the invite has actually gone out.+ room_id, agent_ids, running = await _seed(session_factory, agents=1)+ tracker = _TrackingSessionFactory(session_factory)+ svc, matrix = _service(tracker, running)+ seen_at_invite: list[list[str]] = []++ async def _invite(matrix_room_id: str, matrix_user_id: str) -> None:+ async with session_factory() as session:+ seen_at_invite.append(+ await RoomStore().get_client_ids(session, room_id)+ )++ matrix.invite_to_room = _invite # type: ignore[method-assign]++ await svc.add_agents_to_room(room_id, agent_ids=agent_ids)++ assert seen_at_invite == [[]]+ async with session_factory() as session:+ assert await RoomStore().get_client_ids(session, room_id) == [+ running[agent_ids[0]].client_id+ ]++ async def test_a_missing_room_still_raises_before_any_matrix_call(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ _, agent_ids, running = await _seed(session_factory, agents=1)+ tracker = _TrackingSessionFactory(session_factory)+ svc, matrix = _service(tracker, running)++ with pytest.raises(ValueError, match="Room not found"):+ await svc.add_agents_to_room("no-such-room", agent_ids=agent_ids)++ assert matrix.calls == []+++class TestRemoveAgentsFromRoom:+ async def test_no_session_is_open_across_the_kicks(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ room_id, agent_ids, running = await _seed(session_factory, agents=3)+ tracker = _TrackingSessionFactory(session_factory)+ svc, matrix = _service(tracker, running)+ await svc.add_agents_to_room(room_id, agent_ids=agent_ids)+ matrix.calls.clear()++ await svc.remove_agents_from_room(room_id, agent_ids)++ assert [kind for kind, _who, _live in matrix.calls] == ["kick"] * 3+ assert [live for _kind, _who, live in matrix.calls] == [0, 0, 0]++ async def test_the_kick_lands_before_the_row_is_dropped(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # Removal is the mirror of addition: revoke on Matrix first, so the+ # window is never "joined on Matrix, no membership row".+ room_id, agent_ids, running = await _seed(session_factory, agents=1)+ tracker = _TrackingSessionFactory(session_factory)+ svc, matrix = _service(tracker, running)+ await svc.add_agents_to_room(room_id, agent_ids=agent_ids)+ seen_at_kick: list[list[str]] = []++ async def _kick(matrix_room_id: str, matrix_user_id: str) -> None:+ async with session_factory() as session:+ seen_at_kick.append(await RoomStore().get_agent_ids(session, room_id))++ matrix.kick_user = _kick # type: ignore[method-assign]++ await svc.remove_agents_from_room(room_id, agent_ids)++ assert seen_at_kick == [agent_ids]+ async with session_factory() as session:+ assert await RoomStore().get_agent_ids(session, room_id) == []+++class TestDeleteRoom:+ async def test_no_session_is_open_across_the_teardown(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ room_id, agent_ids, running = await _seed(session_factory, agents=2)+ tracker = _TrackingSessionFactory(session_factory)+ svc, matrix = _service(tracker, running)+ await svc.add_agents_to_room(room_id, agent_ids=agent_ids)+ matrix.calls.clear()++ await svc.delete_room(room_id)++ assert [kind for kind, _who, _live in matrix.calls] == [+ "kick",+ "kick",+ "delete_room",+ ]+ assert [live for _kind, _who, live in matrix.calls] == [0, 0, 0]++ async with session_factory() as session:+ assert await RoomStore().get(session, room_id) is Nonediff --git a/core/tests/switch_core/test_room_service_reconcile.py b/core/tests/switch_core/test_room_service_reconcile.pyindex 5588f6552..090e49b2d 100644--- a/core/tests/switch_core/test_room_service_reconcile.py+++ b/core/tests/switch_core/test_room_service_reconcile.py@@ -19,10 +19,14 @@ class _FakeSessionCM:class _FakeRoomStore:def __init__(- self, rooms: list[Any], client_ids_by_room: dict[str, list[str]]+ self,+ rooms: list[Any],+ client_ids_by_room: dict[str, list[str]],+ agent_clients_by_room: dict[str, dict[str, str]],) -> None:self._rooms = roomsself._client_ids_by_room = client_ids_by_room+ self._agent_clients_by_room = agent_clients_by_roomself.added: list[tuple[str, str]] = []async def get_all(@@ -33,6 +37,11 @@ class _FakeRoomStore:async def get_client_ids(self, session: Any, room_id: str) -> list[str]:return list(self._client_ids_by_room.get(room_id, []))+ async def get_member_agent_clients(+ self, session: Any, room_id: str+ ) -> dict[str, str]:+ return dict(self._agent_clients_by_room.get(room_id, {}))+async def add_client(self, session: Any, client_id: str, room_id: str) -> None:self.added.append((client_id, room_id))@@ -66,8 +75,9 @@ def _build_service(rooms: list[Any],client_ids_by_room: dict[str, list[str]],by_type: dict[str, list[Any]],+ agent_clients_by_room: dict[str, dict[str, str]] | None = None,) -> tuple[RoomService, _FakeRoomStore, _FakeMatrix]:- room_store = _FakeRoomStore(rooms, client_ids_by_room)+ room_store = _FakeRoomStore(rooms, client_ids_by_room, agent_clients_by_room or {})matrix = _FakeMatrix()svc = object.__new__(RoomService)svc._session_factory = lambda: _FakeSessionCM() # type: ignore[assignment]@@ -77,7 +87,7 @@ def _build_service(return svc, room_store, matrix-class TestReconcileSystemClients:+class TestReconcileRoomClients:async def test_backfills_missing_admin_into_existing_room(self) -> None:# A room created before the admin client existed: it has the other# system clients but not the admin. Reconcile invites + records it.@@ -88,7 +98,7 @@ class TestReconcileSystemClients:by_type={"admin": [_admin()]},)- await svc.reconcile_system_clients()+ await svc.reconcile_room_clients()assert matrix.invited == [("!mx:switch.local", "@switch-admin:switch.local")]assert room_store.added == [("admin-client", "room-1")]@@ -101,7 +111,7 @@ class TestReconcileSystemClients:by_type={"admin": [_admin()]},)- await svc.reconcile_system_clients()+ await svc.reconcile_room_clients()assert matrix.invited == []assert room_store.added == []@@ -117,7 +127,7 @@ class TestReconcileSystemClients:by_type={"admin": [_admin()]},)- await svc.reconcile_system_clients()+ await svc.reconcile_room_clients()assert ("!live:switch.local", "@switch-admin:switch.local") in matrix.invitedassert ("!arch:switch.local", "@switch-admin:switch.local") in matrix.invited@@ -132,7 +142,38 @@ class TestReconcileSystemClients:by_type={},)- await svc.reconcile_system_clients()+ await svc.reconcile_room_clients()++ assert matrix.invited == []+ assert room_store.added == []++ async def test_reinvites_an_agent_whose_invite_never_landed(self) -> None:+ # `add_agents_to_room` writes the membership row, invites, then records+ # `room_clients`. A crash in that window leaves the member with no+ # `room_clients` row, which is exactly what is repaired here.+ room = SimpleNamespace(id="room-1", matrix_room_id="!mx:switch.local")+ svc, room_store, matrix = _build_service(+ rooms=[room],+ client_ids_by_room={"room-1": []},+ by_type={},+ agent_clients_by_room={"room-1": {"agent-client": "@fixer:switch.local"}},+ )++ await svc.reconcile_room_clients()++ assert matrix.invited == [("!mx:switch.local", "@fixer:switch.local")]+ assert room_store.added == [("agent-client", "room-1")]++ async def test_an_agent_already_recorded_is_left_alone(self) -> None:+ room = SimpleNamespace(id="room-1", matrix_room_id="!mx:switch.local")+ svc, room_store, matrix = _build_service(+ rooms=[room],+ client_ids_by_room={"room-1": ["agent-client"]},+ by_type={},+ agent_clients_by_room={"room-1": {"agent-client": "@fixer:switch.local"}},+ )++ await svc.reconcile_room_clients()assert matrix.invited == []assert room_store.added == []