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
Refactor switch-core for saner events (observability/telemetry) (#610)
Abel Dantas6e19b3f8f9a7
diff --git a/.env.example b/.env.exampleindex af98b1932..0ac052716 100644--- a/.env.example+++ b/.env.example@@ -124,9 +124,10 @@ DB_NAME=switch# OTLP_EXPORT_INTERVAL_SECONDS=60# ── Client identity ──────────────────────────────────────────────────────────-# The server half of every client's `@localpart:server` id. Nothing is-# contacted at it; the ids are stable public handles.-MATRIX_SERVER_NAME=localhost+# The server half of every member's `@localpart:server` id. Nothing is+# contacted at it; the ids are stable public handles. (MATRIX_SERVER_NAME, the+# old name, is still accepted for one release.)+ID_SERVER_NAME=localhost# ── Agent registration ───────────────────────────────────────────────────────AGENT_REGISTRATION_TOKEN=diff --git a/CLAUDE.md b/CLAUDE.mdindex a74f1547f..2d07f0f39 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -77,10 +77,10 @@ just test -k "test_name" # run specific test- `stores/` — query methods and domain-specific data access- `migrations/` — Alembic migrations (`env.py`, `versions/`)- `room_service.py` / `rooms_yaml.py` — Room lifecycle, configuration, provisioning-- `clients/` — room clients (agent, admin, bridge)+- `clients/` — room participants: `actor.py` (identity, membership, writes: `HumanActor`, `AgentActor`, `SystemActor`) and `consumer.py` (the delivery loop and hooks: `AgentConsumer`, `CommandConsumer`, `WorkspaceConsumer`)- `bridges/` — External integrations- - `agent/` — Agent Bridge (HTTP API, MCP server, server-side connectors)- - `collaboration/` — Collaboration Bridge (Slack, Mattermost, Discord, Teams, Telegram adapters)+ - `agent/` — Agent Bridge (HTTP API, MCP server, server-side connectors); `protocol/agent_core.py` is `AgentCore`, `protocol/agent_connections.py` holds each `AgentConnection`+ - `collaboration/` — Collaboration Bridge: one `CollaborationCore` per workspace, driving a `PlatformAdapter` (Slack, Mattermost, Discord, Teams, Telegram)- `resource/` — Resource Bridge (platform resource management)- `gateway/` — Management API for the frontend@@ -88,7 +88,24 @@ just test -k "test_name" # run specific test- Async throughout: all I/O is async (DB, external APIs)- Dependency injection: stores and services are injected, not global singletons- Session management: API endpoints use middleware-provided sessions; background work creates sessions explicitly-- All participants in rooms are clients reading and writing the `messages` table through the transport port+- Every room participant is an actor writing to the `messages` table through the transport port; only a participant that reads the room has a consumer. Human actors (one `HumanActor` per platform user) read nothing, because the bridge's `WorkspaceConsumer` reads for the whole workspace++**The message bus is PostgreSQL** (`transport/postgres.py`). Switch once ran on a+Matrix homeserver; that is gone, and no Matrix server or client library is+involved. A send is an `INSERT` into `messages`, with a per-room advisory lock+assigning `seq` (`db/stores/message_store.py`). The `messages_notify` trigger+calls `pg_notify('switch_message', …)` with the room, `seq` and row id, delivered+on commit (`db/notify_ddl.py`). One `MessageListener` (`messages/notify.py`)+holds a dedicated `LISTEN` connection and wakes the subscribers for that room;+each client then reads the rows after its own cursor, 200 at a time. The+notification is a wake-up, never the payload. Invites and presence travel over+in-process buses (`transport/invites.py`, `transport/ephemeral.py`), which is+part of why switch-core runs as a single replica. Names such as+the `matrix_room_id` / `matrix_user_id` columns and wire fields, the+`@localpart:server` id shape and `m.room.message` content types are kept as+stable identifiers and wire shapes, not as a sign that Matrix is in use. In+Python they are `transport_room_id` / `transport_user_id`, and the server name+is `ID_SERVER_NAME` (`MATRIX_SERVER_NAME` is still read, with a warning).## The Switch skilldiff --git a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.tsindex a60c23263..453634168 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.ts@@ -42,7 +42,7 @@ const h = vi.hoisted(() => {};});-vi.mock('@main/core/sdk-host/shared-watcher', () => ({+vi.mock('@main/core/sdk-host/agent-host', () => ({discardControllerState: h.discardControllerState,}));diff --git a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.tsindex 0421dcd80..f1a58b4db 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts@@ -1,6 +1,6 @@import { eq } from 'drizzle-orm';import { getPlugin } from '@main/core/providers/plugin-registry';-import { discardControllerState } from '@main/core/sdk-host/shared-watcher';+import { discardControllerState } from '@main/core/sdk-host/agent-host';import { sessionHooks } from '@main/core/sessions/session-hooks';import { setControllerStopped } from '@main/core/switch-rooms/auto-session-store';import { autoSessionWatcher } from '@main/core/switch-rooms/auto-session-watcher';diff --git a/console/apps/switch-console-desktop/src/main/core/agents/remote-watcher.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/remote-watcher.test.tsindex feaa3d3e5..618cbfdce 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/remote-watcher.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/remote-watcher.test.ts@@ -19,8 +19,8 @@ vi.mock('./getAgents', () => ({getAgents: async () => [{ id: 'existing', switchAgentId: 'registered' }],}));vi.mock('./getAgentById', () => ({ getAgentById: vi.fn() }));-vi.mock('@main/core/sdk-host/shared-watcher', () => ({- configureSharedWatcher: vi.fn(),+vi.mock('@main/core/sdk-host/agent-host', () => ({+ configureAgentHost: vi.fn(),applyControllerState: mocks.applyControllerState,}));vi.mock('@main/core/switch-rooms/auto-session-store', () => ({ listAutoSessionAgentIds: vi.fn() }));diff --git a/console/apps/switch-console-desktop/src/main/core/agents/remote-watcher.ts b/console/apps/switch-console-desktop/src/main/core/agents/remote-watcher.tsindex 05420dd3d..d5d394547 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/remote-watcher.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/remote-watcher.ts@@ -1,4 +1,4 @@-import { applyControllerState, configureSharedWatcher } from '@main/core/sdk-host/shared-watcher';+import { applyControllerState, configureAgentHost } from '@main/core/sdk-host/agent-host';import { agentEvents } from './agent-events';import { getAgentById } from './getAgentById';import { getAgents } from './getAgents';@@ -44,5 +44,5 @@ export async function pushRemoteAutoApprove(agentId: string): Promise<void> {remoteSessionReconciler.start(agentId);}export async function stopRemoteWatcher(agentId: string): Promise<void> {- await configureSharedWatcher(agentId, { connected: false, spawning: false }, 'restore');+ await configureAgentHost(agentId, { connected: false, spawning: false }, 'restore');}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.test.tsindex 95738d2c1..724b1f23d 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.test.ts@@ -18,8 +18,8 @@ vi.mock('@main/core/workspaces/workspace-session', () => ({}));vi.mock('@main/core/sdk-host/host-sessions', () => ({ listHostSessions: mocks.list }));vi.mock('@main/core/sdk-host/shared-agent-runtime', () => ({ stopSharedSession: mocks.stop }));-vi.mock('@main/core/sdk-host/shared-watcher', () => ({- configureSharedWatcher: mocks.disable,+vi.mock('@main/core/sdk-host/agent-host', () => ({+ configureAgentHost: mocks.disable,applyControllerState: mocks.restart,}));// Sidecar management is deliberately left real: it owns the Start transition,diff --git a/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.tsindex aeebeb943..5d48de666 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.ts@@ -1,7 +1,7 @@import { eq } from 'drizzle-orm';+import { configureAgentHost } from '@main/core/sdk-host/agent-host';import { listHostSessions } from '@main/core/sdk-host/host-sessions';import { stopSharedSession } from '@main/core/sdk-host/shared-agent-runtime';-import { configureSharedWatcher } from '@main/core/sdk-host/shared-watcher';import { manageAgentSidecar } from '@main/core/sdk-host/sidecar-management';import { sessionHooks } from '@main/core/sessions/session-hooks';import { sessionRuntimeManager } from '@main/core/sessions/session-runtime-manager';@@ -20,7 +20,7 @@ export async function resetRemoteAgent(agentId: string): Promise<void> {const agent = await getAgentById(agentId);if (!agent?.workspaceId || !agent.switchAgentId)throw new Error('The agent is not linked to Switch.');- await configureSharedWatcher(agentId, { connected: false, spawning: false }, 'explicit');+ await configureAgentHost(agentId, { connected: false, spawning: false }, 'explicit');remoteSessionReconciler.stop(agentId);const remote = await listHostSessions(agentId);for (const session of remote) {diff --git a/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoApprove.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoApprove.test.tsindex 59d0c5979..a0b42ebad 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoApprove.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoApprove.test.ts@@ -31,7 +31,7 @@ vi.mock('@main/core/switch-rooms/auto-session-store', () => ({listStoppedControllerAgentIds,}));vi.mock('./remote-watcher', () => ({ pushRemoteAutoApprove }));-vi.mock('@main/core/sdk-host/shared-watcher', () => ({+vi.mock('@main/core/sdk-host/agent-host', () => ({keepAutoApproveChoice,recordAutoApproveOnHost,}));diff --git a/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoApprove.ts b/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoApprove.tsindex 5dfa70fb1..391dcdc15 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoApprove.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoApprove.ts@@ -1,4 +1,4 @@-import { keepAutoApproveChoice, recordAutoApproveOnHost } from '@main/core/sdk-host/shared-watcher';+import { keepAutoApproveChoice, recordAutoApproveOnHost } from '@main/core/sdk-host/agent-host';import { listStoppedControllerAgentIds } from '@main/core/switch-rooms/auto-session-store';import { getRemoteAgentLocation } from './agent-location';import { getAgentById } from './getAgentById';diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.ymlindex eaa2eab12..0134d794f 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml@@ -213,6 +213,10 @@ services:DB_OWNER_USER: ${DB_OWNER_USER}DB_OWNER_PASSWORD: ${DB_OWNER_PASSWORD}DB_NAME: ${DB_NAME}+ ID_SERVER_NAME: localhost+ # The same setting under its old name, for a SWITCH_VERSION released+ # before the rename, which reads only this one. Drop it once the oldest+ # supported release reads ID_SERVER_NAME.MATRIX_SERVER_NAME: localhostAGENT_REGISTRATION_TOKEN: ${AGENT_REGISTRATION_TOKEN}JWT_SECRET_KEY: ${JWT_SECRET_KEY}diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.auto-approve.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/agent-host.auto-approve.test.tssimilarity index 93%rename from console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.auto-approve.test.tsrename to console/apps/switch-console-desktop/src/main/core/sdk-host/agent-host.auto-approve.test.tsindex 17d1ac99b..0710aa1a2 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.auto-approve.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/agent-host.auto-approve.test.ts@@ -74,11 +74,11 @@ vi.mock('./local-host', () => ({ startLocalWatcher: vi.fn(), stopLocalWatcher: vvi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: vi.fn() } }));const {- configureSharedWatcher,- configureSharedWatcherFor,+ configureAgentHost,+ configureAgentHostFor,keepAutoApproveChoice,recordAutoApproveOnHost,-} = await import('./shared-watcher');+} = await import('./agent-host');const run = promisify(execFile);let root: string;@@ -140,7 +140,7 @@ it('takes auto-approve from the host when another Console changed it', async ()mocks.agent.mockResolvedValue(agent(false));mocks.bringUp.mockResolvedValue({ root, runtimeMode: 'full-access', legacyStopped: [] });- await configureSharedWatcher('agent-1', { connected: true, spawning: true }, 'explicit');+ await configureAgentHost('agent-1', { connected: true, spawning: true }, 'explicit');expect(adopted()).toBe(true);expect(mocks.updateAgent).toHaveBeenCalledWith({ agentId: 'agent-1', autoApprove: true });@@ -149,7 +149,7 @@ it('takes auto-approve from the host when another Console changed it', async ()it('leaves the row alone when it already agrees with the host', async () => {mocks.agent.mockResolvedValue(agent(true));- await configureSharedWatcher('agent-1', { connected: true, spawning: true }, 'explicit');+ await configureAgentHost('agent-1', { connected: true, spawning: true }, 'explicit');expect(adopted()).toBe(true);expect(mocks.updateAgent).not.toHaveBeenCalled();@@ -158,7 +158,7 @@ it('leaves the row alone when it already agrees with the host', async () => {it('writes this Console’s value when the person using it has just changed it', async () => {mocks.agent.mockResolvedValue(agent(true));- await configureSharedWatcherFor('agent-1', { connected: true, spawning: true }, 'explicit', {+ await configureAgentHostFor('agent-1', { connected: true, spawning: true }, 'explicit', {name: undefined,autoApprove: 'this-console',});@@ -177,12 +177,7 @@ it('does not take a subagent watcher’s setting for its parent’s', async () =return { stdout, stderr };});- await configureSharedWatcher(- 'agent-1',- { connected: true, spawning: true },- 'explicit',- 'helper'- );+ await configureAgentHost('agent-1', { connected: true, spawning: true }, 'explicit', 'helper');expect(adopted()).toBe(false);expect(mocks.updateAgent).not.toHaveBeenCalled();@@ -192,7 +187,7 @@ it('does not take a subagent watcher’s setting for its parent’s', async () =it('asks nothing of the host’s choice for a watcher being stopped', async () => {mocks.agent.mockResolvedValue(agent(true));- await configureSharedWatcher('agent-1', { connected: false, spawning: false }, 'explicit');+ await configureAgentHost('agent-1', { connected: false, spawning: false }, 'explicit');expect(adopted()).toBe(false);});diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.locality.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/agent-host.locality.test.tssimilarity index 89%rename from console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.locality.test.tsrename to console/apps/switch-console-desktop/src/main/core/sdk-host/agent-host.locality.test.tsindex e30aaa747..adc2dc50d 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.locality.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/agent-host.locality.test.ts@@ -66,8 +66,8 @@ vi.mock('./local-host', () => ({removeLocalWatcherRoots: mocks.removeRoots,}));-const { applyControllerState, configureSharedWatcher, discardControllerState } =- await import('./shared-watcher');+const { applyControllerState, configureAgentHost, discardControllerState } =+ await import('./agent-host');const { controllerConnectionId } = await import('@main/core/switch-rooms/session-connection-id');beforeEach(() => {@@ -93,7 +93,7 @@ beforeEach(() => {it('watches a local agent inside Console without deploying a host', async () => {mocks.location.mockResolvedValue({ id: 'local', dir: '/work', sshHost: null });- await configureSharedWatcher('agent-1', { connected: true, spawning: true }, 'explicit');+ await configureAgentHost('agent-1', { connected: true, spawning: true }, 'explicit');expect(mocks.startLocal).toHaveBeenCalled();expect(mocks.deploy).not.toHaveBeenCalled();expect(mocks.runCommand).not.toHaveBeenCalled();@@ -101,7 +101,7 @@ it('watches a local agent inside Console without deploying a host', async () =>it('gives the watcher the agent’s controller connection, not a fresh one', async () => {mocks.location.mockResolvedValue({ id: 'local', dir: '/work', sshHost: null });- await configureSharedWatcher('agent-1', { connected: true, spawning: true }, 'explicit');+ await configureAgentHost('agent-1', { connected: true, spawning: true }, 'explicit');// Derived from the Switch agent id, so a second Console watching this agent// reopens this connection rather than opening one the server cannot tell is// the same role.@@ -112,7 +112,7 @@ it('gives the watcher the agent’s controller connection, not a fresh one', asyit('stops a local agent through Console rather than a deployed host', async () => {mocks.location.mockResolvedValue({ id: 'local', dir: '/work', sshHost: null });- await configureSharedWatcher('agent-1', { connected: false, spawning: false }, 'explicit');+ await configureAgentHost('agent-1', { connected: false, spawning: false }, 'explicit');expect(mocks.stopLocal).toHaveBeenCalledWith('switch-agent-1');expect(mocks.deploy).not.toHaveBeenCalled();});@@ -124,7 +124,7 @@ it('brings a watcher on an SSH host up in one command there', async () => {sshHost: 'builder',connectionId: 'connection-1',});- await configureSharedWatcher('agent-1', { connected: true, spawning: true }, 'explicit');+ await configureAgentHost('agent-1', { connected: true, spawning: true }, 'explicit');expect(mocks.bringUp).toHaveBeenCalledOnce();expect(mocks.bringUp.mock.calls[0][0]).toMatchObject({transport: expect.objectContaining({ kind: 'ssh' }),@@ -153,7 +153,7 @@ it.each(['tells an SSH host whether a %s to connected=%s clears standing down',async (intent, connected, clear) => {mocks.location.mockResolvedValue({ id: 'remote', dir: '/work', sshHost: 'builder' });- await configureSharedWatcher('agent-1', { connected, spawning: connected }, intent);+ await configureAgentHost('agent-1', { connected, spawning: connected }, intent);expect(mocks.bringUp.mock.calls[0][0]).toMatchObject({state: { connected, spawning: connected },clear: clear === 'true',@@ -163,7 +163,7 @@ it.each([it('tells an SSH host to connect without spawning when auto-start is off', async () => {mocks.location.mockResolvedValue({ id: 'remote', dir: '/work', sshHost: 'builder' });- await configureSharedWatcher('agent-1', { connected: true, spawning: false }, 'explicit');+ await configureAgentHost('agent-1', { connected: true, spawning: false }, 'explicit');expect(mocks.bringUp.mock.calls[0][0]).toMatchObject({state: { connected: true, spawning: false },clear: true,@@ -172,7 +172,7 @@ it('tells an SSH host to connect without spawning when auto-start is off', asyncit('passes the spawn decision to a local watcher', async () => {mocks.location.mockResolvedValue({ id: 'local', dir: '/work', sshHost: null });- await configureSharedWatcher('agent-1', { connected: true, spawning: false }, 'explicit');+ await configureAgentHost('agent-1', { connected: true, spawning: false }, 'explicit');expect(mocks.startLocal.mock.calls[0][1]).toEqual({ intent: 'explicit', spawning: false });});@@ -226,11 +226,7 @@ it('connects only once the agent’s managed server is ready', async () => {ready = resolve;}));- const connecting = configureSharedWatcher(- 'agent-1',- { connected: true, spawning: true },- 'restore'- );+ const connecting = configureAgentHost('agent-1', { connected: true, spawning: true }, 'restore');await vi.waitFor(() =>expect(mocks.ready).toHaveBeenCalledWith(expect.objectContaining({ id: 'server-1' })));@@ -249,7 +245,7 @@ it('never connects to a server whose update failed', async () => {});mocks.ready.mockRejectedValue(new Error('Updating Local from switch-core 0.1.0 failed'));await expect(- configureSharedWatcher('agent-1', { connected: true, spawning: true }, 'restore')+ configureAgentHost('agent-1', { connected: true, spawning: true }, 'restore')).rejects.toThrow('failed');expect(mocks.bringUp).not.toHaveBeenCalled();expect(mocks.startLocal).not.toHaveBeenCalled();@@ -258,7 +254,7 @@ it('never connects to a server whose update failed', async () => {it('stands a watcher down without waiting for its server', async () => {mocks.location.mockResolvedValue({ id: 'local', dir: '/work', sshHost: null });mocks.ready.mockRejectedValue(new Error('update failed'));- await configureSharedWatcher('agent-1', { connected: false, spawning: false }, 'explicit');+ await configureAgentHost('agent-1', { connected: false, spawning: false }, 'explicit');expect(mocks.ready).not.toHaveBeenCalled();expect(mocks.stopLocal).toHaveBeenCalledWith('switch-agent-1');});diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/agent-host.tssimilarity index 96%rename from console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.tsrename to console/apps/switch-console-desktop/src/main/core/sdk-host/agent-host.tsindex d51a88510..1d88a3406 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/agent-host.ts@@ -128,7 +128,7 @@ export async function applyControllerState(autoApprove: AutoApproveSource): Promise<void> {const connected = !(await listStoppedControllerAgentIds()).includes(agentId);- await configureSharedWatcherFor(agentId, { connected, spawning: connected }, intent, {+ await configureAgentHostFor(agentId, { connected, spawning: connected }, intent, {name: undefined,autoApprove,});@@ -159,17 +159,17 @@ export async function discardControllerState(agentId: string): Promise<void> {* auto-approve comes from. */export type WatcherTarget = { name: string | undefined; autoApprove: AutoApproveSource };-/** {@link configureSharedWatcherFor}, taking auto-approve from the host. */-export function configureSharedWatcher(+/** {@link configureAgentHostFor}, taking auto-approve from the host. */+export function configureAgentHost(agentId: string,state: ControllerState,intent: WatcherIntent,name?: string): Promise<void> {- return configureSharedWatcherFor(agentId, state, intent, { name, autoApprove: 'host' });+ return configureAgentHostFor(agentId, state, intent, { name, autoApprove: 'host' });}-export async function configureSharedWatcherFor(+export async function configureAgentHostFor(agentId: string,state: ControllerState,intent: WatcherIntent,@@ -253,7 +253,7 @@ export async function configureSharedWatcherFor(stopped: brought.legacyStopped,});if (brought.runtimeMode !== null) {- log.info('shared-watcher: taking auto-approve from the host, where another Console set it', {+ log.info('agent-host: taking auto-approve from the host, where another Console set it', {agentId,runtimeMode: brought.runtimeMode,});diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/local-host.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/local-host.test.tsindex 24d52714f..f9b26812a 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/local-host.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/local-host.test.ts@@ -19,7 +19,7 @@ vi.mock('node:os', async (importOriginal) => ({}));vi.mock('@switch-console/agent-providers', () => ({ensureSharedProcess: mocks.ensure,- runSharedWatcher: mocks.runWatcher,+ runAgentHost: mocks.runWatcher,superviseSharedHost: mocks.supervise,clearTakenOver: mocks.clearTakenOver,WATCH_FLAGS_FILE: 'watch.json',diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/local-host.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/local-host.tsindex eeb6f2b58..03c391db3 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/local-host.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/local-host.ts@@ -7,7 +7,7 @@ import {clearTakenOver,ensureSharedProcess,type HostStartSource,- runSharedWatcher,+ runAgentHost,sharedConfigSchema,type SharedHostConfig,sharedSessionRoot,@@ -298,7 +298,7 @@ export async function startLocalWatcher(watchers,prepared,(signal) =>- runSharedWatcher(+ runAgentHost(prepared,written,signal,diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/sidecar-management.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/sidecar-management.test.tsindex d23f48ef8..2a8dd32ac 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/sidecar-management.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/sidecar-management.test.ts@@ -11,8 +11,8 @@ vi.mock('@main/core/agents/agent-location', () => ({ getRemoteAgentLocation: mocvi.mock('@main/core/switch-rooms/auto-session-store', () => ({setControllerStopped: mocks.setStopped,}));-vi.mock('./shared-watcher', () => ({- configureSharedWatcher: mocks.configure,+vi.mock('./agent-host', () => ({+ configureAgentHost: mocks.configure,applyControllerState: mocks.apply,}));const { manageAgentSidecar } = await import('./sidecar-management');diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/sidecar-management.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/sidecar-management.tsindex b559c8cfc..8ca98d2a8 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/sidecar-management.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/sidecar-management.ts@@ -1,7 +1,7 @@import { getRemoteAgentLocation } from '@main/core/agents/agent-location';import { getAgentById } from '@main/core/agents/getAgentById';import { setControllerStopped } from '@main/core/switch-rooms/auto-session-store';-import { applyControllerState, configureSharedWatcher } from './shared-watcher';+import { applyControllerState, configureAgentHost } from './agent-host';export async function manageAgentSidecar(agentId: string,@@ -21,13 +21,13 @@ export async function manageAgentSidecar(// one, so this no longer touches that setting.await setControllerStopped(agentId, action === 'stop');if (action === 'stop') {- await configureSharedWatcher(agentId, { connected: false, spawning: false }, 'explicit');+ await configureAgentHost(agentId, { connected: false, spawning: false }, 'explicit');return;}// Someone pressed Start, Update or Restart, so this is the explicit ask that// brings a controller back after it stood down for a connection something// else took. Update and Restart stop first so the new bundle is what starts.if (action !== 'start')- await configureSharedWatcher(agentId, { connected: false, spawning: false }, 'explicit');+ await configureAgentHost(agentId, { connected: false, spawning: false }, 'explicit');await applyControllerState(agentId, 'explicit', 'host');}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.test.tsindex bf805ed23..f61124302 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts@@ -21,9 +21,9 @@ const mocks = vi.hoisted(() => {},};});-vi.mock('@main/core/sdk-host/shared-watcher', () => ({+vi.mock('@main/core/sdk-host/agent-host', () => ({applyControllerState: mocks.apply,- configureSharedWatcher: mocks.configure,+ configureAgentHost: mocks.configure,}));vi.mock('@main/core/sdk-host/local-host', () => ({ disposeLocalHosts: mocks.dispose }));vi.mock('@main/core/agents/getAgents', () => ({ getAgents: mocks.agents }));diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.tsindex 4d43c971b..7085f798a 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.ts@@ -4,8 +4,8 @@ import { getAgents } from '@main/core/agents/getAgents';import { onManagedServerUpgraded } from '@main/core/managed-switch-server/session-readiness';import type { HostReachabilityChange } from '@main/core/remote-hosts/host-reachability-service';import { hostReachabilityService } from '@main/core/remote-hosts/production-host-reachability';+import { applyControllerState, configureAgentHost } from '@main/core/sdk-host/agent-host';import { disposeLocalHosts, type WatcherIntent } from '@main/core/sdk-host/local-host';-import { applyControllerState, configureSharedWatcher } from '@main/core/sdk-host/shared-watcher';import { log } from '@main/lib/logger';import type { Agent } from '@shared/core/agents/agents';import { listAutoSessionSubagents, setAutoSessionSubagent } from './auto-session-store';@@ -256,13 +256,13 @@ class AutoSessionWatcher {stopForAgent(agentId: string): Promise<void> {this.cancelRetry(agentId);- return configureSharedWatcher(agentId, { connected: false, spawning: false }, 'restore');+ return configureAgentHost(agentId, { connected: false, spawning: false }, 'restore');}startForSubagent(agentId: string, name: string): Promise<void> {- return configureSharedWatcher(agentId, { connected: true, spawning: true }, 'restore', name);+ return configureAgentHost(agentId, { connected: true, spawning: true }, 'restore', name);}stopForSubagent(agentId: string, name: string): Promise<void> {- return configureSharedWatcher(agentId, { connected: false, spawning: false }, 'restore', name);+ return configureAgentHost(agentId, { connected: false, spawning: false }, 'restore', name);}/** Stops every locally hosted watcher and session, so none outlives Console. */dispose(): Promise<void> {diff --git a/console/packages/agent-providers/src/host/shared-watcher.test.ts b/console/packages/agent-providers/src/host/agent-host.test.tssimilarity index 92%rename from console/packages/agent-providers/src/host/shared-watcher.test.tsrename to console/packages/agent-providers/src/host/agent-host.test.tsindex ccde67b3d..9849b4341 100644--- a/console/packages/agent-providers/src/host/shared-watcher.test.ts+++ b/console/packages/agent-providers/src/host/agent-host.test.ts@@ -7,17 +7,17 @@ import { join } from 'node:path';import type * as runtime from '@sandboxaq/switch-agent-runtime';import type { AgentBridgeEvent, SwitchEventStreamDeps } from '@sandboxaq/switch-agent-runtime';import { afterEach, expect, it, vi } from 'vitest';-import type { Handoff } from './handoff';-import { ensureSharedProcess, type Supervision } from './launch';-import { type SessionRequest, SessionLinks } from './session-channel';-import { sharedConfigSchema } from './shared-config';import {MAX_HOST_RESTARTS,stopSupersededSessions,- runSharedWatcher,- SharedWatchAssignments,+ runAgentHost,+ AgentHostAssignments,supersededSessions,-} from './shared-watcher';+} from './agent-host';+import type { Handoff } from './handoff';+import { ensureSharedProcess, type Supervision } from './launch';+import { type SessionRequest, SessionLinks } from './session-channel';+import { sharedConfigSchema } from './shared-config';import { clearTakenOver, recordTakenOver } from './taken-over';import { WatcherControl } from './watcher-tools';@@ -203,10 +203,10 @@ it.each(['claude', 'codex', 'opencode', 'antigravity', 'cursor'])(roomConnection: { connectionId: 'watcher' },});const event = { sequence: 7, roomId: 'room', messageId: 'message' };- const opened = await SharedWatchAssignments.open(root);+ const opened = await AgentHostAssignments.open(root);const first = await opened.assign(template, event);await opened.handled(event.sequence);- const restarted = await SharedWatchAssignments.open(root);+ const restarted = await AgentHostAssignments.open(root);expect(restarted.cursor).toBe(7);// The same delivery served again is the session it was already given, not a// second one started to answer the same message.@@ -336,7 +336,7 @@ it('stays down while a takeover marker says another client holds the connection'// Returns instead of reading the credentials it would need to connect: the// watcher never gets as far as reopening the connection it lost.await expect(- runSharedWatcher(+ runAgentHost(root,watchable(root),new AbortController().signal,@@ -350,7 +350,7 @@ it('stays down while a takeover marker says another client holds the connection'// failing here only because this test gave it no credentials to read.await clearTakenOver(root);await expect(- runSharedWatcher(+ runAgentHost(root,watchable(root),new AbortController().signal,@@ -365,7 +365,7 @@ it('asks again for an event it assigned but died before routing', async () => {roots.push(root);paths.root = root;const config = template(root);- const assignments = await SharedWatchAssignments.open(root);+ const assignments = await AgentHostAssignments.open(root);const routed = await assignments.assign(config, {sequence: 4,roomId: 'room',@@ -379,7 +379,7 @@ it('asks again for an event it assigned but died before routing', async () => {messageId: 'six',});- const restarted = await SharedWatchAssignments.open(root);+ const restarted = await AgentHostAssignments.open(root);expect(restarted.cursor).toBe(4);// Redelivery finds the same session, so the event is routed where it was// always going rather than to a second one.@@ -402,7 +402,7 @@ it('resumes a journal written before routing was recorded at its last complete eroots.push(root);paths.root = root;const config = template(root);- const older = await SharedWatchAssignments.open(root);+ const older = await AgentHostAssignments.open(root);for (const [sequence, roomId] of [[4, 'room'],[6, 'other'],@@ -412,7 +412,7 @@ it('resumes a journal written before routing was recorded at its last complete e// Six, because the watcher only assigns the next event once the one before it// has been routed — so only the last record is still owed.- expect((await SharedWatchAssignments.open(root)).cursor).toBe(6);+ expect((await AgentHostAssignments.open(root)).cursor).toBe(6);});it('resumes at the server head after its numbering restarts', async () => {@@ -420,7 +420,7 @@ it('resumes at the server head after its numbering restarts', async () => {roots.push(root);paths.root = root;const config = template(root);- const assignments = await SharedWatchAssignments.open(root);+ const assignments = await AgentHostAssignments.open(root);const before = await assignments.assign(config, {sequence: 13,roomId: 'room',@@ -434,7 +434,7 @@ it('resumes at the server head after its numbering restarts', async () => {// A saved position from the old numbering would be asked for again on every// reconnect, so the watcher must forget it rather than stall behind head.expect(assignments.cursor).toBe(0);- const reloaded = await SharedWatchAssignments.open(root);+ const reloaded = await AgentHostAssignments.open(root);expect(reloaded.cursor).toBe(0);// Low sequence numbers are fresh events now, not duplicates of old ones.@@ -487,7 +487,7 @@ async function eventually(reached: () => boolean | Promise<boolean>): Promise<vo/** Whether every event the watcher parked has been taken by its session. */async function settled(root: string): Promise<boolean> {- return (await SharedWatchAssignments.open(root)).pending().length === 0;+ return (await AgentHostAssignments.open(root)).pending().length === 0;}const addressed = (sequence: number, roomId: string): AgentBridgeEvent => ({@@ -521,7 +521,7 @@ it('starts no saved session at startup; each waits until it is needed', async ()const { supervision } = sessionHosts();const abort = new AbortController();- const run = runSharedWatcher(root, config, abort.signal, supervision, new WatcherControl());+ const run = runAgentHost(root, config, abort.signal, supervision, new WatcherControl());try {await new Promise((resolve) => setTimeout(resolve, 500));expect(ensureSharedProcess).not.toHaveBeenCalled();@@ -552,7 +552,7 @@ it('leaves an event queued behind earlier work unstarted once spawning is turned);const abort = new AbortController();- const run = runSharedWatcher(root, config, abort.signal, supervision, new WatcherControl());+ const run = runAgentHost(root, config, abort.signal, supervision, new WatcherControl());try {await eventually(() => streams.length === 1);const stream = streams[0]!;@@ -574,7 +574,7 @@ it('leaves an event queued behind earlier work unstarted once spawning is turnedawait run;}- const journal = await SharedWatchAssignments.open(root);+ const journal = await AgentHostAssignments.open(root);const sessions = journal.sessions().map((assigned) => assigned.session.sessionId);expect(sessions).toHaveLength(2);expect(started).toEqual([sessions[0]]);@@ -600,7 +600,7 @@ it('gives one room one session however close together its first messages arrive'vi.spyOn(console, 'warn').mockImplementation(() => {});const abort = new AbortController();- const run = runSharedWatcher(root, config, abort.signal, supervision, new WatcherControl());+ const run = runAgentHost(root, config, abort.signal, supervision, new WatcherControl());try {await eventually(() => streams.length === 1);await Promise.all([@@ -613,7 +613,7 @@ it('gives one room one session however close together its first messages arrive'await run;}- const journal = await SharedWatchAssignments.open(root);+ const journal = await AgentHostAssignments.open(root);expect(journal.sessions()).toHaveLength(1);expect(new Set(started).size).toBe(1);expect(journal.pending()).toEqual([]);@@ -634,7 +634,7 @@ it('routes a room that has a session to that session, and starts no other', asynconst hosts = sessionHosts();const abort = new AbortController();- const run = runSharedWatcher(root, config, abort.signal, hosts.supervision, new WatcherControl());+ const run = runAgentHost(root, config, abort.signal, hosts.supervision, new WatcherControl());try {await eventually(() => streams.length === 1);await streams[0]!.onEvent!(addressed(2, 'room'));@@ -661,7 +661,7 @@ it('routes a room that has a session to that session, and starts no other', asynvi.mocked(ensureSharedProcess).mock.calls.map((call) => call[0].config.session.sessionId))).toEqual(new Set([owner.sessionId]));- const journal = await SharedWatchAssignments.open(root);+ const journal = await AgentHostAssignments.open(root);expect(journal.sessions()).toHaveLength(1);// Recorded as taken, so a watcher restarted here reopens past it rather than// handing the same event over again.@@ -678,7 +678,7 @@ it('routes to the session Console moved the room to, and tells Switch where everconst control = new WatcherControl();const abort = new AbortController();- const run = runSharedWatcher(root, config, abort.signal, hosts.supervision, control);+ const run = runAgentHost(root, config, abort.signal, hosts.supervision, control);try {await eventually(() => streams.length === 1);expect(await control.place(placed.sessionId, 'room')).toEqual({@@ -704,7 +704,7 @@ it('routes to the session Console moved the room to, and tells Switch where ever{ type: 'room', handoff: { sequence: 1, roomId: 'room', messageId: 'message-1' } },]);// The room was served without the watcher minting a session for it.- expect((await SharedWatchAssignments.open(root)).sessions()).toEqual([]);+ expect((await AgentHostAssignments.open(root)).sessions()).toEqual([]);// And a watcher started again routes where this one did.expect(JSON.parse(await readFile(join(root, 'placements.json'), 'utf8'))).toEqual({placements: { [placed.sessionId]: 'room' },@@ -723,7 +723,7 @@ it('puts a move Console asked for back when Switch refuses it', async () => {vi.spyOn(console, 'warn').mockImplementation(() => {});const abort = new AbortController();- const run = runSharedWatcher(root, config, abort.signal, hosts.supervision, control);+ const run = runAgentHost(root, config, abort.signal, hosts.supervision, control);try {await eventually(() => streams.length === 1);await control.place(first.sessionId, 'room');@@ -784,7 +784,7 @@ it('answers its sessions’ tool calls as the calling session, placing the roomconst identity = { agentId: config.session.agentId, sessionId: caller.sessionId };const abort = new AbortController();- const run = runSharedWatcher(root, config, abort.signal, hosts.supervision, new WatcherControl());+ const run = runAgentHost(root, config, abort.signal, hosts.supervision, new WatcherControl());try {await eventually(() => streams.length === 1);const tools = await hosts.ask(caller.sessionRoot, identity, { type: 'tools' });@@ -855,7 +855,7 @@ it('forgets a room another connection took over, and a session that was stopped'vi.spyOn(console, 'warn').mockImplementation(() => {});const abort = new AbortController();- const run = runSharedWatcher(root, config, abort.signal, hosts.supervision, new WatcherControl());+ const run = runAgentHost(root, config, abort.signal, hosts.supervision, new WatcherControl());try {await eventually(() => streams.length === 1);await streams[0]!.onRoomReleased!({ roomId: 'room', sessionId: taken.sessionId });@@ -863,7 +863,7 @@ it('forgets a room another connection took over, and a session that was stopped'// With nothing placed there and starting sessions off, the room's message waits.await streams[0]!.onEvent!(addressed(3, 'room'));- expect((await SharedWatchAssignments.open(root)).pending()).toMatchObject([+ expect((await AgentHostAssignments.open(root)).pending()).toMatchObject([{ roomId: 'room', messageId: 'message-3' },]);expect(hosts.to(taken.sessionRoot)).toEqual([]);@@ -901,7 +901,7 @@ it('still owes an event its session never acknowledged', async () => {roots.push(root);paths.root = root;const config = await spawning(root);- const assignments = await SharedWatchAssignments.open(root);+ const assignments = await AgentHostAssignments.open(root);const assigned = await assignments.assign(config, {sequence: 1,roomId: 'room',@@ -915,7 +915,7 @@ it('still owes an event its session never acknowledged', async () => {const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});const abort = new AbortController();- const run = runSharedWatcher(root, config, abort.signal, hosts.supervision, new WatcherControl());+ const run = runAgentHost(root, config, abort.signal, hosts.supervision, new WatcherControl());try {await eventually(() => streams.length === 1);await streams[0]!.onEvent!(addressed(2, 'room'));@@ -928,7 +928,7 @@ it('still owes an event its session never acknowledged', async () => {await run;}- const journal = await SharedWatchAssignments.open(root);+ const journal = await AgentHostAssignments.open(root);expect(journal.pending()).toMatchObject([{ sequence: 2, roomId: 'room', messageId: 'message-2', event: { type: 'message' } },]);@@ -1033,14 +1033,14 @@ it('hands a session it has just created the event that created it', async () =>// watcher that dies here still has the event to hand over.started.push({sessionId: launched.session.sessionId,- parked: (await SharedWatchAssignments.open(root)).pending(),+ parked: (await AgentHostAssignments.open(root)).pending(),});return hosts.start(sessionRoot);});const abort = new AbortController();- const run = runSharedWatcher(root, config, abort.signal, hosts.supervision, new WatcherControl());+ const run = runAgentHost(root, config, abort.signal, hosts.supervision, new WatcherControl());try {await eventually(() => streams.length === 1);await streams[0]!.onEvent!(addressed(1, 'room'));@@ -1050,7 +1050,7 @@ it('hands a session it has just created the event that created it', async () =>await run;}- const [assigned] = (await SharedWatchAssignments.open(root)).sessions();+ const [assigned] = (await AgentHostAssignments.open(root)).sessions();expect(started.map((entry) => entry.sessionId)).toEqual([assigned!.session.sessionId]);expect(started[0]!.parked).toMatchObject([{ sequence: 1, roomId: 'room', messageId: 'message-1' },@@ -1080,11 +1080,11 @@ it('holds a room nothing can take while starting sessions is off, and delivers ovi.spyOn(console, 'warn').mockImplementation(() => {});const abort = new AbortController();- const run = runSharedWatcher(root, config, abort.signal, supervision, new WatcherControl());+ const run = runAgentHost(root, config, abort.signal, supervision, new WatcherControl());try {await eventually(() => streams.length === 1);await streams[0]!.onEvent!(addressed(1, 'room'));- expect((await SharedWatchAssignments.open(root)).pending()).toMatchObject([+ expect((await AgentHostAssignments.open(root)).pending()).toMatchObject([{ sequence: 1, roomId: 'room', messageId: 'message-1', spawning: false },]);expect(ensureSharedProcess).not.toHaveBeenCalled();@@ -1096,7 +1096,7 @@ it('holds a room nothing can take while starting sessions is off, and delivers oabort.abort();await run;}- const journal = await SharedWatchAssignments.open(root);+ const journal = await AgentHostAssignments.open(root);expect(journal.pending()).toEqual([]);expect(journal.sessions()).toHaveLength(1);});@@ -1112,7 +1112,7 @@ it('keeps a held event, content and all, across a controller restart', async ()vi.spyOn(console, 'warn').mockImplementation(() => {});const first = new AbortController();- const running = runSharedWatcher(root, config, first.signal, supervision, new WatcherControl());+ const running = runAgentHost(root, config, first.signal, supervision, new WatcherControl());try {await eventually(() => streams.length === 1);await streams[0]!.onEvent!(addressed(1, 'room'));@@ -1123,13 +1123,7 @@ it('keeps a held event, content and all, across a controller restart', async ()await writeFlags(root, { enabled: true, spawn: true });const second = new AbortController();- const restarted = runSharedWatcher(- root,- config,- second.signal,- supervision,- new WatcherControl()- );+ const restarted = runAgentHost(root, config, second.signal, supervision, new WatcherControl());try {await eventually(() => hosts.requests.length >= 1);await eventually(() => settled(root));@@ -1137,7 +1131,7 @@ it('keeps a held event, content and all, across a controller restart', async ()second.abort();await restarted;}- const [assigned] = (await SharedWatchAssignments.open(root)).sessions();+ const [assigned] = (await AgentHostAssignments.open(root)).sessions();expect(hosts.to(join(root, assigned!.session.sessionId))).toMatchObject([{type: 'room',@@ -1163,7 +1157,7 @@ it('starts the session serving a room again when its host has gone, instead of a);const abort = new AbortController();- const run = runSharedWatcher(root, config, abort.signal, hosts.supervision, new WatcherControl());+ const run = runAgentHost(root, config, abort.signal, hosts.supervision, new WatcherControl());try {await eventually(() => streams.length === 1);started.length = 0;@@ -1178,7 +1172,7 @@ it('starts the session serving a room again when its host has gone, instead of aexpect(hosts.to(owner.sessionRoot)).toMatchObject([{ type: 'room', handoff: { messageId: 'message-2' } },]);- expect((await SharedWatchAssignments.open(root)).sessions()).toHaveLength(1);+ expect((await AgentHostAssignments.open(root)).sessions()).toHaveLength(1);});it('gives a room a new session once the one serving it has been stopped', async () => {@@ -1195,7 +1189,7 @@ it('gives a room a new session once the one serving it has been stopped', asyncconst hosts = sessionHosts();const abort = new AbortController();- const run = runSharedWatcher(root, config, abort.signal, hosts.supervision, new WatcherControl());+ const run = runAgentHost(root, config, abort.signal, hosts.supervision, new WatcherControl());try {await eventually(() => streams.length === 1);await streams[0]!.onEvent!(addressed(2, 'room'));@@ -1204,7 +1198,7 @@ it('gives a room a new session once the one serving it has been stopped', asyncabort.abort();await run;}- const sessions = (await SharedWatchAssignments.open(root)).sessions();+ const sessions = (await AgentHostAssignments.open(root)).sessions();expect(sessions).toHaveLength(2);expect(sessions.at(-1)!.session.sessionId).not.toBe(owner.sessionId);expect(hosts.to(owner.sessionRoot)).toEqual([]);@@ -1226,7 +1220,7 @@ it('forgets a session Console deleted, so its room starts a new one', async () =const control = new WatcherControl();const abort = new AbortController();- const run = runSharedWatcher(root, config, abort.signal, hosts.supervision, control);+ const run = runAgentHost(root, config, abort.signal, hosts.supervision, control);try {await eventually(() => streams.length === 1);await control.forget(owner.sessionId);@@ -1237,7 +1231,7 @@ it('forgets a session Console deleted, so its room starts a new one', async () =abort.abort();await run;}- const sessions = (await SharedWatchAssignments.open(root)).sessions();+ const sessions = (await AgentHostAssignments.open(root)).sessions();const fresh = sessions.at(-1)!.session.sessionId;expect(fresh).not.toBe(owner.sessionId);expect(hosts.to(owner.sessionRoot)).toEqual([]);@@ -1261,7 +1255,7 @@ it('passes an approval answer to the session it is for, and only that one', asynawait hosts.start(own.sessionRoot);await hosts.start(other.sessionRoot);const abort = new AbortController();- const run = runSharedWatcher(root, config, abort.signal, hosts.supervision, new WatcherControl());+ const run = runAgentHost(root, config, abort.signal, hosts.supervision, new WatcherControl());const outcome = (sessionId: string) => ({session_id: sessionId,request_id: 'permission',@@ -1299,7 +1293,7 @@ it('hands a relayed command to the session it names, and only if it runs here',await hosts.start(other.sessionRoot);const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});const abort = new AbortController();- const run = runSharedWatcher(root, config, abort.signal, hosts.supervision, new WatcherControl());+ const run = runAgentHost(root, config, abort.signal, hosts.supervision, new WatcherControl());const command = (sessionId: string) => ({ sessionId, commandId: `command-${sessionId}` });try {await eventually(() => streams.length === 1);@@ -1338,7 +1332,7 @@ it('refuses to run without being the parent of its sessions', async () => {links: null,};await expect(- runSharedWatcher(root, config, new AbortController().signal, detached, new WatcherControl())+ runAgentHost(root, config, new AbortController().signal, detached, new WatcherControl())).rejects.toThrow('parent of its sessions');});@@ -1350,7 +1344,7 @@ it('hands a message to its session over the IPC pipe and releases it once taken'const hosts = sessionHosts();const abort = new AbortController();- const run = runSharedWatcher(root, config, abort.signal, hosts.supervision, new WatcherControl());+ const run = runAgentHost(root, config, abort.signal, hosts.supervision, new WatcherControl());try {await eventually(() => streams.length === 1);await streams[0]!.onEvent!(addressed(1, 'room'));@@ -1374,7 +1368,7 @@ it('hands a message to its session over the IPC pipe and releases it once taken'},},]);- const journal = await SharedWatchAssignments.open(root);+ const journal = await AgentHostAssignments.open(root);// Released on the host's acknowledgement, so nothing is left to route again.expect(journal.pending()).toEqual([]);expect(journal.cursor).toBe(1);@@ -1392,13 +1386,7 @@ it('reports its connection and placements as they change, and why it stopped', acontrol.onHealth(({ state, detail, placements }) => heard.push({ state, detail, placements }));vi.spyOn(console, 'warn').mockImplementation(() => {});- const run = runSharedWatcher(- root,- config,- new AbortController().signal,- hosts.supervision,- control- );+ const run = runAgentHost(root, config, new AbortController().signal, hosts.supervision, control);await eventually(() => streams.length === 1);expect(control.health()).toMatchObject({ state: 'connecting', placements: {} });streams[0]!.onConnected!();@@ -1430,13 +1418,7 @@ it('reports a room connection that is turned off, and a watcher that failed', asconst hosts = sessionHosts();const control = new WatcherControl();- const run = runSharedWatcher(- root,- config,- new AbortController().signal,- hosts.supervision,- control- );+ const run = runAgentHost(root, config, new AbortController().signal, hosts.supervision, control);await eventually(() => streams.length === 1);await writeFlags(root, { enabled: false, spawn: false });await run;@@ -1445,7 +1427,7 @@ it('reports a room connection that is turned off, and a watcher that failed', asawait writeFlags(root, { enabled: true, spawn: true });await rm(join(root, 'credentials.json'));await expect(- runSharedWatcher(root, config, new AbortController().signal, hosts.supervision, control)+ runAgentHost(root, config, new AbortController().signal, hosts.supervision, control)).rejects.toThrow('credentials.json');expect(control.health().state).toBe('not-running');expect(control.health().detail).toContain('credentials.json');@@ -1485,7 +1467,7 @@ it('stops starting a session whose host failed, keeps its message, and tells itsvi.spyOn(console, 'warn').mockImplementation(() => {});const abort = new AbortController();- const run = runSharedWatcher(root, config, abort.signal, hosts.supervision, new WatcherControl());+ const run = runAgentHost(root, config, abort.signal, hosts.supervision, new WatcherControl());try {await eventually(() => streams.length === 1);const first = addressed(1, 'room');@@ -1522,7 +1504,7 @@ it('stops starting a session whose host failed, keeps its message, and tells itsexpect(calls.filter((call) => call.name === 'send_targeted_message')).toHaveLength(2);// Both messages are still owed.- expect((await SharedWatchAssignments.open(root)).pending().map((e) => e.messageId)).toEqual([+ expect((await AgentHostAssignments.open(root)).pending().map((e) => e.messageId)).toEqual(['message-1','message-2',]);@@ -1552,7 +1534,7 @@ it('tells the room without addressing anyone when the owner cannot be addressed,const error = vi.spyOn(console, 'error').mockImplementation(() => {});const abort = new AbortController();- const run = runSharedWatcher(root, config, abort.signal, hosts.supervision, new WatcherControl());+ const run = runAgentHost(root, config, abort.signal, hosts.supervision, new WatcherControl());try {await eventually(() => streams.length === 1);await streams[0]!.onEvent!(addressed(1, 'room'));@@ -1603,7 +1585,7 @@ it('tells the room once a session keeps not taking a message, instead of startinconst error = vi.spyOn(console, 'error').mockImplementation(() => {});const abort = new AbortController();- const run = runSharedWatcher(root, config, abort.signal, hosts.supervision, new WatcherControl());+ const run = runAgentHost(root, config, abort.signal, hosts.supervision, new WatcherControl());try {await eventually(() => streams.length === 1);await streams[0]!.onEvent!(addressed(1, 'room'));@@ -1623,7 +1605,7 @@ it('tells the room once a session keeps not taking a message, instead of startinawait vi.advanceTimersByTimeAsync(60_000);expect(vi.mocked(ensureSharedProcess).mock.calls.length).toBe(starts);// The message is still owed, for when the session can take it.- expect((await SharedWatchAssignments.open(root)).pending().map((e) => e.messageId)).toEqual([+ expect((await AgentHostAssignments.open(root)).pending().map((e) => e.messageId)).toEqual(['message-1',]);} finally {diff --git a/console/packages/agent-providers/src/host/shared-watcher.ts b/console/packages/agent-providers/src/host/agent-host.tssimilarity index 99%rename from console/packages/agent-providers/src/host/shared-watcher.tsrename to console/packages/agent-providers/src/host/agent-host.tsindex c730cc539..ab78b677f 100644--- a/console/packages/agent-providers/src/host/shared-watcher.ts+++ b/console/packages/agent-providers/src/host/agent-host.ts@@ -254,11 +254,11 @@ export async function stopSupersededSessions(* assignment and the routing that follows it are on disk before the stream is* allowed past the event.*/-export class SharedWatchAssignments {+export class AgentHostAssignments {private constructor(private readonly journal: Journal<WatchRecord>) {}- static async open(root: string): Promise<SharedWatchAssignments> {- return new SharedWatchAssignments(+ static async open(root: string): Promise<AgentHostAssignments> {+ return new AgentHostAssignments(await Journal.load(join(root, 'assignments.jsonl'), (value) => recordSchema.parse(value)));}@@ -452,7 +452,7 @@ export class SharedWatchAssignments {}}-export async function runSharedWatcher(+export async function runAgentHost(root: string,template: SharedHostConfig,signal: AbortSignal,@@ -517,7 +517,7 @@ export async function runSharedWatcher(return;}const credentials = await readSharedCredentials(template);- const assignments = await SharedWatchAssignments.open(root);+ const assignments = await AgentHostAssignments.open(root);const links = supervision.links;if (!links)throw new Error(diff --git a/console/packages/agent-providers/src/host/bench/daemon.ts b/console/packages/agent-providers/src/host/bench/daemon.tsindex 42b14ca40..12d472d3f 100644--- a/console/packages/agent-providers/src/host/bench/daemon.ts+++ b/console/packages/agent-providers/src/host/bench/daemon.ts@@ -23,6 +23,7 @@import { spawn } from 'node:child_process';import { mkdir, readFile } from 'node:fs/promises';import { join, resolve } from 'node:path';+import { runAgentHost } from '../agent-host';import { ensureSessions, serveControl } from '../control';import { detachedSupervision, ensureSharedProcess, inProcessSupervision } from '../launch';import { replaceOwner } from '../ownership-lock';@@ -30,7 +31,6 @@ import { ownProcessGroup } from '../process-fence';import { SessionLinks } from '../session-channel';import { sharedConfigSchema } from '../shared-config';import { hostSessionProcess } from '../shared-host';-import { runSharedWatcher } from '../shared-watcher';import { superviseSharedHost } from '../supervisor';import { WatcherControl } from '../watcher-tools';import { createBenchAdapter } from './adapter';@@ -89,9 +89,7 @@ async function main(): Promise<void> {// start it again.try {await Promise.all([- runSharedWatcher(root, config, stop.signal, supervision, control).finally(() =>- stop.abort()- ),+ runAgentHost(root, config, stop.signal, supervision, control).finally(() => stop.abort()),serveControl(resolve(root), links, ensure, control, stop.signal),]);} finally {diff --git a/console/packages/agent-providers/src/host/shared-daemon.ts b/console/packages/agent-providers/src/host/shared-daemon.tsindex 7e289e491..15615e26e 100644--- a/console/packages/agent-providers/src/host/shared-daemon.ts+++ b/console/packages/agent-providers/src/host/shared-daemon.ts@@ -2,6 +2,7 @@ import { spawn } from 'node:child_process';import { randomUUID } from 'node:crypto';import { mkdir, readFile } from 'node:fs/promises';import { join, resolve } from 'node:path';+import { runAgentHost } from './agent-host';import { ensureSessions, serveControl } from './control';import { detachedSupervision, ensureSharedProcess, inProcessSupervision } from './launch';import { replaceOwner } from './ownership-lock';@@ -11,7 +12,6 @@ import { adapterFor } from './server';import { HOST_EXIT_GRACE_MS, SessionLinks } from './session-channel';import { sharedConfigSchema } from './shared-config';import { hostSessionProcess } from './shared-host';-import { runSharedWatcher } from './shared-watcher';import { superviseSharedHost } from './supervisor';import { recordWatcherHealth } from './watcher-health-file';import { WatcherControl } from './watcher-tools';@@ -130,9 +130,7 @@ async function main(): Promise<void> {// start it again.try {await Promise.all([- runSharedWatcher(root, config, stop.signal, supervision, control).finally(() =>- stop.abort()- ),+ runAgentHost(root, config, stop.signal, supervision, control).finally(() => stop.abort()),serveControl(resolve(root), links, ensure, control, stop.signal),]);} finally {diff --git a/console/packages/agent-providers/src/index.ts b/console/packages/agent-providers/src/index.tsindex f535c15d8..57a936816 100644--- a/console/packages/agent-providers/src/index.ts+++ b/console/packages/agent-providers/src/index.ts@@ -58,7 +58,7 @@ export {} from './host/launch';export type { Supervision } from './host/launch';export { hostStartSources, type HostStartSource } from './host/session-start';-export { runSharedWatcher } from './host/shared-watcher';+export { runAgentHost } from './host/agent-host';export { clearTakenOver, readTakenOver, type TakenOver } from './host/taken-over';export {recordWatcherHealth,diff --git a/core/README.md b/core/README.mdindex 5d31f97bd..ab4325282 100644--- a/core/README.md+++ b/core/README.md@@ -2,7 +2,7 @@The Switch Core backend — the Python service that powers the Switch AI agentorchestration and governance platform. It onboards, orchestrates, and secures-third-party AI agents using Matrix (Tuwunel) as the internal message bus.+third-party AI agents, with PostgreSQL as the internal message bus.This directory is the self-contained Python project (import root `switch_core`,distribution name `switch-core`): its `pyproject.toml`, `uv.lock`, anddiff --git a/core/switch_core/agent_runs.py b/core/switch_core/agent_runs.pyindex 9560345c9..45217ff3b 100644--- a/core/switch_core/agent_runs.py+++ b/core/switch_core/agent_runs.py@@ -24,7 +24,7 @@ from sqlalchemy import func, selectfrom switch_core.addressing import can_address, parse_policyfrom switch_core.agent_refusals import AgentRefused-from switch_core.clients.admin_client import AdminClient+from switch_core.clients.actor import SystemActorfrom switch_core.clients.admin_messages import OnBehalfOffrom switch_core.clients.mentions import mention_regex, strip_emphasis@@ -452,16 +452,18 @@ class RunService:returntry:await admin.send_platform_message(- room.matrix_room_id, text, on_behalf_of=OnBehalfOf(user_id, user_name)+ room.transport_room_id,+ text,+ on_behalf_of=OnBehalfOf(user_id, user_name),)except Exception: # noqa: BLE001 - the run is running either waylogger.warning("Could not wake the agent in %s", room.id, exc_info=True)- def _admin(self, room: Room) -> AdminClient | None:+ def _admin(self, room: Room) -> SystemActor | None:if self._client_lifecycle is None:return Noneadmins = self._client_lifecycle.get_by_type("admin", room.tenant_id)- return next((c for c in admins if isinstance(c, AdminClient)), None)+ return next((c for c in admins if isinstance(c, SystemActor)), None)async def _notice(self, room: Room, text: str) -> None:"""Best effort: the state has changed whether or not the note lands."""@@ -469,6 +471,6 @@ class RunService:if admin is None:returntry:- await admin.send_notice(room.matrix_room_id, text)+ await admin.send_notice(room.transport_room_id, text)except Exception: # noqa: BLE001 - a note is not worth failing a stoplogger.warning("Could not post a run notice in %s", room.id, exc_info=True)diff --git a/core/switch_core/attachments.py b/core/switch_core/attachments.pyindex 52a32c46c..412850574 100644--- a/core/switch_core/attachments.py+++ b/core/switch_core/attachments.py@@ -1,9 +1,8 @@"""Shared constants for multi-attachment messages.-Matrix has no native way to put several files on one message: an-`m.room.message` media event carries exactly one `url`. The proposals that-would change that (MSC4274 inline media galleries, MSC2881 message-attachments) are unmerged, so Switch groups at the edges instead — a message+An `m.room.message` media event carries exactly one `url`, a shape kept from+when Switch ran on Matrix, while messaging platforms put several files on one+post. So Switch groups at the edges: a messagewith n files is sent as n media events that share a group id, and thereceiving side coalesces them back into a single logical message.diff --git a/core/switch_core/bridges/agent/api/activity_routes.py b/core/switch_core/bridges/agent/api/activity_routes.pyindex e2e8060b5..bb5a34782 100644--- a/core/switch_core/bridges/agent/api/activity_routes.py+++ b/core/switch_core/bridges/agent/api/activity_routes.py@@ -32,11 +32,11 @@ from switch_core.session_activity.service import (MAX_TEXT_CHARS,MAX_TITLE_CHARS,MAX_TOKENS,+ AgentSessionActivityService,ApprovalOption,Decision,Question,QuestionOption,- SessionActivityService,TokenSpend,)from switch_core.telemetry import TelemetryService@@ -199,7 +199,7 @@ async def report_started(async def report_activity(session_id: _Id, body: ActivityReport, agent: AuthenticatedAgent, factory: Factory) -> ActivityReceipt:- recorded = await SessionActivityService(factory).report_item(+ recorded = await AgentSessionActivityService(factory).report_item(agent.id,session_id,turn_id=body.turn_id,@@ -232,7 +232,7 @@ async def report_activity(async def open_approval(session_id: _Id, body: ApprovalOpen, agent: AuthenticatedAgent, factory: Factory) -> ApprovalView:- row = await SessionActivityService(factory).open_approval(+ row = await AgentSessionActivityService(factory).open_approval(agent.id,session_id,request_id=body.request_id,@@ -265,7 +265,7 @@ async def open_approval(async def close_approval(session_id: _Id, request_id: _Id, agent: AuthenticatedAgent, factory: Factory) -> ApprovalView:- row = await SessionActivityService(factory).close_approval(+ row = await AgentSessionActivityService(factory).close_approval(agent.id, session_id, request_id)return ApprovalView.of(row)@@ -277,7 +277,7 @@ async def close_approval(async def mark_delivered(session_id: _Id, request_id: _Id, agent: AuthenticatedAgent, factory: Factory) -> ApprovalView:- row = await SessionActivityService(factory).mark_delivered(+ row = await AgentSessionActivityService(factory).mark_delivered(agent.id, session_id, request_id)return ApprovalView.of(row)@@ -288,5 +288,5 @@ async def undelivered_outcomes(agent: AuthenticatedAgent, factory: Factory) -> list[ApprovalView]:"""Answers and expiries the agent has not acknowledged, oldest first."""- rows = await SessionActivityService(factory).undelivered_outcomes(agent.id)+ rows = await AgentSessionActivityService(factory).undelivered_outcomes(agent.id)return [ApprovalView.of(row) for row in rows]diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.pyindex 1e96064ba..700112644 100644--- a/core/switch_core/bridges/agent/api/handlers.py+++ b/core/switch_core/bridges/agent/api/handlers.py@@ -79,10 +79,10 @@ from switch_core.bridges.agent.dependencies import (get_protocol,get_session,)-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (+ AgentConnection,ClientDeclaration,Closure,- Connection,ConnectionError_,DeliveryFilter,NoStreamAttachedError,@@ -97,8 +97,8 @@ from switch_core.bridges.agent.protocol.connections import (UnknownConnectionError,evicted_session_warning,)+from switch_core.bridges.agent.protocol.agent_core import AgentCore, AgentExistsErrorfrom switch_core.bridges.agent.protocol.event_buffer import Reader-from switch_core.bridges.agent.protocol.service import AgentExistsError, ProtocolServicefrom switch_core.bridges.agent.protocol.stream import event_streamfrom switch_core.bridges.agent.registration_bootstrap import (BOOTSTRAP_KEY_TYPE,@@ -146,7 +146,7 @@ async def _resolve_registration_user_id(authorization: Annotated[str, Header()],session: Annotated[AsyncSession, Depends(get_session)],api_key_store: Annotated[ApiKeyStore, Depends(get_api_key_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> str:"""Validate the registration token in the Authorization header andreturn the user_id new agents should be owned by.@@ -198,7 +198,7 @@ def registration_path() -> str:async def register_agent_endpoint(req: RegisterAgentRequest,owner_id: Annotated[str, Depends(_resolve_registration_user_id)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> RegisterAgentResponse:try:result = await protocol.register_agent(@@ -236,7 +236,7 @@ async def _register_known(parent_agent_id: str | None,overwrite: bool,owner_id: str,- protocol: ProtocolService,+ protocol: AgentCore,) -> tuple[str, str]:"""Register one known agent, translating domain errors to HTTP errors.@@ -291,7 +291,7 @@ async def _register_known(async def register_known_agent_endpoint(req: RegisterKnownAgentRequest,owner_id: Annotated[str, Depends(_resolve_registration_user_id)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> RegisterAgentResponse:agent_id, api_key = await _register_known(agent_type=req.agent_type,@@ -312,7 +312,7 @@ async def register_known_agent_endpoint(async def register_known_agents_bulk_endpoint(req: RegisterKnownAgentBulkRequest,owner_id: Annotated[str, Depends(_resolve_registration_user_id)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],session: Annotated[AsyncSession, Depends(get_session)],) -> RegisterKnownAgentBulkResponse:"""Register many Claude Code subagents under one parent agent.@@ -416,7 +416,7 @@ async def update_agent(agent_id: str,req: UpdateAgentRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> dict[str, bool]:if agent.id != agent_id:raise HTTPException(status_code=403, detail="Not authorized for this agent")@@ -437,7 +437,7 @@ async def update_agent(async def delete_agent(agent_id: str,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> dict[str, bool]:if agent.id != agent_id:raise HTTPException(status_code=403, detail="Not authorized for this agent")@@ -459,7 +459,7 @@ async def send_message(agent_id: str,req: SendMessageRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> dict[str, object]:logger.debug("Recieved message from agent %s: %s", agent.name, req.content)try:@@ -478,14 +478,16 @@ async def send_message(async def download_media(agent_id: str,room_id: str,- mxc: Annotated[str, Query(description="The mxc:// URI of the attachment")],+ mxc: Annotated[+ str, Query(description="The media URI of the attachment (its `mxc` field)")+ ],agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> Response:- """Stream an attachment's bytes from the Matrix media repo.+ """Stream an attachment's bytes from Switch's media store.The local channel uses this to materialise inbound images to disk (it holds- only the bridge API token, not Matrix credentials).+ only the bridge API token, no other credentials)."""try:data, content_type, filename = await protocol.download_media(@@ -511,7 +513,7 @@ async def upload_media(agent_id: str,room_id: str,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],file: UploadFile | None = None,files: list[UploadFile] | None = None,caption: Annotated[str | None, Form()] = None,@@ -521,7 +523,7 @@ async def upload_media(The inverse of the GET media endpoint: the local channel (or any connectorholding the bridge API token) sends the files' bytes here; they are- uploaded to the Matrix media repo and posted to the room as+ stored in Switch's media store and posted to the room asm.image / m.file events, with optional caption and threading.Accepts either a single `file` part or repeated `files` parts. Several@@ -567,7 +569,7 @@ async def set_typing(agent_id: str,req: TypingRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> dict[str, bool]:logger.debug("Set Typing recieved %s, %s", agent.name, req.is_typing)try:@@ -584,7 +586,7 @@ async def set_typing(async def renew_role_lease(agent_id: str,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],connection_id: Annotated[str | None, Header(alias="x-switch-connection-id")] = None,) -> dict[str, bool]:"""Refresh the caller's role-lease heartbeat (room-agnostic).@@ -608,7 +610,7 @@ async def renew_connection(agent_id: str,req: ConnectionRenewRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> dict[str, bool]:"""Refresh the agent's room-scoped liveness heartbeat.@@ -630,7 +632,7 @@ async def renew_connection(async def watch_heartbeat(agent_id: str,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> dict[str, bool]:"""Refresh an auto_session connector's global "watching" heartbeat.@@ -649,7 +651,7 @@ async def update_status(agent_id: str,req: StatusRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> dict[str, bool]:if req.detail:try:@@ -667,7 +669,7 @@ async def set_runtime_state(agent_id: str,req: RuntimeStateRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> dict[str, bool]:"""Report the agent's session runtime state (working/awaiting-input/idle).@@ -701,7 +703,7 @@ async def set_runtime_state(async def poll_events(agent_id: str,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],timeout: Annotated[float, Query()] = 10,accept: Annotated[str | None, Header()] = None,connection_id: Annotated[str | None, Query()] = None,@@ -757,7 +759,7 @@ async def poll_events(def _resolve_start_cursor(- protocol: ProtocolService,+ protocol: AgentCore,agent_id: str,start_from: str,last_event_id: str | None,@@ -782,7 +784,7 @@ def _resolve_start_cursor(async def _open_event_stream(*,agent: Agent,- protocol: ProtocolService,+ protocol: AgentCore,connection_id: str | None,scope: str,event_filter: str,@@ -931,7 +933,7 @@ async def connection_beat(agent_id: str,req: ConnectionBeatRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> dict[str, Any]:"""The single per-connection heartbeat.@@ -977,10 +979,10 @@ async def connection_beat(def _current_connection(- protocol: ProtocolService,+ protocol: AgentCore,agent_id: str,req: ConnectionSubscribeRequest | ConnectionPlacementsRequest,-) -> Connection:+) -> AgentConnection:"""The connection this request may write to, or the refusal saying why not.A connection id survives a takeover, so it names the connection rather than@@ -1004,7 +1006,7 @@ async def connection_subscribe(agent_id: str,req: ConnectionSubscribeRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> dict[str, Any]:"""Claim a room on an open connection.@@ -1079,7 +1081,7 @@ async def connection_unsubscribe(agent_id: str,req: ConnectionSubscribeRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> dict[str, Any]:"""Release a room, returning coverage to any all-scope connection."""conn = _current_connection(protocol, agent.id, req)@@ -1095,7 +1097,7 @@ async def connection_placements(agent_id: str,req: ConnectionPlacementsRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> dict[str, Any]:"""Replace every session placement on an open connection.@@ -1164,7 +1166,7 @@ async def connection_placements(async def poll_notifications(agent_id: str,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],timeout: Annotated[float, Query()] = 10,) -> EventResponse | Response:"""Long-poll the agent's notification stream across all its rooms.@@ -1185,7 +1187,7 @@ async def poll_room_events(agent_id: str,room_id: str,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],timeout: Annotated[float, Query()] = 10,) -> EventResponse | Response:try:@@ -1205,7 +1207,7 @@ async def get_room_history(agent_id: str,room_id: str,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],since: Annotated[str | None,Query(description="ISO 8601 timestamp — return events from this point forward"),@@ -1259,7 +1261,7 @@ async def get_room_history(async def list_participants(room_id: str,_agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> ParticipantsResponse:try:participants_desc = await protocol.list_participants(room_id)@@ -1287,7 +1289,7 @@ async def delegate_task(agent_id: str,req: DelegateTaskRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> DelegateTaskResponse:# TODO: do we still need this ?if agent.id != agent_id:@@ -1319,7 +1321,7 @@ async def accept_task(agent_id: str,req: AcceptTaskRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> TaskInfo:if agent.id != agent_id:raise HTTPException(status_code=403, detail="Not authorized for this agent")@@ -1340,7 +1342,7 @@ async def cancel_task(agent_id: str,req: CancelTaskRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> TaskInfo:if agent.id != agent_id:raise HTTPException(status_code=403, detail="Not authorized for this agent")@@ -1360,7 +1362,7 @@ async def cancel_task(async def list_tasks(agent_id: str,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],room_id: Annotated[str | None, Query()] = None,role: Annotated[str | None, Query(description="'delegated' or 'assigned'")] = None,status: Annotated[str | None, Query()] = None,@@ -1379,7 +1381,7 @@ async def get_task(agent_id: str,task_id: str,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> TaskInfo:if agent.id != agent_id:raise HTTPException(status_code=403, detail="Not authorized for this agent")@@ -1398,7 +1400,7 @@ async def get_task(async def list_task_agents(agent_id: str,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],room_id: Annotated[str, Query()],) -> TaskAgentsResponse:if agent.id != agent_id:@@ -1424,7 +1426,7 @@ async def update_task(agent_id: str,req: UpdateTaskRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> TaskInfo:if agent.id != agent_id:raise HTTPException(status_code=403, detail="Not authorized for this agent")@@ -1445,7 +1447,7 @@ async def finalise_task(agent_id: str,req: FinaliseTaskRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> TaskInfo:if agent.id != agent_id:raise HTTPException(status_code=403, detail="Not authorized for this agent")@@ -1469,7 +1471,7 @@ async def report_events(agent_id: str,req: ReportEventsRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> Response:if agent.id != agent_id:raise HTTPException(status_code=403, detail="Not authorized for this agent")@@ -1492,7 +1494,7 @@ async def pre_tool_call(agent_id: str,req: PreToolCallRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> PreToolCallResponse:if agent.id != agent_id:raise HTTPException(status_code=403, detail="Not authorized for this agent")@@ -1517,7 +1519,7 @@ async def pre_llm_request(agent_id: str,req: PreLlmRequestRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> PreLlmRequestResponse:if agent.id != agent_id:raise HTTPException(status_code=403, detail="Not authorized for this agent")@@ -1542,7 +1544,7 @@ async def post_tool_result(agent_id: str,req: PostToolResultRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> PostToolResultResponse:if agent.id != agent_id:raise HTTPException(status_code=403, detail="Not authorized for this agent")@@ -1567,7 +1569,7 @@ async def post_llm_response(agent_id: str,req: PostLlmResponseRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> PostLlmResponseResponse:if agent.id != agent_id:raise HTTPException(status_code=403, detail="Not authorized for this agent")@@ -1595,7 +1597,7 @@ async def create_room(agent_id: str,req: CreateModerationRoomRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> CreateModerationRoomResponse:if agent.id != agent_id:raise HTTPException(status_code=403, detail="Not authorized for this agent")@@ -1632,8 +1634,8 @@ async def create_room(return CreateModerationRoomResponse(id=result.room.id,name=result.room.name,- transport_room_id=result.room.matrix_room_id,- matrix_room_id=result.room.matrix_room_id,+ transport_room_id=result.room.transport_room_id,+ matrix_room_id=result.room.transport_room_id,failed_attachments=result.failed_attachments,)@@ -1644,7 +1646,7 @@ async def invite_agent(room_id: str,req: InviteAgentRequest,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> dict[str, bool]:if agent.id != agent_id:raise HTTPException(status_code=403, detail="Not authorized for this agent")@@ -1662,7 +1664,7 @@ async def invite_agent(async def list_rooms(agent_id: str,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> RoomListResponse:if agent.id != agent_id:raise HTTPException(status_code=403, detail="Not authorized for this agent")@@ -1678,7 +1680,7 @@ async def get_room(agent_id: str,room_id: str,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> RoomDetailResponse:if agent.id != agent_id:raise HTTPException(status_code=403, detail="Not authorized for this agent")@@ -1702,7 +1704,7 @@ async def get_room(async def list_agents(agent_id: str,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> AgentListResponse:if agent.id != agent_id:raise HTTPException(status_code=403, detail="Not authorized for this agent")@@ -1725,7 +1727,7 @@ async def list_agents(async def list_bridges(agent_id: str,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> ListBridgesResponse:if agent.id != agent_id:raise HTTPException(status_code=403, detail="Not authorized for this agent")diff --git a/core/switch_core/bridges/agent/api/operations.py b/core/switch_core/bridges/agent/api/operations.pyindex 53fc928c9..a4cfb0298 100644--- a/core/switch_core/bridges/agent/api/operations.py+++ b/core/switch_core/bridges/agent/api/operations.py@@ -19,6 +19,7 @@ from __future__ import annotationsimport inspectimport logging+import timefrom typing import Annotated, Anyfrom fastapi import APIRouter, Depends, Header, HTTPException@@ -32,10 +33,16 @@ from switch_core.bridges.agent.operations.callctx import (CallerSession,call_context,)-from switch_core.bridges.agent.protocol.connections import UnknownConnectionError-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_connections import UnknownConnectionError+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.budgets import BudgetExceededfrom switch_core.db.models import Agent+from switch_core.observability.catalogue import (+ BRIDGE_CALL_DURATION,+ BRIDGE_ERRORS,+ BRIDGE_EVENTS_IN,+)+from switch_core.observability.metrics import metricslogger = logging.getLogger(__name__)@@ -110,13 +117,32 @@ async def call_operation(if missing:raise BadArgumentsError(f"{operation} requires: {', '.join(missing)}")+ # The agent bridge's side of `switch.bridge.*`: every operation an agent+ # calls is an event in, timed as a call, and counted as an error when it+ # raises. `event` is the operation's name, bounded by the registry.+ metrics().increment(+ BRIDGE_EVENTS_IN, {"bridge": "agent", "platform": "switch", "event": operation}+ )+ started = time.perf_counter()with call_context(CallContext(agent_id=agent_id, session_key=connection_id, session=session)):- result = fn(**call_args)- if inspect.isawaitable(result):- result = await result- return result+ try:+ result = fn(**call_args)+ if inspect.isawaitable(result):+ result = await result+ except Exception:+ metrics().increment(+ BRIDGE_ERRORS,+ {"bridge": "agent", "platform": "switch", "direction": "inbound"},+ )+ raise+ metrics().observe(+ BRIDGE_CALL_DURATION,+ {"bridge": "agent", "platform": "switch", "kind": operation},+ (time.perf_counter() - started) * 1000.0,+ )+ return result# ── HTTP router ──────────────────────────────────────────────────────────────@@ -132,7 +158,7 @@ SESSION_SELECTOR_HEADERS = (async def resolve_caller(*,agent_id: str,- protocol: ProtocolService,+ protocol: AgentCore,factory: async_sessionmaker[AsyncSession],connection_id: str | None,session_id: str | None,@@ -198,7 +224,7 @@ async def post_operation(agent_id: str,operation: str,agent: Annotated[Agent, Depends(get_agent_from_scope)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],factory: Annotated[async_sessionmaker[AsyncSession], Depends(get_session_factory)],body: dict[str, Any] | None = None,connection_id: Annotated[str | None, Header(alias="x-switch-connection-id")] = None,diff --git a/core/switch_core/bridges/agent/api/session_reporter.py b/core/switch_core/bridges/agent/api/session_reporter.pyindex 26e8e9a6f..861feb959 100644--- a/core/switch_core/bridges/agent/api/session_reporter.py+++ b/core/switch_core/bridges/agent/api/session_reporter.py@@ -16,11 +16,11 @@ import asyncioimport loggingimport time-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (HEARTBEAT_TTL_SECONDS,+ AgentConnection,+ AgentConnectionRegistry,CloseCode,- Connection,- ConnectionRegistry,)from switch_core.db.models import Agentfrom switch_core.telemetry import TelemetryService, emit_safely@@ -56,17 +56,17 @@ class SessionReporter:def __init__(self,telemetry: TelemetryService | None,- connections: ConnectionRegistry | None = None,+ connections: AgentConnectionRegistry | None = None,) -> None:self._telemetry = telemetryself._connections = connections- # Connection ids whose stream was actually handed back. A connection+ # AgentConnection ids whose stream was actually handed back. A connection# closed before that — a rejected room claim — is not part of any# session and must not end one.self._streaming: set[str] = set()self._sessions: dict[str, _Session] = {}- async def started(self, agent: Agent, conn: Connection) -> None:+ async def started(self, agent: Agent, conn: AgentConnection) -> None:"""A stream is about to be returned on `conn`."""self._streaming.add(conn.id)session = self._sessions.get(conn.agent_id)@@ -89,7 +89,7 @@ class SessionReporter:"first_session_started", known_agent_type=runtime)- def on_close(self, conn: Connection) -> None:+ def on_close(self, conn: AgentConnection) -> None:"""The registry's close listener, for every path that closes."""if conn.id not in self._streaming:# A refused room claim closed it on the way out; nothing began.diff --git a/core/switch_core/bridges/agent/api_key_cache.py b/core/switch_core/bridges/agent/api_key_cache.pyindex 73e2d7de1..4cc5efc35 100644--- a/core/switch_core/bridges/agent/api_key_cache.py+++ b/core/switch_core/bridges/agent/api_key_cache.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport timefrom collections import OrderedDict-from switch_core.bridges.agent.protocol.connections import HEARTBEAT_TTL_SECONDS+from switch_core.bridges.agent.protocol.agent_connections import HEARTBEAT_TTL_SECONDSfrom switch_core.db.models import Agent, ApiKeydiff --git a/core/switch_core/bridges/agent/app.py b/core/switch_core/bridges/agent/app.pyindex 2ada9cb08..123320878 100644--- a/core/switch_core/bridges/agent/app.py+++ b/core/switch_core/bridges/agent/app.py@@ -5,6 +5,7 @@ import loggingfrom fastapi import FastAPI, HTTPException, Requestfrom fastapi.exceptions import RequestValidationErrorfrom fastapi.responses import JSONResponse+from starlette.types import ASGIApp, Receive, Scope, Sendfrom switch_core.bridges.agent.api.activity_routes import router as activity_routerfrom switch_core.bridges.agent.api.handlers import router as api_router@@ -15,9 +16,9 @@ from switch_core.bridges.agent.auth import BearerAuthMiddlewarefrom switch_core.bridges.agent.deeplink import router as deeplink_routerfrom switch_core.bridges.agent.dependencies import get_protocol, init_dependenciesfrom switch_core.bridges.agent.mcp import create_mcp_app-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.event_buffer import EventBuffer-from switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.collaboration.lifecycle_service import (CollaborationBridgeLifecycleService,)@@ -31,6 +32,7 @@ from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgefrom switch_core.db.stores.external_user_store import ExternalUserStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.task_store import TaskStore+from switch_core.logging_context import log_contextfrom switch_core.observability.http import MetricsMiddlewarefrom switch_core.request_context import RequestContextMiddlewarefrom switch_core.room_service import RoomService@@ -59,15 +61,15 @@ def create_agent_bridge_app(session_factory: object,config: SwitchConfig,approval_outcomes: ApprovalOutcomes,- connections: ConnectionRegistry | None = None,+ connections: AgentConnectionRegistry | None = None,telemetry: TelemetryService | None = None,-) -> tuple[FastAPI, ProtocolService]:+) -> tuple[FastAPI, AgentCore]:# One registry for the whole process: the live connection set is the source# of truth for reachability, so every service must see the same one. The- # caller may supply it — main.py does, because the Matrix agent clients are+ # caller may supply it, and main.py does, because the agent clients are# wired before this app is built and read presence from the same registry.if connections is None:- connections = ConnectionRegistry()+ connections = AgentConnectionRegistry()# One cache for the whole process, for the same reason as `connections`:# the HTTP door and the MCP door each carry their own auth middleware, and@@ -164,8 +166,33 @@ def create_agent_bridge_app(# is still counted and timed — an authentication failure is traffic, and a# spike of it is the thing you most want a dashboard to show.app.add_middleware(MetricsMiddleware)+ # Tags every log line of an agent request as the agent bridge's, as a+ # field. Only agent paths: the gateway is mounted on this same app.+ app.add_middleware(AgentBridgeLogContextMiddleware)# Added last, so it wraps the bearer middleware: a request rejected for bad# credentials is logged with a request id like any other.app.add_middleware(RequestContextMiddleware)return app, protocol+++class AgentBridgeLogContextMiddleware:+ """Binds `bridge="agent"` for requests to the agent bridge's own paths.++ Pure ASGI rather than `BaseHTTPMiddleware`, so the binding covers a+ streamed response (the SSE stream) for as long as it runs, and is reset in+ the same context it was set in.+ """++ _PREFIXES = ("/agents", "/mcp")++ def __init__(self, app: ASGIApp) -> None:+ self.app = app++ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:+ path = scope.get("path", "") if scope["type"] in ("http", "websocket") else ""+ if not path.startswith(self._PREFIXES):+ await self.app(scope, receive, send)+ return+ with log_context(bridge="agent"):+ await self.app(scope, receive, send)diff --git a/core/switch_core/bridges/agent/commands.py b/core/switch_core/bridges/agent/commands.pyindex ab07ca9be..df3e89a51 100644--- a/core/switch_core/bridges/agent/commands.py+++ b/core/switch_core/bridges/agent/commands.py@@ -27,8 +27,8 @@ from switch_core.gateway.known_agents import known_agent_forfrom switch_core.transport import RoomRefif TYPE_CHECKING:- from switch_core.clients.admin_client import AdminClient- from switch_core.clients.agent_client import AgentClient+ from switch_core.clients.agent_consumer import AgentConsumer+ from switch_core.clients.command_consumer import CommandConsumerfrom switch_core.clients.room_meta import RoomMetafrom switch_core.db.models import Agent@@ -46,23 +46,25 @@ AGENT_GREETINGS = ["Hi there! Just @{name} me when you're ready.",]-CommandHandler = Callable[["AgentClient", RoomRef, CommandEvent, bool], Awaitable[None]]+CommandHandler = Callable[+ ["AgentConsumer", RoomRef, CommandEvent, bool], Awaitable[None]+]# (client, args, room_id) -> whether THIS agent is addressed by the command.# Targeting is a per-command policy (see Command.addressed) rather than a fixed# rule in on_command, so a command like `run-cmd` can interpret its args its# own way.-CommandTargeting = Callable[["AgentClient", str, str], Awaitable[bool]]+CommandTargeting = Callable[["AgentConsumer", str, str], Awaitable[bool]]# (host, room, event, meta) -> None. An admin-side usage check run by the# always-present admin client BEFORE agents act on a command. It posts a# system message when the command is misused (bad/missing target) and does# nothing when usage is valid; it never executes the command itself.CommandAdminCheck = Callable[- ["AdminClient", RoomRef, CommandEvent, "RoomMeta"], Awaitable[None]+ ["CommandConsumer", RoomRef, CommandEvent, "RoomMeta"], Awaitable[None]]async def _addressed_by_name_or_role(- client: AgentClient, args: str, room_id: str+ client: AgentConsumer, args: str, room_id: str) -> bool:"""Default command targeting.@@ -81,7 +83,7 @@ async def _addressed_by_name_or_role(async def _addressed_by_first_mention(- client: AgentClient, args: str, room_id: str+ client: AgentConsumer, args: str, room_id: str) -> bool:"""Targeting for `run-cmd`: only the FIRST `@token` addresses an agent (byname or by a role it holds). Any further `@token` is data for the handler@@ -97,7 +99,7 @@ async def _addressed_by_first_mention(async def _addressed_by_required_first_mention(- client: AgentClient, args: str, room_id: str+ client: AgentConsumer, args: str, room_id: str) -> bool:"""Like `_addressed_by_first_mention`, but a missing target addresses NOONE. Used by `!reset`, where a bare `!reset` must not silently reset every@@ -110,14 +112,14 @@ async def _addressed_by_required_first_mention(return await _first_token_is_me(client, tokens[0], room_id)-async def _addressed_everyone(client: AgentClient, args: str, room_id: str) -> bool:+async def _addressed_everyone(client: AgentConsumer, args: str, room_id: str) -> bool:"""Targeting for room-wide control commands (`!reset-all-agents`): everyagent is addressed regardless of args, so the command always fans out tothe whole room."""return True-async def _first_token_is_me(client: AgentClient, first: str, room_id: str) -> bool:+async def _first_token_is_me(client: AgentConsumer, first: str, room_id: str) -> bool:"""Whether `@first` names this agent — by name, room alias, or a held role."""if client._args_tag_my_name(f"@{first}"):return True@@ -128,7 +130,7 @@ async def _first_token_is_me(client: AgentClient, first: str, room_id: str) -> basync def _check_control_target(- host: AdminClient, room: RoomRef, event: CommandEvent, meta: RoomMeta+ host: CommandConsumer, room: RoomRef, event: CommandEvent, meta: RoomMeta) -> None:"""Admin-side usage feedback for a target-required control command.@@ -347,7 +349,7 @@ def _control_frame(}-async def _room_surface(client: AgentClient, room_id: str) -> str:+async def _room_surface(client: AgentConsumer, room_id: str) -> str:"""The platform a room is bridged to, as a contract surface."""async with client.session_factory() as db:room = await db.get(Room, room_id)@@ -360,7 +362,7 @@ async def _room_surface(client: AgentClient, room_id: str) -> str:async def _reply(- client: AgentClient | AdminClient,+ client: AgentConsumer | CommandConsumer,room: RoomRef,event: CommandEvent,body: str,@@ -384,7 +386,7 @@ async def _reply(async def _cmd_help(- client: AgentClient, room: RoomRef, event: CommandEvent, _is_direct: bool+ client: AgentConsumer, room: RoomRef, event: CommandEvent, _is_direct: bool) -> None:lines = ["**Available commands:**"]for cmd in COMMANDS:@@ -395,7 +397,7 @@ async def _cmd_help(async def _dispatch_control_command(- client: AgentClient,+ client: AgentConsumer,room: RoomRef,event: CommandEvent,command: str,@@ -535,7 +537,7 @@ async def _dispatch_control_command(async def _cmd_reset(- client: AgentClient, room: RoomRef, event: CommandEvent, _is_direct: bool+ client: AgentConsumer, room: RoomRef, event: CommandEvent, _is_direct: bool) -> None:await _dispatch_control_command(client,@@ -556,7 +558,7 @@ async def _cmd_reset(async def _cmd_compact(- client: AgentClient, room: RoomRef, event: CommandEvent, _is_direct: bool+ client: AgentConsumer, room: RoomRef, event: CommandEvent, _is_direct: bool) -> None:await _dispatch_control_command(client,@@ -576,7 +578,7 @@ async def _cmd_compact(async def _cmd_interrupt(- client: AgentClient, room: RoomRef, event: CommandEvent, _is_direct: bool+ client: AgentConsumer, room: RoomRef, event: CommandEvent, _is_direct: bool) -> None:await _dispatch_control_command(client,@@ -596,7 +598,7 @@ async def _cmd_interrupt(async def _cmd_list_room_agents(- client: AgentClient,+ client: AgentConsumer,room: RoomRef,event: CommandEvent,_is_direct: bool,@@ -624,7 +626,7 @@ async def _cmd_list_room_agents(async def _cmd_list_aliases(- client: AgentClient,+ client: AgentConsumer,room: RoomRef,event: CommandEvent,_is_direct: bool,@@ -656,7 +658,7 @@ async def _cmd_list_aliases(async def _cmd_set_alias(- client: AgentClient,+ client: AgentConsumer,room: RoomRef,event: CommandEvent,_is_direct: bool,@@ -726,7 +728,7 @@ async def _cmd_set_alias(async def _cmd_remove_alias(- client: AgentClient,+ client: AgentConsumer,room: RoomRef,event: CommandEvent,_is_direct: bool,@@ -778,7 +780,7 @@ async def _cmd_remove_alias(async def _cmd_invite(- client: AgentClient,+ client: AgentConsumer,room: RoomRef,event: CommandEvent,_is_direct: bool,@@ -824,11 +826,11 @@ async def _cmd_invite(return# `invite-agent` is admin-owned, so only the always-present admin client- # runs this handler — the `room_service` reference lives on AdminClient.+ # runs this handler — the `room_service` reference lives on CommandConsumer.# Reuse `add_agents_to_room` (the same path as the `invite_agent_to_room`- # MCP tool) so the agent is invited to Matrix AND added to any bridged+ # MCP tool) so the agent is invited to the room AND added to any bridged# channel.- await cast("AdminClient", client)._room_service.add_agents_to_room(+ await cast("CommandConsumer", client)._room_service.add_agents_to_room(meta.room_id, agent_names=[target.name])await _reply(@@ -897,7 +899,7 @@ def _format_status_lines(async def _cmd_status(- client: AgentClient,+ client: AgentConsumer,room: RoomRef,event: CommandEvent,_is_direct: bool,@@ -939,7 +941,7 @@ async def _cmd_status(async def _cmd_roles(- client: AgentClient,+ client: AgentConsumer,room: RoomRef,event: CommandEvent,_is_direct: bool,@@ -977,7 +979,7 @@ async def _cmd_roles(async def _cmd_list_documents(- client: AgentClient,+ client: AgentConsumer,room: RoomRef,event: CommandEvent,_is_direct: bool,@@ -1023,7 +1025,7 @@ async def _cmd_list_documents(async def _cmd_list_references(- client: AgentClient,+ client: AgentConsumer,room: RoomRef,event: CommandEvent,_is_direct: bool,@@ -1059,7 +1061,7 @@ async def _cmd_list_references(async def _cmd_room_url(- client: AgentClient,+ client: AgentConsumer,room: RoomRef,event: CommandEvent,_is_direct: bool,@@ -1086,7 +1088,7 @@ async def _cmd_room_url(async def _cmd_list_all_agents(- client: AgentClient,+ client: AgentConsumer,room: RoomRef,event: CommandEvent,_is_direct: bool,@@ -1118,7 +1120,7 @@ def _role_arg(args: str) -> str | None:async def _cmd_run_cmd(- client: AgentClient,+ client: AgentConsumer,room: RoomRef,event: CommandEvent,_is_direct: bool,@@ -1179,7 +1181,7 @@ async def _cmd_run_cmd(async def _cmd_agents_greet(- client: AgentClient,+ client: AgentConsumer,room: RoomRef,event: CommandEvent,is_direct: bool,@@ -1387,7 +1389,7 @@ COMMANDS_BY_NAME: dict[str, Command] = {cmd.name: cmd for cmd in COMMANDS}async def dispatch_command(- client: AgentClient, room: RoomRef, event: CommandEvent, is_direct: bool+ client: AgentConsumer, room: RoomRef, event: CommandEvent, is_direct: bool) -> bool:"""Runs a command.@@ -1412,7 +1414,7 @@ async def dispatch_command(async def dispatch_admin_command(- host: AdminClient, room: RoomRef, event: CommandEvent+ host: CommandConsumer, room: RoomRef, event: CommandEvent) -> None:"""Run an admin-owned command on the admin client.@@ -1437,4 +1439,4 @@ async def dispatch_admin_command(is_direct = await host._is_direct_room(room.room_id)# Admin-owned handlers use only the store/reply surface both clients share# (never `.agent`), so the admin host satisfies the handler's contract.- await cmd.handler(cast("AgentClient", host), room, event, is_direct)+ await cmd.handler(cast("AgentConsumer", host), room, event, is_direct)diff --git a/core/switch_core/bridges/agent/dependencies.py b/core/switch_core/bridges/agent/dependencies.pyindex 230fc3ee8..fc47b3d0f 100644--- a/core/switch_core/bridges/agent/dependencies.py+++ b/core/switch_core/bridges/agent/dependencies.py@@ -6,9 +6,9 @@ from typing import TYPE_CHECKING, Any, castfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.agent.api_key_cache import ApiKeyCache-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.event_buffer import EventBuffer-from switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.collaboration.lifecycle_service import (CollaborationBridgeLifecycleService,)@@ -44,7 +44,7 @@ def init_dependencies(client_lifecycle: ClientLifecycleService,collab_lifecycle: CollaborationBridgeLifecycleService,event_buffer: EventBuffer,- connections: ConnectionRegistry,+ connections: AgentConnectionRegistry,task_store: TaskStore,resource_service: ResourceService,api_key_store: ApiKeyStore,@@ -75,7 +75,7 @@ def init_dependencies(_state["telemetry"] = telemetry_state["session_start_limiter"] = default_session_start_limiter()- _state["protocol"] = ProtocolService(+ _state["protocol"] = AgentCore(agent_store=agent_store,agent_session_store=agent_session_store,room_store=room_store,@@ -146,7 +146,7 @@ def get_config() -> SwitchConfig:return _state["config"] # type: ignore[no-any-return]-def get_protocol() -> ProtocolService:+def get_protocol() -> AgentCore:return _state["protocol"] # type: ignore[no-any-return]diff --git a/core/switch_core/bridges/agent/mcp/server.py b/core/switch_core/bridges/agent/mcp/server.pyindex 93707c49b..7a26f7d85 100644--- a/core/switch_core/bridges/agent/mcp/server.py+++ b/core/switch_core/bridges/agent/mcp/server.py@@ -27,7 +27,7 @@ from switch_core.bridges.agent.operations.callctx import CallContext, call_contefrom switch_core.bridges.agent.operations.context import init_operations_protocolif TYPE_CHECKING:- from switch_core.bridges.agent.protocol.service import ProtocolService+ from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.config import SwitchConfigfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStore@@ -35,7 +35,7 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)-def init_mcp_protocol(protocol: ProtocolService) -> None:+def init_mcp_protocol(protocol: AgentCore) -> None:"""Give the operations layer its protocol service.Kept under the old name because callers wire it at startup; the state it@@ -90,7 +90,7 @@ def create_mcp_app(*,agent_store: AgentStore,api_key_store: ApiKeyStore,- protocol: ProtocolService,+ protocol: AgentCore,config: SwitchConfig,) -> tuple[ASGIApp, Any]:"""Returns (asgi_app, lifespan). The lifespan must be wired into the parent app."""diff --git a/core/switch_core/bridges/agent/operations/context.py b/core/switch_core/bridges/agent/operations/context.pyindex 4bd2882ca..a6a50a02a 100644--- a/core/switch_core/bridges/agent/operations/context.py+++ b/core/switch_core/bridges/agent/operations/context.py@@ -18,19 +18,19 @@ from switch_core.bridges.agent.operations.callctx import (from switch_core.bridges.agent.protocol.event_buffer import Readerif TYPE_CHECKING:- from switch_core.bridges.agent.protocol.service import ProtocolService+ from switch_core.bridges.agent.protocol.agent_core import AgentCorelogger = logging.getLogger(__name__)-_protocol: ProtocolService | None = None+_protocol: AgentCore | None = None-def init_operations_protocol(protocol: ProtocolService) -> None:+def init_operations_protocol(protocol: AgentCore) -> None:global _protocol_protocol = protocol-def get_protocol() -> ProtocolService:+def get_protocol() -> AgentCore:assert _protocol is not None, "operations protocol not initialized"return _protocoldiff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.pyindex 1cfd9af0f..5bd13a659 100644--- a/core/switch_core/bridges/agent/operations/definitions.py+++ b/core/switch_core/bridges/agent/operations/definitions.py@@ -32,12 +32,12 @@ from switch_core.bridges.agent.operations.context import (sole_connected_room,)from switch_core.bridges.agent.operations.registry import operation-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (ConnectionError_,evicted_session_warning,)+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.instructions import build_room_instructions-from switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.agent.protocol.types import IntegrationProfilefrom switch_core.db.models import CollaborationBridge, Userfrom switch_core.db.stores.template_store import TemplateStore@@ -48,7 +48,7 @@ logger = logging.getLogger(__name__)def claim_room_on_caller_connection(- protocol: ProtocolService, agent_id: str, connection_id: str, room_id: str+ protocol: AgentCore, agent_id: str, connection_id: str, room_id: str) -> str | None:"""Bind the room to the connection that asked to connect.@@ -111,7 +111,7 @@ def claim_room_on_caller_connection(def rooms_on_caller_connection(- protocol: ProtocolService, agent_id: str, connection_id: str+ protocol: AgentCore, agent_id: str, connection_id: str) -> set[str]:"""The rooms claimed by the connection underneath this caller.@@ -126,7 +126,7 @@ def rooms_on_caller_connection(def release_room_on_caller_connection(- protocol: ProtocolService, agent_id: str, connection_id: str, room_id: str+ protocol: AgentCore, agent_id: str, connection_id: str, room_id: str) -> None:"""Drop a room the caller has left from the connection underneath it.@@ -143,7 +143,7 @@ def release_room_on_caller_connection(async def bind_room_for_connectionless_caller(- protocol: ProtocolService,+ protocol: AgentCore,*,agent_id: str,connection_id: str,@@ -225,8 +225,8 @@ async def connect_to_room(Args:room_id: The Switch room id (UUID string) to connect to. Get valid- ids from list_rooms. This is the Switch room id, not the Matrix- room id. Calling again switches the active room for this session.+ ids from list_rooms. This is the Switch room id, not the+ transport room id. Calling again switches the active room for this session.include_general_instructions: When true (default) the `instructions`field carries the full room-onboarding text (interaction modes,task protocol, agent statuses, room setup) followed by any@@ -395,7 +395,7 @@ def _eviction_warning(async def _decorate_linked_rooms(- protocol: ProtocolService,+ protocol: AgentCore,agent_id: str,linked_rooms: list[dict[str, Any]],) -> list[dict[str, Any]]:@@ -644,8 +644,9 @@ async def read_context(Args:limit: Maximum number of timeline entries to return (default 50),- grouped into threads. History is paged from the homeserver until- this many are collected or the room's start is reached.+ grouped into threads. History is read from the room's stored+ messages until this many are collected or the room's start is+ reached.since: ISO-8601 timestamp string (e.g. "2026-05-20T20:55:00Z"). Onlyentries at or after this time are returned. Use this when an eventarrives to fetch just the recent context — pass a timestamp a few@@ -740,7 +741,7 @@ async def post_message(body: str, thread_id: str | None = None) -> dict[str, strthread_id.Returns:- {"event_id": "<matrix event id>"} for the posted message.+ {"event_id": "<event id>"} for the posted message."""agent_id = get_agent_id()room_id = await require_connected_room()@@ -788,7 +789,7 @@ async def send_targeted_message(At least one of target_names / target_roles is required.Returns:- {"event_id": "<matrix event id>", "target_statuses": {name: status}}.+ {"event_id": "<event id>", "target_statuses": {name: status}}.`target_statuses` reports each addressed *agent*'s reachability at sendtime — for a role target, that is each of its live holders: `live`(will receive immediately), `awaiting_manual_poll` (must read context@@ -1170,9 +1171,9 @@ async def create_room(return {"id": result.room.id,"name": result.room.name,- "transport_room_id": result.room.matrix_room_id,+ "transport_room_id": result.room.transport_room_id,# Deprecated alias, carried for the connector compatibility window.- "matrix_room_id": result.room.matrix_room_id,+ "matrix_room_id": result.room.transport_room_id,"failed_attachments": result.failed_attachments,}@@ -2270,7 +2271,7 @@ async def archive_room(room_id: str) -> dict[str, Any]:"""Archive a room you are a member of, hiding it from the default activeroom lists once its work is complete.- Archiving is metadata-only and fully reversible: the Matrix room, its+ Archiving is metadata-only and fully reversible: the room, itsmembers, and any bridge channel are left intact, and the room can stillbe connected to and read. It simply stops appearing in `list_rooms` /`list_all_rooms` (and the management UI) unless archived rooms arediff --git a/core/switch_core/bridges/agent/protocol/connections.py b/core/switch_core/bridges/agent/protocol/agent_connections.pysimilarity index 96%rename from core/switch_core/bridges/agent/protocol/connections.pyrename to core/switch_core/bridges/agent/protocol/agent_connections.pyindex ae7d48c05..db07a20a2 100644--- a/core/switch_core/bridges/agent/protocol/connections.py+++ b/core/switch_core/bridges/agent/protocol/agent_connections.py@@ -393,7 +393,7 @@ class TooManyConnectionsError(ConnectionError_):@dataclass-class Connection:+class AgentConnection:id: stragent_id: strscope: Scope@@ -434,17 +434,17 @@ class Connection:return self.closure is None and (now - self.last_beat) < HEARTBEAT_TTL_SECONDS-class ConnectionRegistry:+class AgentConnectionRegistry:"""The live set of agent connections. Authoritative, in memory."""def __init__(self) -> None:- # Called with every Connection this registry closes, whoever closed it.+ # Called with every AgentConnection this registry closes, whoever closed it.# A callback rather than a report at each call site: `close` is reached# from five places — the sweep, the stale-connection check, the stream,# and two room-claim failures — and a sixth added later would silently# report nothing. The registry stays unaware of what the callback does.- self._on_close: Callable[[Connection], None] = lambda conn: None- self._by_id: dict[str, Connection] = {}+ self._on_close: Callable[[AgentConnection], None] = lambda conn: None+ self._by_id: dict[str, AgentConnection] = {}self._by_agent: dict[str, set[str]] = {}self._slot_locks: dict[str, tuple[asyncio.Lock, int]] = {}# Incarnations are drawn from here, never from the connection, so a@@ -492,7 +492,7 @@ class ConnectionRegistry:cursor: int,declaration: ClientDeclaration,expected_generation: int | None,- ) -> Connection:+ ) -> AgentConnection:"""Open a connection, or reattach to one the client already owns.The client chooses the id, which makes opening idempotent: a timed-out@@ -569,7 +569,7 @@ class ConnectionRegistry:raise TooManyConnectionsError(agent_id, MAX_CONNECTIONS_PER_AGENT)now = time.monotonic()- conn = Connection(+ conn = AgentConnection(id=connection_id,agent_id=agent_id,scope=scope,@@ -600,7 +600,7 @@ class ConnectionRegistry:)return conn- def detach_stream(self, conn: Connection, generation: int) -> None:+ def detach_stream(self, conn: AgentConnection, generation: int) -> None:"""Mark the stream gone while leaving the connection alive.Only the generation that is currently attached may detach: a superseded@@ -615,7 +615,7 @@ class ConnectionRegistry:conn.id,)- def set_close_listener(self, listener: Callable[[Connection], None]) -> None:+ def set_close_listener(self, listener: Callable[[AgentConnection], None]) -> None:"""Observe every connection this registry closes.One listener, set once at wiring time. It must not raise — a bad@@ -625,7 +625,7 @@ class ConnectionRegistry:"""self._on_close = listener- def close(self, connection_id: str, closure: Closure) -> Connection | None:+ def close(self, connection_id: str, closure: Closure) -> AgentConnection | None:conn = self._by_id.pop(connection_id, None)if conn is None:return None@@ -674,7 +674,7 @@ class ConnectionRegistry:)return conn- def sweep(self) -> list[Connection]:+ def sweep(self) -> list[AgentConnection]:"""Close connections whose heartbeat has lapsed. Returns those closed."""now = time.monotonic()stale = [@@ -703,7 +703,7 @@ class ConnectionRegistry:connection_id: str,cursor: int,generation: int | None,- ) -> Connection:+ ) -> AgentConnection:"""Record a client tick and its cursor.Rejects a tick for a connection with no stream: the client is alive but@@ -746,7 +746,7 @@ class ConnectionRegistry:conn.cursor = cursorreturn conn- def require(self, agent_id: str, connection_id: str) -> Connection:+ def require(self, agent_id: str, connection_id: str) -> AgentConnection:conn = self._by_id.get(connection_id)if conn is None or conn.agent_id != agent_id:raise UnknownConnectionError(connection_id)@@ -757,7 +757,7 @@ class ConnectionRegistry:def require_current(self, agent_id: str, connection_id: str, *, generation: int | None- ) -> Connection:+ ) -> AgentConnection:"""Resolve a connection the caller must still be the client on.`require` answers "does this connection exist", which is the wrong@@ -788,7 +788,7 @@ class ConnectionRegistry:return conn@staticmethod- def _fenced_holder(conn: Connection) -> int | None:+ def _fenced_holder(conn: AgentConnection) -> int | None:"""The holder's revision, when it is one that carries the incarnation.The declaration on the connection is the holder's, not the caller's, so@@ -801,10 +801,10 @@ class ConnectionRegistry:return speaksreturn None- def get(self, connection_id: str) -> Connection | None:+ def get(self, connection_id: str) -> AgentConnection | None:return self._by_id.get(connection_id)- def for_agent(self, agent_id: str) -> list[Connection]:+ def for_agent(self, agent_id: str) -> list[AgentConnection]:now = time.monotonic()return [conn@@ -841,7 +841,7 @@ class ConnectionRegistry:return ({previous} - {room_id} if previous else set()), displaceddef replace_placements(- self, conn: Connection, placements: dict[str, str]+ self, conn: AgentConnection, placements: dict[str, str]) -> list[Released]:"""Make `placements` the whole of this connection's session placements.@@ -918,7 +918,7 @@ class ConnectionRegistry:@staticmethoddef _notify_released(- conn: Connection, room_id: str, session_id: str | None+ conn: AgentConnection, room_id: str, session_id: str | None) -> None:"""Queue a `room_released` frame for a client that can take one.@@ -931,7 +931,7 @@ class ConnectionRegistry:conn.released_rooms[room_id] = session_idconn.wake.set()- def _placed_by(self, conn: Connection, room_id: str) -> str | None:+ def _placed_by(self, conn: AgentConnection, room_id: str) -> str | None:"""The session this connection placed in the room, if any."""owners = self._placement_owners.get(conn.agent_id, {})return next(@@ -945,7 +945,7 @@ class ConnectionRegistry:None,)- def connection_placements(self, conn: Connection) -> dict[str, str]:+ def connection_placements(self, conn: AgentConnection) -> dict[str, str]:"""The sessions this connection placed, and their rooms."""owners = self._placement_owners.get(conn.agent_id, {})return {@@ -1025,8 +1025,8 @@ class ConnectionRegistry:self._slot_locks[agent_id] = (lock, remaining - 1)def claim_room(- self, conn: Connection, room_id: str, *, takeover: bool = False- ) -> Connection | None:+ self, conn: AgentConnection, room_id: str, *, takeover: bool = False+ ) -> AgentConnection | None:"""Subscribe a connection to a room, claiming its slot.At most one connection per agent may act in a room, which is what the@@ -1040,7 +1040,7 @@ class ConnectionRegistry:Returns the connection that was evicted, if any."""claimant = self.claimant_of(conn.agent_id, room_id)- evicted: Connection | None = None+ evicted: AgentConnection | None = Noneif claimant is not None and claimant.id != conn.id:if not takeover:raise RoomOccupiedError(room_id, claimant.id)@@ -1054,7 +1054,7 @@ class ConnectionRegistry:conn.wake.set()return evicted- def release_room(self, conn: Connection, room_id: str) -> None:+ def release_room(self, conn: AgentConnection, room_id: str) -> None:conn.rooms.discard(room_id)conn.wake.set()@@ -1074,7 +1074,7 @@ class ConnectionRegistry:conn.rooms.discard(room_id)conn.wake.set()- def claimant_of(self, agent_id: str, room_id: str) -> Connection | None:+ def claimant_of(self, agent_id: str, room_id: str) -> AgentConnection | None:"""The connection that has explicitly claimed this room, if any.Only an explicit claim conflicts. An `all`-scope connection covering a@@ -1086,7 +1086,7 @@ class ConnectionRegistry:return connreturn None- def holder_of(self, agent_id: str, room_id: str) -> Connection | None:+ def holder_of(self, agent_id: str, room_id: str) -> AgentConnection | None:"""The connection entitled to act as this agent in this room, if any.The claimant if there is one, otherwise an `all`-scope connection —@@ -1101,7 +1101,7 @@ class ConnectionRegistry:return connreturn None- def covers(self, conn: Connection, room_id: str) -> bool:+ def covers(self, conn: AgentConnection, room_id: str) -> bool:if conn.scope == "single":return room_id in conn.rooms# An `all` connection covers everything no sibling has claimed.diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/agent_core.pysimilarity index 97%rename from core/switch_core/bridges/agent/protocol/service.pyrename to core/switch_core/bridges/agent/protocol/agent_core.pyindex 6b2ffe36e..e24355c00 100644--- a/core/switch_core/bridges/agent/protocol/service.py+++ b/core/switch_core/bridges/agent/protocol/agent_core.py@@ -25,16 +25,16 @@ from switch_core.authz import Action, Principal, require, require_managefrom switch_core.bridges.agent.api.session_reporter import SessionReporterfrom switch_core.bridges.agent.api_key_cache import ApiKeyCachefrom switch_core.bridges.agent.mediation import MediationService+from switch_core.bridges.agent.protocol.agent_connections import (+ AgentConnectionRegistry,+ ClientDeclaration,+)from switch_core.bridges.agent.protocol.agent_detail import (apply_agent_options,assemble_agent_detail,list_agent_summaries,reparent_agent,)-from switch_core.bridges.agent.protocol.connections import (- ClientDeclaration,- ConnectionRegistry,-)from switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.bridges.agent.protocol.presence import rooms_occupiedfrom switch_core.bridges.agent.protocol.statuses import compute_agent_statuses@@ -98,10 +98,10 @@ from switch_core.db.stores.user_store import UserStorefrom switch_core.db.tenant_lookup import all_tenant_ids, tenant_of_api_keyfrom switch_core.deeplinks import deeplink_for_platformfrom switch_core.events import (- LlmCallReport as MatrixLlmCallReport,+ LlmCallReport as RoomLlmCallReport,)from switch_core.events import (- ToolCallReport as MatrixToolCallReport,+ ToolCallReport as RoomToolCallReport,)from switch_core.messages.recorded_types import MEMBERSHIP_EVENT_TYPEfrom switch_core.room_wide_mention import (@@ -126,7 +126,7 @@ if TYPE_CHECKING:from switch_core.bridges.collaboration.lifecycle_service import (CollaborationBridgeLifecycleService,)- from switch_core.clients.client_base import ClientBase+ from switch_core.clients.actor import Actorfrom switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.config import SwitchConfigfrom switch_core.db.stores.agent_session_store import AgentSessionStore@@ -249,14 +249,14 @@ def _describe_room(room: Room) -> RoomDescriptor:id=room.id,name=room.name,description=room.description,- transport_room_id=room.matrix_room_id,- matrix_room_id=room.matrix_room_id,+ transport_room_id=room.transport_room_id,+ matrix_room_id=room.transport_room_id,archived=room.archived_at is not None,bridge_id=room.bridge_id,)-class ProtocolService:+class AgentCore:# Class-level defaults: several tests assemble a minimal instance without# `__init__`, and `emit_safely` treats None as "report nothing".telemetry: TelemetryService | None = None@@ -275,7 +275,7 @@ class ProtocolService:client_lifecycle: ClientLifecycleService,collab_lifecycle: CollaborationBridgeLifecycleService,event_buffer: EventBuffer,- connections: ConnectionRegistry,+ connections: AgentConnectionRegistry,task_store: TaskStore,resource_service: ResourceService,api_key_store: ApiKeyStore,@@ -306,7 +306,7 @@ class ProtocolService:self.client_lifecycle = client_lifecycleself.collab_lifecycle = collab_lifecycleself.event_buffer = event_buffer- # Injected, not constructed: more than one ProtocolService exists in a+ # Injected, not constructed: more than one AgentCore exists in a# running server, and a connection registered through one must be# visible to all of them. Owning a registry here would split the live# connection set in two.@@ -636,7 +636,7 @@ class ProtocolService:)await self.api_key_store.create(session, api_key_record)- # The Matrix client's display name is the agent's identifier, never its+ # The client's display name is the agent's identifier, never its# human display name: it is stamped on every event as `sender_name`, and# the collaboration bridges match on it to recognise an agent's own echo# coming back from a platform. A human name here would make an agent@@ -788,9 +788,11 @@ class ProtocolService:instead would repeat the cross-tenant identity leak this method existsto avoid."""- for bridge_core in self.collab_lifecycle.bridges_for_tenant(tenant_id):+ for collaboration_core in self.collab_lifecycle.bridges_for_tenant(tenant_id):try:- await bridge_core.adapter.create_agent_identity(agent_name, description)+ await collaboration_core.adapter.create_agent_identity(+ agent_name, description+ )except Exception:logger.warning("Failed to create bridge identity for %s",@@ -900,9 +902,9 @@ class ProtocolService:there, the tenant is the caller's to establish — `delete_agent`refuses without one before it stops anything."""- for bridge_core in self.collab_lifecycle.bridges_for_tenant(tenant_id):+ for collaboration_core in self.collab_lifecycle.bridges_for_tenant(tenant_id):try:- await bridge_core.adapter.remove_agent_identity(agent_name)+ await collaboration_core.adapter.remove_agent_identity(agent_name)except Exception:logger.warning("Failed to remove bridge identity for %s",@@ -1165,44 +1167,44 @@ class ProtocolService:# ── Messaging ──────────────────────────────────────────────────────────────async def _post_agent_notice(- self, client: Any, matrix_room_id: str, body: str+ self, client: Any, transport_room_id: str, body: str) -> None:- """Best-effort post of an activity notice from the agent's own Matrix+ """Best-effort post of an activity notice from the agent's own clientidentity. Used to announce resource-manager-driven side effects (e.g.room-document mutations) in a way that flows through collaborationbridges — the resource manager isn't a bridge participant, so its ownnotices wouldn't reach Slack/Mattermost."""try:- await client.send_message(matrix_room_id, body, metered=False)+ await client.send_message(transport_room_id, body, metered=False)except Exception:logger.exception(- "Failed to post agent activity notice to %s", matrix_room_id+ "Failed to post agent activity notice to %s", transport_room_id)async def _post_role_change_notice(- self, agent_id: str, matrix_room_id: str, action: str+ self, agent_id: str, transport_room_id: str, action: str) -> None:- """Announce a role assume/release from the acting agent's own Matrix+ """Announce a role assume/release from the acting agent's own clientidentity, so the notice reaches collaboration bridges (Slack/Mattermost)."""client = self.client_lifecycle.get_by_agent_id(agent_id)if client is None:return- await self._post_agent_notice(client, matrix_room_id, f"🎭 {action}.")+ await self._post_agent_notice(client, transport_room_id, f"🎭 {action}.")async def _resolve_thread_root(- self, client: ClientBase[Any], matrix_room_id: str, thread_id: str+ self, client: Actor[Any], transport_room_id: str, thread_id: str) -> str:"""Resolve a caller-supplied thread_id to the actual thread root.- Matrix threads are flat: every reply relates to a single root. Agents+ Threads are flat: every reply relates to a single root. Agentsmay pass any message id in a thread (including a mid-thread reply), sowe look the event up and, if it is itself an m.thread reply, return itsroot. If the event does not exist in the room we fail loud rather thanpost into a non-existent thread."""if client.transport is None:- raise ValueError("Agent client not connected to Matrix")- event = await client.transport.get_event(matrix_room_id, thread_id)+ raise ValueError("Agent client not connected")+ event = await client.transport.get_event(transport_room_id, thread_id)if event is None:raise ValueError(f"thread_id not found in room: {thread_id}")root = getattr(event, "thread_root_id", None)@@ -1236,10 +1238,10 @@ class ProtocolService:thread_root_id: str | None = Noneif thread_id is not None:thread_root_id = await self._resolve_thread_root(- client, room.matrix_room_id, thread_id+ client, room.transport_room_id, thread_id)event_id = await client.send_message(- room.matrix_room_id,+ room.transport_room_id,content,thread_root_id=thread_root_id,extra_content=extra_content,@@ -1248,9 +1250,9 @@ class ProtocolService:if event_id is None:raise ValueError("Failed to send message")logger.debug(- "[AGENT-MSG] sent event_id=%s to matrix room=%s",+ "[AGENT-MSG] sent event_id=%s to room=%s",event_id,- room.matrix_room_id,+ room.transport_room_id,)# The agent has replied, so clear any typing indicator raised when the# inbound message arrived. The message itself is already delivered, so a@@ -1271,7 +1273,7 @@ class ProtocolService:caption: str | None = None,thread_id: str | None = None,) -> dict[str, object]:- """Upload one or more files to the Matrix media repository and post them+ """Store one or more files in Switch's media store and post themto a room as m.image / m.file events. `files` is a list of(data, filename, mimetype). Returns{"event_id": <first>, "mxc": <first>, "attachments": [{event_id, mxc,@@ -1287,8 +1289,8 @@ class ProtocolService:(normalised to its root).With more than one file the events share an attachment-group marker so- receivers can coalesce them into one logical message — Matrix itself has- no multi-attachment event.+ receivers can coalesce them into one logical message, since a media+ event carries one file."""if not files:raise ValueError("no attachments provided")@@ -1312,18 +1314,18 @@ class ProtocolService:thread_root_id: str | None = Noneif thread_id is not None:thread_root_id = await self._resolve_thread_root(- client, room.matrix_room_id, thread_id+ client, room.transport_room_id, thread_id)total = len(files)group_id = str(uuid.uuid4()) if total > 1 else Noneposted: list[dict[str, str]] = []for index, (data, filename, mimetype) in enumerate(files):- mxc = await client.upload_media(data, mimetype, filename)+ media_uri = await client.upload_media(data, mimetype, filename)msgtype = "m.image" if mimetype.startswith("image/") else "m.file"event_id = await client.send_media(- room.matrix_room_id,- mxc,+ room.transport_room_id,+ media_uri,filename,mimetype,len(data),@@ -1341,7 +1343,9 @@ class ProtocolService:)if event_id is None:raise ValueError(f"Failed to send media message for '{filename}'")- posted.append({"event_id": event_id, "mxc": mxc, "filename": filename})+ posted.append(+ {"event_id": event_id, "mxc": media_uri, "filename": filename}+ )try:await self._set_typing(agent_id, room, False)except Exception:@@ -1683,8 +1687,8 @@ class ProtocolService:)return- bridge_core = self.collab_lifecycle.get(room.bridge_id)- if bridge_core is None:+ collaboration_core = self.collab_lifecycle.get(room.bridge_id)+ if collaboration_core is None:raise ValueError(f"Collaboration bridge {room.bridge_id} for room {room.id} ""is not running"@@ -1693,7 +1697,7 @@ class ProtocolService:agent = await self.agent_store.get(session, agent_id)if agent is None:raise ValueError(f"Agent not found: {agent_id}")- await bridge_core.handle_outbound_typing(room.id, agent.name, is_typing)+ await collaboration_core.handle_outbound_typing(room.id, agent.name, is_typing)async def update_status(self, agent_id: str, room_id: str, detail: str) -> None:"""Send a status message to a room."""@@ -1702,7 +1706,7 @@ class ProtocolService:if client is None:raise ValueError("Agent client not running")await client.send_message(- room.matrix_room_id, f"*{detail}*", format="markdown", metered=True+ room.transport_room_id, f"*{detail}*", format="markdown", metered=True)async def set_runtime_state(@@ -1774,7 +1778,7 @@ class ProtocolService:await self._emit_runtime_state(agent_id=agent_id,agent_name=agent.name,- matrix_room_id=room.matrix_room_id,+ transport_room_id=room.transport_room_id,room_id=room.id,state=state,mention_handle=await self._mention_handle_for(@@ -1791,7 +1795,7 @@ class ProtocolService:*,agent_id: str,agent_name: str,- matrix_room_id: str,+ transport_room_id: str,room_id: str,state: str,mention_handle: str | None,@@ -1807,7 +1811,7 @@ class ProtocolService:)returnawait client.send_event(- matrix_room_id,+ transport_room_id,"com.switch.agent.runtime_state",{"agent_id": agent_id,@@ -1905,7 +1909,7 @@ class ProtocolService:await self._emit_runtime_state(agent_id=agent.id,agent_name=agent.name,- matrix_room_id=room.matrix_room_id,+ transport_room_id=room.transport_room_id,room_id=room.id,state=RUNTIME_STATE_IDLE,mention_handle=await self._mention_handle_for(agent, room.bridge_id),@@ -2118,9 +2122,9 @@ class ProtocolService:}async def download_media(- self, agent_id: str, room_id: str, mxc: str+ self, agent_id: str, room_id: str, media_uri: str) -> tuple[bytes, str, str | None]:- """Download an attachment's bytes from the Matrix media repository.+ """Read an attachment's bytes from Switch's media store.Membership in `room_id` is required as authorization. Returns(bytes, content_type, filename).@@ -2130,12 +2134,12 @@ class ProtocolService:if client is None:raise ValueError("Agent client not running")if client.transport is None:- raise ValueError("Agent client not connected to Matrix")+ raise ValueError("Agent client not connected")try:- resp = await client.transport.download_media(mxc)+ resp = await client.transport.download_media(media_uri)except TransportError as exc:- raise ValueError(f"Failed to download media {mxc}: {exc}") from exc+ raise ValueError(f"Failed to download media {media_uri}: {exc}") from excreturn resp.body, resp.content_type or "", resp.filename# ── Events ───────────────────────────────────────────────────────────────@@ -2161,7 +2165,7 @@ class ProtocolService:without the same check this call would hand over events from a roomthe agent has since been removed from.- `AgentClient.on_removed` already empties the buffer of a removed+ `AgentConsumer.on_removed` already empties the buffer of a removedroom's events, so this is the second of two answers. It is theauthoritative one: that signal is in-process, and this reads the tablethe removal wrote.@@ -2236,11 +2240,11 @@ class ProtocolService:if client is None:raise ValueError("Agent client not running")if client.transport is None:- raise ValueError("Agent client not connected to Matrix")+ raise ValueError("Agent client not connected")for event in events:if isinstance(event, ToolCallReport):- tool_event = MatrixToolCallReport(+ tool_event = RoomToolCallReport(agent_id=agent_id,tool_id=event.tool_name,args=event.arguments,@@ -2249,12 +2253,12 @@ class ProtocolService:cost=event.cost,)await client.send_event(- room.matrix_room_id,+ room.transport_room_id,"com.switch.report.tool_call",tool_event.model_dump(exclude_none=True),)elif isinstance(event, LlmCallReport):- llm_event = MatrixLlmCallReport(+ llm_event = RoomLlmCallReport(agent_id=agent_id,model_id=event.model,messages=event.messages,@@ -2264,7 +2268,7 @@ class ProtocolService:cost=event.cost,)await client.send_event(- room.matrix_room_id,+ room.transport_room_id,"com.switch.report.llm_call",llm_event.model_dump(exclude_none=True),)@@ -2328,7 +2332,7 @@ class ProtocolService:client = self.client_lifecycle.get_by_agent_id(requester_id)if client and client.transport:await client.send_event(- room.matrix_room_id,+ room.transport_room_id,"com.switch.task.delegate",{"task_id": task_id,@@ -2363,7 +2367,7 @@ class ProtocolService:client = self.client_lifecycle.get_by_agent_id(agent_id)if client and client.transport:await client.send_event(- room.matrix_room_id,+ room.transport_room_id,"com.switch.task.accept",{"task_id": task_id,@@ -2396,7 +2400,7 @@ class ProtocolService:client = self.client_lifecycle.get_by_agent_id(agent_id)if client and client.transport:await client.send_event(- room.matrix_room_id,+ room.transport_room_id,"com.switch.task.update",{"task_id": task_id,@@ -2430,7 +2434,7 @@ class ProtocolService:client = self.client_lifecycle.get_by_agent_id(agent_id)if client and client.transport:await client.send_event(- room.matrix_room_id,+ room.transport_room_id,"com.switch.task.finalise",{"task_id": task_id,@@ -2440,7 +2444,7 @@ class ProtocolService:},)await client.send_message(- room.matrix_room_id, outcome, format="markdown", metered=True+ room.transport_room_id, outcome, format="markdown", metered=True)async def cancel_task(self, agent_id: str, task_id: str, reason: str) -> None:@@ -2462,7 +2466,7 @@ class ProtocolService:client = self.client_lifecycle.get_by_agent_id(agent_id)if client and client.transport:await client.send_event(- room.matrix_room_id,+ room.transport_room_id,"com.switch.task.cancel",{"task_id": task_id,@@ -2759,7 +2763,7 @@ class ProtocolService:"""Add human users to a bridged room. Requires room membership (or owner/admin).The room must already be bridged; each name is resolved against the- room's bridge, added to its external channel, and joined to the Matrix+ room's bridge, added to its external channel, and joined to theroom. Returns the names that could not be resolved on the bridge (thesewere skipped); an empty list means every requested user was added."""@@ -3121,7 +3125,7 @@ class ProtocolService:resolved_name = role.nameif not already_held:await self._post_role_change_notice(- agent_id, room.matrix_room_id, f"assumed the `{resolved_name}` role"+ agent_id, room.transport_room_id, f"assumed the `{resolved_name}` role")return result@@ -3136,18 +3140,18 @@ class ProtocolService:session, agent_id, live_connection_ids)released_role: str | None = None- matrix_room_id: str | None = None+ transport_room_id: str | None = Noneif live is not None:released_role = await self.room_role_store.agent_room_role(session, live.room_id, agent_id, live_connection_ids)room = await self.room_store.get(session, live.room_id)- matrix_room_id = room.matrix_room_id if room is not None else None+ transport_room_id = room.transport_room_id if room is not None else Noneawait self.room_role_store.release_lease(session, agent_id)await session.commit()- if released_role is not None and matrix_room_id is not None:+ if released_role is not None and transport_room_id is not None:await self._post_role_change_notice(- agent_id, matrix_room_id, f"released the `{released_role}` role"+ agent_id, transport_room_id, f"released the `{released_role}` role")async def touch_role_lease(self, agent_id: str, holder: str | None) -> bool:@@ -3689,8 +3693,8 @@ class ProtocolService:channel_type=room.channel_type,admin_mode=room.admin_mode,instructions=room.instructions,- transport_room_id=room.matrix_room_id,- matrix_room_id=room.matrix_room_id,+ transport_room_id=room.transport_room_id,+ matrix_room_id=room.transport_room_id,created_at=str(room.created_at),bridge_id=room.bridge_id,bridge_display_name=bridge_display_name,@@ -3840,7 +3844,7 @@ class ProtocolService:) -> RoomDetailDescriptor:"""Archive or unarchive a room on the calling agent's behalf.- Metadata-only and reversible — the Matrix room, members, and bridge+ Metadata-only and reversible: the room, members, and bridgechannel are untouched; the room just leaves (or rejoins) the defaultactive lists. Requires the agent to be a member of the room and tohave write access to it.@@ -3968,7 +3972,7 @@ class ProtocolService:await self._announce_document(agent_id,- room.matrix_room_id,+ room.transport_room_id,f"\U0001f4c4 created room document \u201c{document_name}\u201d.",)return document_id@@ -4001,7 +4005,7 @@ class ProtocolService:await self._announce_document(agent_id,- room.matrix_room_id,+ room.transport_room_id,f"\U0001f4c4 updated room document \u201c{document_name}\u201d.",)@@ -4030,12 +4034,12 @@ class ProtocolService:await self._announce_document(agent_id,- room.matrix_room_id,+ room.transport_room_id,f"\U0001f5d1 deleted room document \u201c{document_name}\u201d.",)async def _announce_document(- self, agent_id: str, matrix_room_id: str, body: str+ self, agent_id: str, transport_room_id: str, body: str) -> None:"""Say in the room what the agent just did to a document.@@ -4050,10 +4054,10 @@ class ProtocolService:"Agent %s has no connected client, so its document change in ""%s was not announced in the room",agent_id,- matrix_room_id,+ transport_room_id,)return- await self._post_agent_notice(client, matrix_room_id, body)+ await self._post_agent_notice(client, transport_room_id, body)async def post_llm_response(self,diff --git a/core/switch_core/bridges/agent/protocol/agent_detail.py b/core/switch_core/bridges/agent/protocol/agent_detail.pyindex 0566e29a3..d8502b598 100644--- a/core/switch_core/bridges/agent/protocol/agent_detail.py+++ b/core/switch_core/bridges/agent/protocol/agent_detail.py@@ -16,7 +16,7 @@ from typing import Any, castfrom sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.addressing import AddressingPolicy-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistryfrom switch_core.bridges.agent.protocol.statuses import compute_agent_statusesfrom switch_core.db.models import Agent, AgentSessionfrom switch_core.db.stores.agent_session_store import AgentSessionStore@@ -155,7 +155,7 @@ async def assemble_agent_detail(user_store: UserStore,agent_session_store: AgentSessionStore,room_role_store: RoomRoleStore,- connections: ConnectionRegistry,+ connections: AgentConnectionRegistry,) -> AgentDetail:owner_names: dict[str, str] = {}diff --git a/core/switch_core/bridges/agent/protocol/presence.py b/core/switch_core/bridges/agent/protocol/presence.pyindex 72cb20a3a..3a1791fb5 100644--- a/core/switch_core/bridges/agent/protocol/presence.py+++ b/core/switch_core/bridges/agent/protocol/presence.py@@ -1,6 +1,6 @@"""Which agents have something of their own in a room, from live state only.-Presence is a session that connected to the room (`ConnectionRegistry`+Presence is a session that connected to the room (`AgentConnectionRegistry`placement) or a room slot claimed on one of the agent's connections, which iswhat a standalone or MCP client leaves behind. Coverage is not presence: an`all`-scope watcher covering a room is the delivery rule, not something in it.@@ -14,11 +14,11 @@ from __future__ import annotationsfrom collections.abc import Iterable-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistrydef agents_present_in(- agent_ids: Iterable[str], room_id: str, connections: ConnectionRegistry+ agent_ids: Iterable[str], room_id: str, connections: AgentConnectionRegistry) -> set[str]:return {agent_id@@ -28,7 +28,7 @@ def agents_present_in(}-def rooms_occupied(agent_id: str, connections: ConnectionRegistry) -> set[str]:+def rooms_occupied(agent_id: str, connections: AgentConnectionRegistry) -> set[str]:"""Every room this agent is in right now."""occupied = connections.placed_rooms(agent_id)for conn in connections.for_agent(agent_id):diff --git a/core/switch_core/bridges/agent/protocol/statuses.py b/core/switch_core/bridges/agent/protocol/statuses.pyindex c41722af3..c8dc2ce8e 100644--- a/core/switch_core/bridges/agent/protocol/statuses.py+++ b/core/switch_core/bridges/agent/protocol/statuses.py@@ -2,7 +2,7 @@ from __future__ import annotationsfrom sqlalchemy.ext.asyncio import AsyncSession-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistryfrom switch_core.bridges.agent.protocol.presence import agents_present_infrom switch_core.bridges.agent.protocol.types import AgentStatusfrom switch_core.db.models import Agent@@ -14,7 +14,7 @@ async def compute_agent_statuses(agents: list[Agent],room_id: str,agent_session_store: AgentSessionStore,- connections: ConnectionRegistry,+ connections: AgentConnectionRegistry,) -> dict[str, AgentStatus]:"""Derive each agent's presence status in a room, keyed by agent id.@@ -49,7 +49,7 @@ async def compute_agent_statuses(agent is connected but nothing will start one; else DISCONNECTED.- ``session_passive``: always AWAITING_MANUAL_POLL (no heartbeat).- Shared by ProtocolService (room detail / participants) and the in-room+ Shared by AgentCore (room detail / participants) and the in-room``!status`` command so both report presence identically."""always_on_ids: list[str] = []diff --git a/core/switch_core/bridges/agent/protocol/stream.py b/core/switch_core/bridges/agent/protocol/stream.pyindex eb0604a92..e5c2d4744 100644--- a/core/switch_core/bridges/agent/protocol/stream.py+++ b/core/switch_core/bridges/agent/protocol/stream.py@@ -19,19 +19,21 @@ import timefrom collections.abc import AsyncIteratorfrom typing import TYPE_CHECKING, Any-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (APPROVAL_OUTCOME_PROTOCOL_REVISION,HEARTBEAT_LAPSED,PROTOCOL_VERSION,TAKEN_OVER,+ AgentConnection,+ AgentConnectionRegistry,Closure,- Connection,- ConnectionRegistry,)from switch_core.bridges.agent.protocol.event_buffer import (CursorExpiredError,EventBuffer,)+from switch_core.observability.catalogue import BRIDGE_EVENTS_OUT+from switch_core.observability.metrics import metricsfrom switch_core.tenant_context import current_tenant_idfrom switch_core.version import server_declaration@@ -59,7 +61,7 @@ def _frame(event: str, data: dict[str, Any], *, seq: int | None = None) -> bytesreturn ("\n".join(lines) + "\n\n").encode()-def _connection_state(conn: Connection) -> dict[str, Any]:+def _connection_state(conn: AgentConnection) -> dict[str, Any]:"""The first frame of every stream, and where the server declares itself.Version disclosure rides this frame rather than an endpoint of its own@@ -104,8 +106,8 @@ def _eviction(closure: Closure) -> dict[str, Any]:def event_stream(*,- conn: Connection,- registry: ConnectionRegistry,+ conn: AgentConnection,+ registry: AgentConnectionRegistry,buffer: EventBuffer,approvals: ApprovalOutcomes | None,) -> AsyncIterator[bytes]:@@ -120,8 +122,8 @@ def event_stream(async def _event_stream(*,- conn: Connection,- registry: ConnectionRegistry,+ conn: AgentConnection,+ registry: AgentConnectionRegistry,buffer: EventBuffer,approvals: ApprovalOutcomes | None,generation: int,@@ -385,6 +387,10 @@ async def _event_stream(# on its heartbeat, which is the value that governs resume.conn.cursor = item.seqdelivered = True+ metrics().increment(+ BRIDGE_EVENTS_OUT,+ {"bridge": "agent", "platform": "switch", "kind": item.event.type},+ )yield _frame(item.event.type, payload, seq=item.seq)if delivered:@@ -412,7 +418,7 @@ async def _event_stream(registry.detach_stream(conn, generation)-async def _wait_for_wake(conn: Connection) -> bool:+async def _wait_for_wake(conn: AgentConnection) -> bool:"""Wait for the connection itself to change — a room claim, or a close.Deliberately not waiting on the event bell: a parked connection covers@@ -426,7 +432,7 @@ async def _wait_for_wake(conn: Connection) -> bool:return False-async def _wait_for_work(bell: asyncio.Event, conn: Connection) -> bool:+async def _wait_for_work(bell: asyncio.Event, conn: AgentConnection) -> bool:"""Wait for a new event or a change to the connection itself.Returns False when neither happened before the keepalive interval, so thediff --git a/core/switch_core/bridges/agent/protocol/types.py b/core/switch_core/bridges/agent/protocol/types.pyindex 22265c77d..7462f62b7 100644--- a/core/switch_core/bridges/agent/protocol/types.py+++ b/core/switch_core/bridges/agent/protocol/types.py@@ -218,7 +218,8 @@ EventType = Literal[class AttachmentRef(BaseModel):"""A pointer to a media attachment on a message event.- Carries metadata plus the Matrix `mxc://` URI only — never the bytes. The+ Carries metadata plus the media URI (the `mxc` field, an opaque key) only,+ never the bytes. Theactual file is fetched on demand via the media-download endpoint."""@@ -259,7 +260,7 @@ class CommandPayload(BaseModel):class RoomJoinPayload(BaseModel):- # The joiner's matrix user id (the member event's state_key) and display+ # The joiner's participant id (the member event's state_key) and display# name. room_id / bridge_id / channel_type live on the enclosing AgentEvent.member: strmember_name: strdiff --git a/core/switch_core/bridges/agent/server_connectors/core.py b/core/switch_core/bridges/agent/server_connectors/core.pyindex 68c130e0a..76fdc0161 100644--- a/core/switch_core/bridges/agent/server_connectors/core.py+++ b/core/switch_core/bridges/agent/server_connectors/core.py@@ -23,7 +23,7 @@ from switch_core.bridges.agent.server_connectors.base import (from switch_core.tenant_context import no_tenant, tenant_scopeif TYPE_CHECKING:- from switch_core.bridges.agent.protocol.service import ProtocolService+ from switch_core.bridges.agent.protocol.agent_core import AgentCorelogger = logging.getLogger(__name__)@@ -42,9 +42,9 @@ class _AgentHandle:class _ProtocolReporter(ConnectorReporter):- """Reporter implementation backed by an in-process ProtocolService call."""+ """Reporter implementation backed by an in-process AgentCore call."""- def __init__(self, protocol: ProtocolService, handle: _AgentHandle) -> None:+ def __init__(self, protocol: AgentCore, handle: _AgentHandle) -> None:self._protocol = protocolself._handle = handle@@ -67,11 +67,11 @@ class ConnectorCore:"""Runtime orchestrator for a single server-side connector.Discovers agents on the external platform, registers them through the- in-process ProtocolService, and runs per-agent poll loops that forward+ in-process AgentCore, and runs per-agent poll loops that forwardmessages and tasks between the connector and Switch.Server-side connectors live in the same process as Switch core, so they- do not need HTTP — they call ``ProtocolService`` directly. (External+ do not need HTTP — they call ``AgentCore`` directly. (Externalagent integrations are the ones that go over the HTTP agent bridge.)"""@@ -83,7 +83,7 @@ class ConnectorCore:connector_type: str,connector: ServerSideConnector,registration_token: str,- protocol: ProtocolService,+ protocol: AgentCore,) -> None:self._connector_id = connector_id# The tenant of the connector's own row. Held, never bound for thediff --git a/core/switch_core/bridges/agent/server_connectors/lifecycle.py b/core/switch_core/bridges/agent/server_connectors/lifecycle.pyindex 0f9d2a3e8..9aa5ee635 100644--- a/core/switch_core/bridges/agent/server_connectors/lifecycle.py+++ b/core/switch_core/bridges/agent/server_connectors/lifecycle.py@@ -6,7 +6,7 @@ import secretsfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.server_connectors.base import (ServerSideConnector,ServerSideConnectorConfig,@@ -42,7 +42,7 @@ class ServerSideConnectorLifecycleService:*,connector_store: ServerConnectorStore,api_key_store: ApiKeyStore,- protocol: ProtocolService,+ protocol: AgentCore,session_factory: async_sessionmaker[AsyncSession],telemetry: TelemetryService | None = None,encryption_secret: str,diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.pyindex 938789fdf..f83ebb601 100644--- a/core/switch_core/bridges/collaboration/adapter.py+++ b/core/switch_core/bridges/collaboration/adapter.py@@ -331,7 +331,7 @@ class SupportsSharedConnection(Protocol):def set_on_attached(self, callback: Callable[[], None]) -> None: ...-class CollaborationAdapter(ABC):+class PlatformAdapter(ABC):#: Whether this platform draws agents' session activity: each turn step by#: step, and the approval and question cards a session waits on.draws_session_activity: ClassVar[bool] = False@@ -546,7 +546,7 @@ class CollaborationAdapter(ABC):invalidate whatever the last one signed or encrypted.Async because generating key material is CPU-bound and this runs on- the event loop that carries every live Matrix session.+ the event loop that carries every live client in switch-core."""return connection_config@@ -666,7 +666,7 @@ class CollaborationAdapter(ABC):**`content` is Switch Markdown, and this method renders it.** Unlike`send_message`, whose caller translates, every caller here passes an- unrendered body — the notices in `bridge_core`, the adapters' own+ unrendered body — the notices in `collaboration_core`, the adapters' ownnotices, and the relayed admin events alike. An override must thereforerun `translate_outbound` itself. Splitting that responsibility betweencallers is what once sent a body through the conversion twice, and the@@ -699,7 +699,7 @@ class CollaborationAdapter(ABC):Switch files a person under the name it first sees, and some platformsdo not always supply one — Teams omits it from a 1:1 chat activity. The- id then becomes that person's name everywhere: their Matrix account,+ id then becomes that person's name everywhere: their client,the title of any room auto-created for them, and every agent reply thataddresses them. Fixing the resolution stops it happening to the nextperson and does nothing for the ones already recorded, so an adapterdiff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/collaboration_core.pysimilarity index 88%rename from core/switch_core/bridges/collaboration/bridge_core.pyrename to core/switch_core/bridges/collaboration/collaboration_core.pyindex c21f848a3..57a388c36 100644--- a/core/switch_core/bridges/collaboration/bridge_core.py+++ b/core/switch_core/bridges/collaboration/collaboration_core.py@@ -8,7 +8,7 @@ import uuidfrom collections.abc import Awaitable, Callable, Iterator, Mappingfrom contextlib import contextmanagerfrom dataclasses import dataclass, field-from typing import TYPE_CHECKING, Any, TypeVar+from typing import TYPE_CHECKING, TypeVarfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker@@ -18,7 +18,7 @@ from switch_core.attachments import parse_attachment_groupfrom switch_core.bridges.agent.commands import stop_control_framefrom switch_core.bridges.collaboration.adapter import (AgentPresentation,- CollaborationAdapter,+ PlatformAdapter,SupportsSharedConnection,)from switch_core.bridges.collaboration.models import (@@ -33,13 +33,13 @@ from switch_core.bridges.collaboration.models import ()from switch_core.bridges.collaboration.session.refusal import InboundActor, Refusedfrom switch_core.bridges.collaboration.session.renderers import INTERRUPT_ACTION+from switch_core.clients.actor import Actor, ClientConfigfrom switch_core.clients.admin_messages import (ADMIN_MARKER,PLATFORM_MARKER,AdminMessageType,platform_on_behalf_of,)-from switch_core.clients.client_base import ClientBase, ClientConfigfrom switch_core.clients.mentions import mention_regex, strip_emphasisfrom switch_core.db.models import BridgeMessageMap, ExternalUserfrom switch_core.db.session_scope import tenant_session@@ -61,13 +61,13 @@ from switch_core.provisioning import Provisioningfrom switch_core.room_service import RoomCreateConfigfrom switch_core.room_wide_mention import is_room_wide_mentionfrom switch_core.session_activity.bridge_answers import ApprovalAnswers-from switch_core.session_activity.bridge_publisher import (- SessionActivityBridgePublisher,+from switch_core.session_activity.listener import AgentSessionActivityListener+from switch_core.session_activity.publisher import (+ AgentSessionActivityPublisher,)-from switch_core.session_activity.listener import SessionActivityListenerfrom switch_core.session_activity.service import (+ AgentSessionActivityService,PlatformPerson,- SessionActivityService,)from switch_core.sessions.attachments import normalise_mime_typefrom switch_core.sessions.errors import SessionError@@ -84,8 +84,11 @@ from switch_core.transport import ()if TYPE_CHECKING:- from switch_core.bridges.agent.protocol.connections import ConnectionRegistry+ from switch_core.bridges.agent.protocol.agent_connections import (+ AgentConnectionRegistry,+ )from switch_core.clients.client_lifecycle_service import ClientLifecycleService+ from switch_core.clients.workspace_consumer import WorkspaceConsumerfrom switch_core.room_service import RoomService@@ -101,9 +104,9 @@ _InboundEventT = TypeVar(InboundAppJoin,)-# How long to wait for a freshly-invited external-user puppet to actually join a+# How long to wait for a freshly-invited external-user human actor to actually join a# room before giving up on relaying its message.-PUPPET_JOIN_TIMEOUT = 30.0+HUMAN_JOIN_TIMEOUT = 30.0# How long to hold an incomplete outbound attachment group before relaying the# parts that arrived, flagged as incomplete (see _schedule_outbound_group_flush).@@ -151,9 +154,9 @@ def _no_agents_notice(slash_hint: str | None) -> str:)-class BridgeCore:- # Tests assemble a BridgeCore with `__new__`; these read as "not wired".- _activity_publisher: SessionActivityBridgePublisher | None = None+class CollaborationCore:+ # Tests assemble a CollaborationCore with `__new__`; these read as "not wired".+ _activity_publisher: AgentSessionActivityPublisher | None = None_approval_answers: ApprovalAnswers | None = Nonedef __init__(@@ -163,7 +166,7 @@ class BridgeCore:bridge_tenant_id: str,bridge_type: str,bridge_display_name: str,- adapter: CollaborationAdapter,+ adapter: PlatformAdapter,room_store: RoomStore,external_user_store: ExternalUserStore,bridge_message_map_store: BridgeMessageMapStore,@@ -171,14 +174,14 @@ class BridgeCore:client_store: ClientStore,room_service: RoomService,client_lifecycle: ClientLifecycleService,- matrix_admin: Provisioning,+ provisioning: Provisioning,session_factory: async_sessionmaker[AsyncSession],- matrix_server_name: str,- bridge_client_matrix_user_id: str,+ id_server_name: str,+ workspace_consumer_transport_user_id: str,max_attachment_bytes: int,- session_activity_listener: SessionActivityListener,- session_activity_service: SessionActivityService,- connections: ConnectionRegistry,+ session_activity_listener: AgentSessionActivityListener,+ session_activity_service: AgentSessionActivityService,+ connections: AgentConnectionRegistry,gateway_public_url: str | None = None,) -> None:self._bridge_id = bridge_id@@ -200,10 +203,12 @@ class BridgeCore:self._client_store = client_storeself._room_service = room_serviceself._client_lifecycle = client_lifecycle- self._matrix_admin = matrix_admin+ self._provisioning = provisioningself._session_factory = session_factory- self._matrix_server_name = matrix_server_name- self._bridge_client_matrix_user_id = bridge_client_matrix_user_id+ self._id_server_name = id_server_name+ self._workspace_consumer_transport_user_id = (+ workspace_consumer_transport_user_id+ )self._max_attachment_bytes = max_attachment_bytesself._channel_to_room: dict[str, tuple[str, str]] = {}@@ -213,15 +218,15 @@ class BridgeCore:# has a channel mapping always has a tenant here — including rooms# created long after this bridge started. See `_room_tenant`.self._room_tenants: dict[str, str] = {}- self._user_puppets: dict[str, str] = {}+ self._human_actors: dict[str, str] = {}# External user ids whose stored name is known not to be a platform id,# so the placeholder repair does not re-ask the database once per# message. One-way, so a cached answer cannot go stale — see# _repair_placeholder_username.self._names_known_good: set[str] = set()- self._puppet_matrix_ids: set[str] = set()+ self._human_user_ids: set[str] = set()self._channel_locks: dict[str, asyncio.Lock] = {}- self._puppet_locks: dict[str, asyncio.Lock] = {}+ self._human_actor_locks: dict[str, asyncio.Lock] = {}# Channels Switch is itself provisioning right now (outbound room# creation / bridge change). The bot auto-joins a channel the instant# it is created, which fires an inbound join before the room↔channel@@ -234,7 +239,7 @@ class BridgeCore:# never completes cannot leak.self._outbound_groups: dict[str, _PendingOutboundGroup] = {}self._outbound_group_timers: dict[str, asyncio.TimerHandle] = {}- # Matrix-event -> external-post anchors written synchronously right after+ # Room-event -> external-post anchors written synchronously right after# room_send, before the durable _record_message_map commit, so a fast# command reply relayed during that DB await still resolves the command's# thread root instead of dropping to the channel root. Popped on commit.@@ -248,7 +253,7 @@ class BridgeCore:self._connections = connectionsself._session_activity_service = session_activity_serviceself._activity_publisher = (- SessionActivityBridgePublisher(+ AgentSessionActivityPublisher(adapter=adapter,bridge_id=bridge_id,bridge_type=bridge_type,@@ -274,7 +279,7 @@ class BridgeCore:)@property- def adapter(self) -> CollaborationAdapter:+ def adapter(self) -> PlatformAdapter:return self._adapterdef relays_room(self, room_id: str) -> bool:@@ -299,7 +304,7 @@ class BridgeCore:"""Count one relay out to the platform, time it, and count its failure.Placed around the relay call rather than at the top of the handler: a- handler returns early for a puppet's own echo and for a room with no+ handler returns early for a human actor's own echo and for a room with nochannel mapping, and neither of those is a message anybody sentoutwards.@@ -314,19 +319,25 @@ class BridgeCore:under the same name; `switch.bridge.errors` is where that shows."""metrics().increment(- BRIDGE_EVENTS_OUT, {"platform": self._bridge_type, "kind": kind}+ BRIDGE_EVENTS_OUT,+ {"bridge": "collaboration", "platform": self._bridge_type, "kind": kind},)started = time.perf_counter()try:yieldexcept Exception:metrics().increment(- BRIDGE_ERRORS, {"platform": self._bridge_type, "direction": "outbound"}+ BRIDGE_ERRORS,+ {+ "bridge": "collaboration",+ "platform": self._bridge_type,+ "direction": "outbound",+ },)raisemetrics().observe(BRIDGE_CALL_DURATION,- {"platform": self._bridge_type, "kind": kind},+ {"bridge": "collaboration", "platform": self._bridge_type, "kind": kind},(time.perf_counter() - started) * 1000.0,)@@ -361,9 +372,18 @@ class BridgeCore:async def traced(event: _InboundEventT) -> None:event_id = uuid.uuid4().hex[:16]- with log_context(request_id=f"{self._bridge_type}-{event_id}"):+ with log_context(+ request_id=f"{self._bridge_type}-{event_id}",+ bridge="collaboration",+ platform=self._bridge_type,+ ):metrics().increment(- BRIDGE_EVENTS_IN, {"platform": self._bridge_type, "event": kind}+ BRIDGE_EVENTS_IN,+ {+ "bridge": "collaboration",+ "platform": self._bridge_type,+ "event": kind,+ },)room_ids = self._channel_to_room.get(event.channel_id)tenant_id = (@@ -386,7 +406,11 @@ class BridgeCore:# invisible from the platform's side.metrics().increment(BRIDGE_ERRORS,- {"platform": self._bridge_type, "direction": "inbound"},+ {+ "bridge": "collaboration",+ "platform": self._bridge_type,+ "direction": "inbound",+ },)raise@@ -394,7 +418,7 @@ class BridgeCore:async def start(self) -> None:await self._load_channel_map()- await self._load_existing_puppets()+ await self._load_existing_human_actors()self._adapter.set_channel_migration_handler(self._handle_channel_migrated)self._adapter.set_channel_type_handler(self._record_channel_type)self._adapter.set_agent_presentation_resolver(self._agent_presentation)@@ -463,7 +487,7 @@ class BridgeCore:if room.external_channel_id:self.add_room_mapping(room.id,- room.matrix_room_id,+ room.transport_room_id,room.external_channel_id,room.tenant_id,)@@ -498,7 +522,7 @@ class BridgeCore:self._room_tenants[room_id] = tenant_idreturn tenant_id- async def _load_existing_puppets(self) -> None:+ async def _load_existing_human_actors(self) -> None:async with tenant_session(self._session_factory, self._bridge_tenant_id) as session:@@ -515,7 +539,7 @@ class BridgeCore:)for user in users:- self._user_puppets[user.external_user_id] = user.client_id+ self._human_actors[user.external_user_id] = user.client_idclient = self._client_lifecycle.get(user.client_id)if client is None:@@ -524,7 +548,7 @@ class BridgeCore:client = self._client_lifecycle.start_client(record)if client:- self._puppet_matrix_ids.add(client.matrix_user_id)+ self._human_user_ids.add(client.transport_user_id)def _provision_identities_on_attach(self) -> None:"""Re-run identity provisioning when a shared connection attaches.@@ -827,8 +851,8 @@ class BridgeCore:)if await self._is_registered_agent(msg.sender_name):# A bridged Switch agent's own message echoed back from the platform.- # The agent posts natively on Matrix (that is where agents see each- # other), so re-importing the echo would double-post it and spawn a+ # The agent posts natively in the Switch room (that is where agents+ # see each other), so re-importing the echo would double-post it and spawn a# duplicate "user" identity for the agent. Drop it. Note# this is by *name*, so genuine third-party bots and humans still# bridge in normally.@@ -862,7 +886,7 @@ class BridgeCore:if room_ids is None:return- room_id, matrix_room_id = room_ids+ room_id, transport_room_id = room_ids# A bot @mention carries no agent name in its text (the platform tags the# bot, not the agent). Resolve which agent it addresses so we can inject@@ -875,13 +899,13 @@ class BridgeCore:await self._maybe_guide_self_mention(msg, room_id)await self._repair_placeholder_username(msg.sender_id, msg.sender_name)- puppet = await self._ensure_user_in_matrix_room(+ human_actor = await self._ensure_human_in_room(external_user_id=msg.sender_id,external_username=msg.sender_name,room_id=room_id,- matrix_room_id=matrix_room_id,+ transport_room_id=transport_room_id,)- if puppet is None:+ if human_actor is None:returncontent = self._adapter.translate_inbound(msg.content)@@ -890,23 +914,23 @@ class BridgeCore:):content = f"@{mention_target} {content}"logger.debug(- "[BRIDGE-IN] sending to matrix room=%s via puppet=%s attachments=%d",- matrix_room_id,- puppet.matrix_user_id,+ "[BRIDGE-IN] writing to room=%s as human=%s attachments=%d",+ transport_room_id,+ human_actor.transport_user_id,len(msg.attachments),)# Bridge threads inbound: if the external post replied into a thread,- # resolve that external root to the Matrix event we bridged for it.+ # resolve that external root to the room event we bridged for it.thread_root_id: str | None = Noneif msg.root_id is not None:- thread_root_id = await self._matrix_event_for_external_post(msg.root_id)+ thread_root_id = await self._event_for_external_post(msg.root_id)if thread_root_id is None:logger.warning(- "[BRIDGE-IN] no Matrix event mapped for external root %s; "+ "[BRIDGE-IN] no room message mapped for external root %s; ""posting top-level in room %s",msg.root_id,- matrix_room_id,+ transport_room_id,)# An attachment the platform offered but we could not relay must be@@ -920,8 +944,8 @@ class BridgeCore:content = f"{content}\n{notes}" if content.strip() else notesif not msg.attachments:- event_id = await puppet.send_message(- matrix_room_id,+ event_id = await human_actor.send_message(+ transport_room_id,content,format="markdown",thread_root_id=thread_root_id,@@ -932,7 +956,7 @@ class BridgeCore:"[BRIDGE-IN] failed to relay message from %s into room %s — ""it will not reach the room",msg.sender_name,- matrix_room_id,+ transport_room_id,)return# Record the correlation so a later reply (either direction) threads.@@ -952,18 +976,18 @@ class BridgeCore:total = len(msg.attachments)# A platform post hands us all its files at once, so the group is known# up front — no waiting on the receiving side to learn how many to- # expect. Matrix carries them as `total` events sharing this id.+ # expect. The room carries them as `total` events sharing this id.group_id = str(uuid.uuid4()) if total > 1 else Nonefor index, attachment in enumerate(msg.attachments):- mxc = await puppet.upload_media(+ media_uri = await human_actor.upload_media(attachment.data, attachment.mimetype, attachment.filename)msgtype = ("m.image" if attachment.mimetype.startswith("image/") else "m.file")- event_id = await puppet.send_media(- matrix_room_id,- mxc,+ event_id = await human_actor.send_media(+ transport_room_id,+ media_uri,attachment.filename,attachment.mimetype,len(attachment.data),@@ -982,7 +1006,7 @@ class BridgeCore:"[BRIDGE-IN] failed to relay attachment %s from %s into room %s",attachment.filename,msg.sender_name,- matrix_room_id,+ transport_room_id,)if index == 0:first_event_id = event_id@@ -1010,15 +1034,15 @@ class BridgeCore:)if room_ids is None:return- room_id, matrix_room_id = room_ids+ room_id, transport_room_id = room_ids- puppet = await self._ensure_user_in_matrix_room(+ human_actor = await self._ensure_human_in_room(external_user_id=cmd.sender_id,external_username=cmd.sender_name,room_id=room_id,- matrix_room_id=matrix_room_id,+ transport_room_id=transport_room_id,)- if puppet is None:+ if human_actor is None:return# Where the command's result should thread. A command typed inside an@@ -1027,46 +1051,44 @@ class BridgeCore:# Mattermost RootId. A top-level command starts its own thread, rooted# at the command post (message_ref).thread_root_post = cmd.root_id or cmd.message_ref- existing_matrix_root: str | None = None+ existing_root: str | None = Noneif thread_root_post is not None:- existing_matrix_root = await self._matrix_event_for_external_post(- thread_root_post- )+ existing_root = await self._event_for_external_post(thread_root_post)content: dict[str, object] = {"command": cmd.command,"args": self._adapter.translate_inbound(cmd.args),- "user_id": puppet.matrix_user_id,+ "user_id": human_actor.transport_user_id,"user_name": cmd.sender_name,}# If the thread root is already bridged, relate the command event to it- # so the result threads onto the existing Matrix root (which resolves+ # so the result threads onto the existing room root (which resolves# back to a valid Mattermost root post). Otherwise the command event# itself anchors the thread (mapping recorded below).- if existing_matrix_root is not None:+ if existing_root is not None:content["m.relates_to"] = {"rel_type": "m.thread",- "event_id": existing_matrix_root,+ "event_id": existing_root,}try:- event_id = await puppet.send_event(- matrix_room_id, "com.switch.command", content+ event_id = await human_actor.send_event(+ transport_room_id, "com.switch.command", content)except TransportError as exc:logger.error("Failed to bridge command %s into %s: %s",cmd.command,- matrix_room_id,+ transport_room_id,exc,)return- # No bridged Matrix event for the thread root yet: map the command event+ # No bridged room event for the thread root yet: map the command event# to it so a result threaded under the command resolves back to a valid# Mattermost root post (the command post for a top-level command, or the# thread root for an in-thread command whose root we hadn't recorded).- if existing_matrix_root is None and thread_root_post is not None:+ if existing_root is None and thread_root_post is not None:# Anchor in memory before the DB write: the write awaits a query that# yields the loop, and a fast reply (e.g. !help) relayed in that gap# would miss the row and land at the channel root. Popped on commit.@@ -1183,7 +1205,9 @@ class BridgeCore:await session.commit()self._channel_to_room.pop(old_id, None)- self.add_room_mapping(room.id, room.matrix_room_id, new_id, room.tenant_id)+ self.add_room_mapping(+ room.id, room.transport_room_id, new_id, room.tenant_id+ )logger.warning("Re-pointed room %s from channel %s to %s after the platform ""reissued the id",@@ -1203,7 +1227,7 @@ class BridgeCore:async def _adopt_existing_room(self, channel_id: str) -> tuple[str, str] | None:"""If a room already exists in the DB for this channel on this bridge,register it in the in-memory map and return its (room_id,- matrix_room_id). Returns None if no such room exists. Idempotent."""+ transport_room_id). Returns None if no such room exists. Idempotent."""async with tenant_session(self._session_factory, self._bridge_tenant_id) as session:@@ -1212,9 +1236,11 @@ class BridgeCore:)if room is None:return None- self.add_room_mapping(room.id, room.matrix_room_id, channel_id, room.tenant_id)+ self.add_room_mapping(+ room.id, room.transport_room_id, channel_id, room.tenant_id+ )logger.debug("Adopted existing room %s for channel %s", room.id, channel_id)- return (room.id, room.matrix_room_id)+ return (room.id, room.transport_room_id)async def _create_room_for_channel(self,@@ -1291,11 +1317,13 @@ class BridgeCore:return Noneroom = result.room- self.add_room_mapping(room.id, room.matrix_room_id, channel_id, room.tenant_id)+ self.add_room_mapping(+ room.id, room.transport_room_id, channel_id, room.tenant_id+ )logger.info("Auto-created %s room %s for %s channel %s",channel_type,- room.matrix_room_id,+ room.transport_room_id,bridge_name,channel_id,)@@ -1303,7 +1331,7 @@ class BridgeCore:if not agent_ids:# create_room invited the bridge client before returning, so posting# now cannot predate its join. admin_message goes straight to the- # channel via the platform API (not through Matrix), so it surfaces+ # channel via the platform API (not through the room), so it surfaces# regardless — but the ordering keeps the room consistent.logger.warning("Auto-created room %s for channel %s has no agents", room.id, channel_id@@ -1314,7 +1342,7 @@ class BridgeCore:message_type=AdminMessageType.NO_AGENTS,)- return (room.id, room.matrix_room_id)+ return (room.id, room.transport_room_id)async def _resolve_agents_for_channel(self, channel_id: str, channel_type: ChannelType@@ -1344,7 +1372,7 @@ class BridgeCore:When the DB lookup misses, falls back to an exact match in theplatform directory, so a person who has never messaged through Switchstill resolves. A hit is persisted (an ``ExternalUser`` row and its- puppet), so room membership, addressing and export all see the same+ human actor), so room membership, addressing and export all see the sameperson this resolution found."""async with self._session_factory() as session:@@ -1395,11 +1423,11 @@ class BridgeCore:async def ensure_users_in_room(self,room_id: str,- matrix_room_id: str,+ transport_room_id: str,user_names: list[str],) -> None:- """For each resolvable name in `user_names`, ensure a running puppet- client exists and is joined to the Matrix room.+ """For each resolvable name in `user_names`, ensure a running human actor+ client exists and is joined to the room.Resolution goes through `resolve_external_user_id_map`, the sameanswer the channel-invite path uses, so a person the platform@@ -1419,59 +1447,62 @@ class BridgeCore:self._bridge_id,)continue- await self._ensure_user_in_matrix_room(+ await self._ensure_human_in_room(external_user_id=ext_user.external_user_id,external_username=ext_user.external_username,room_id=room_id,- matrix_room_id=matrix_room_id,+ transport_room_id=transport_room_id,)- async def _ensure_user_in_matrix_room(+ async def _ensure_human_in_room(self,*,external_user_id: str,external_username: str,room_id: str,- matrix_room_id: str,- ) -> ClientBase[ClientConfig] | None:- """Get-or-create the puppet for this external user and ensure it has- actually joined the room. Returns the running puppet, or None if it+ transport_room_id: str,+ ) -> Actor[ClientConfig] | None:+ """Get-or-create the human actor for this external user and ensure it has+ actually joined the room. Returns the running human actor, or None if itcouldn't be brought up or didn't join in time. Idempotent."""- client_id = self._user_puppets.get(external_user_id)+ client_id = self._human_actors.get(external_user_id)if client_id is None:- client_id = await self._create_puppet(external_user_id, external_username)- puppet = self._client_lifecycle.get(client_id)- if puppet is None:+ client_id = await self._create_human_actor(+ external_user_id, external_username+ )+ human_actor = self._client_lifecycle.get(client_id)+ if human_actor is None:logger.error(- "Puppet client %s not running for external user %s",+ "Human actor %s not running for external user %s",client_id,external_user_id,)return None- await puppet.wait_ready()+ await human_actor.wait_ready()try:await self._room_service.ensure_client_in_room(room_id, client_id)except Exception:logger.exception(- "Failed to add puppet client %s to room %s", client_id, room_id+ "Failed to add human actor %s to room %s", client_id, room_id)return None- # ensure_client_in_room only *invites*; the puppet joins asynchronously- # from its own sync loop. Sending before that join lands gets rejected by- # the homeserver, so the message that triggered the provisioning would be- # lost. Block until the join is observed.- if not await puppet.wait_joined(matrix_room_id, PUPPET_JOIN_TIMEOUT):+ # A human actor runs no consumer, so nothing of its own accepts the+ # invitation: provisioning records the membership itself. A message+ # written before that row lands predates the join and is filtered by+ # the room's readers, so the message that triggered the provisioning+ # would be lost. Block until the membership is observed.+ if not await human_actor.wait_joined(transport_room_id, HUMAN_JOIN_TIMEOUT):logger.error(- "Puppet %s (external user %s) did not join room %s within %ss — "+ "Human actor %s (external user %s) did not join room %s within %ss — ""cannot relay its message",- puppet.matrix_user_id,+ human_actor.transport_user_id,external_user_id,- matrix_room_id,- PUPPET_JOIN_TIMEOUT,+ transport_room_id,+ HUMAN_JOIN_TIMEOUT,)return None- return puppet+ return human_actorasync def _handle_inbound_interaction(self, interaction: InboundInteraction@@ -1616,7 +1647,7 @@ class BridgeCore:async def _identify_actor(self, actor: InboundActor) -> str | None:"""The Switch identity behind the platform account that acted.- None where the channel maps to no room, or the puppet cannot be brought+ None where the channel maps to no room, or the human actor cannot be broughtinto it. Both are refusals: an answer carries who gave it, and there isno default actor to fall back on."""@@ -1627,21 +1658,21 @@ class BridgeCore:actor.channel_id,)return None- room_id, matrix_room_id = room_ids- puppet = await self._ensure_user_in_matrix_room(+ room_id, transport_room_id = room_ids+ human_actor = await self._ensure_human_in_room(external_user_id=actor.sender_id,external_username=actor.sender_name,room_id=room_id,- matrix_room_id=matrix_room_id,+ transport_room_id=transport_room_id,)- return puppet.matrix_user_id if puppet is not None else None+ return human_actor.transport_user_id if human_actor is not None else Noneasync def _handle_user_joined_channel(self, join: InboundUserJoin) -> None:"""Called by the adapter when an external user joins a bridgedchannel (e.g. someone adds louisa to a Mattermost channel via theMattermost UI). Auto-creates the Switch room if the channel isn'tmapped yet (same as the lazy inbound-message path), then ensures- the puppet exists and is joined to the Matrix room."""+ the human actor exists and is joined to the room."""if await self._is_registered_agent(join.external_username):# The account that joined is actually a bridged Switch agent (its# bot account), not an external user. Route it through the agent-join@@ -1670,15 +1701,15 @@ class BridgeCore:)if room_ids is None:return- room_id, matrix_room_id = room_ids- await self._ensure_user_in_matrix_room(+ room_id, transport_room_id = room_ids+ await self._ensure_human_in_room(external_user_id=join.external_user_id,external_username=join.external_username,room_id=room_id,- matrix_room_id=matrix_room_id,+ transport_room_id=transport_room_id,)- # ── Puppet lifecycle ─────────────────────────────────────────────────────+ # ── Human actor lifecycle ─────────────────────────────────────────────────────async def _repair_placeholder_username(self, external_user_id: str, resolved_username: str@@ -1687,7 +1718,7 @@ class BridgeCore:Switch files someone under the name it first saw, and a platform thatsupplied none left its own id there — which then reads as that person's- name in the room title, on their Matrix account and in every agent+ name in the room title, on their client and in every agentreply that addresses them. Repairing on the way past needs no migrationfor the rows already written.@@ -1733,17 +1764,17 @@ class BridgeCore:)await session.commit()client_id = existing.client_id- # The Matrix account keeps its localpart — that is an address, and- # changing it would orphan the history — but its display name is what+ # The client keeps its localpart, since that is an address and+ # changing it would orphan the history, but its display name is what# people read.- puppet = self._client_lifecycle.get(client_id)- if puppet is not None:+ human_actor = self._client_lifecycle.get(client_id)+ if human_actor is not None:try:- await puppet.set_display_name(resolved_username)+ await human_actor.set_display_name(resolved_username)except Exception:logger.warning("Renamed external user %s but could not update the display "- "name of its Matrix account",+ "name of its HumanActor",external_user_id,exc_info=True,)@@ -1757,7 +1788,7 @@ class BridgeCore:The inbound path creates these lazily on first message, which leavesnobody to claim for a workspace that has only just been connected.Claiming an identity (CHOO-2137) needs the record to exist up front, so- this provisions the same puppet the inbound path would have.+ this provisions the same human actor the inbound path would have."""async with self._session_factory() as session:existing = await self._external_user_store.get_by_external_id(@@ -1766,9 +1797,11 @@ class BridgeCore:if existing is not None:return existing- client_id = self._user_puppets.get(external_user_id)+ client_id = self._human_actors.get(external_user_id)if client_id is None:- client_id = await self._create_puppet(external_user_id, external_username)+ client_id = await self._create_human_actor(+ external_user_id, external_username+ )async with self._session_factory() as session:created = await self._external_user_store.get_by_client_id(@@ -1776,47 +1809,47 @@ class BridgeCore:)if created is None:raise RuntimeError(- f"Puppet for external user {external_user_id} on bridge "+ f"Human actor for external user {external_user_id} on bridge "f"{self._bridge_id} was created without an ExternalUser record")return created- async def _create_puppet(+ async def _create_human_actor(self, external_user_id: str, external_username: str) -> str:- """Mint the Matrix identity that stands in for a person on the platform.+ """Mint the client identity that stands in for a person on the platform.Bound to the **bridge's** tenant, not to whatever room the message- that triggered it arrived in. A puppet is per-bridge and outlives that+ that triggered it arrived in. A human actor is per-bridge and outlives thatmessage: the same client is reused for every room this person speaksin, so a client row stamped with the first room's tenant would bewrong for the second — and the client task it starts must not carrythat tenant either, which is why `ClientLifecycleService` unbindsbefore running one."""- lock = self._puppet_locks.setdefault(external_user_id, asyncio.Lock())+ lock = self._human_actor_locks.setdefault(external_user_id, asyncio.Lock())async with lock:with tenant_scope(self._bridge_tenant_id):- return await self._create_puppet_locked(+ return await self._create_human_actor_locked(external_user_id, external_username)- async def _create_puppet_locked(+ async def _create_human_actor_locked(self, external_user_id: str, external_username: str) -> str:- existing = self._user_puppets.get(external_user_id)+ existing = self._human_actors.get(external_user_id)if existing is not None:return existing- # Defence in depth against agent/user misdetection: a- # bridged agent must never be puppeted as an external user. If the+ # Defence in depth against agent/user misdetection: a bridged agent+ # must never get a human actor as if it were an external user. If the# name collides with a registered Switch agent, refuse loudly rather# than create a duplicate "user" identity for it.async with self._session_factory() as session:agent = await self._agent_store.get_by_name(session, external_username)if agent is not None:raise ValueError(- f"Refusing to create external-user puppet for '{external_username}'"+ f"Refusing to create external-user human actor for '{external_username}'"" on bridge "f"{self._bridge_id}: name collides with a registered Switch agent"" (likely a bridged agent bot misclassified as a user)"@@ -1824,8 +1857,8 @@ class BridgeCore:sanitized = re.sub(r"[^a-z0-9_-]", "-", external_username.lower()).strip("-")# Scope to the bridge: the same username on two bridges of the same- # type (e.g. two Slack workspaces) must map to distinct Matrix users,- # since matrix_user_id is globally unique but usernames are not.+ # type (e.g. two Slack workspaces) must map to distinct clients,+ # since transport_user_id is globally unique but usernames are not.localpart = f"switch-{self._bridge_type}-{self._bridge_id}-{sanitized}"client = await self._client_lifecycle.create_and_start(@@ -1844,25 +1877,25 @@ class BridgeCore:await self._external_user_store.create(session, ext_user)await session.commit()- self._user_puppets[external_user_id] = client.client_id- self._puppet_matrix_ids.add(client.matrix_user_id)+ self._human_actors[external_user_id] = client.client_id+ self._human_user_ids.add(client.transport_user_id)self._adapter.prime_mention_targets({external_username: external_user_id})logger.info(- "Created puppet %s for external user %s on bridge %s",- client.matrix_user_id,+ "Created human actor %s for external user %s on bridge %s",+ client.transport_user_id,external_user_id,self._bridge_id,)return client.client_iddef _find_channel(- self, room_id: str | None = None, matrix_room_id: str | None = None+ self, room_id: str | None = None, transport_room_id: str | None = None) -> str | None:for (rid, mrid), channel_id in self._room_to_channel.items():if room_id and rid == room_id:return channel_id- if matrix_room_id and mrid == matrix_room_id:+ if transport_room_id and mrid == transport_room_id:return channel_idreturn None@@ -1872,19 +1905,21 @@ class BridgeCore:self, room: RoomRef, event: TransportMessage) -> None:logger.debug(- "[BRIDGE-OUT] matrix event from=%s room=%s body=%s",+ "[BRIDGE-OUT] room message from=%s room=%s body=%s",event.sender,room.room_id,event.body[:80] if event.body else "",)- if event.sender in self._puppet_matrix_ids:- logger.debug("[BRIDGE-OUT] skipping puppet message from %s", event.sender)+ if event.sender in self._human_user_ids:+ logger.debug(+ "[BRIDGE-OUT] skipping human actor message from %s", event.sender+ )return- if event.sender == self._bridge_client_matrix_user_id:+ if event.sender == self._workspace_consumer_transport_user_id:logger.debug("[BRIDGE-OUT] skipping bridge client message")return- channel_id = self._find_channel(matrix_room_id=room.room_id)+ channel_id = self._find_channel(transport_room_id=room.room_id)if channel_id is None:logger.debug("[BRIDGE-OUT] no channel mapping for room %s", room.room_id)return@@ -1902,7 +1937,7 @@ class BridgeCore:platform_marker = event_content.get(PLATFORM_MARKER)sender_name = event.sender_name# An admin/system or platform message renders natively per bridge- # (admin_message) rather than on behalf of its Matrix sender, so it+ # (admin_message) rather than on behalf of its room sender, so it# needs no sender_name.is_system = admin_marker is not None or platform_marker is not Noneif sender_name is None and not is_system:@@ -1976,7 +2011,7 @@ class BridgeCore:async def _outbound_thread_root_ref(self, event_content: dict[str, object], channel_id: str) -> str | None:- """Bridge threads outbound: if this Matrix message is a threaded reply,+ """Bridge threads outbound: if this room message is a threaded reply,resolve its thread root to the external post that anchors the thread."""relates = event_content.get("m.relates_to") or {}if not isinstance(relates, dict) or relates.get("rel_type") != "m.thread":@@ -1984,7 +2019,7 @@ class BridgeCore:root_event_id = relates.get("event_id")if not root_event_id:return None- thread_root_ref = await self._external_post_for_matrix_event(str(root_event_id))+ thread_root_ref = await self._external_post_for_event(str(root_event_id))if thread_root_ref is None:logger.warning("[BRIDGE-OUT] no external post mapped for thread root %s; "@@ -1998,35 +2033,35 @@ class BridgeCore:self,room: RoomRef,event: TransportMedia,- client: ClientBase[Any],+ client: WorkspaceConsumer,) -> None:- """Relay a Matrix media event (an agent-sent image/file) out to the+ """Relay a room media event (an agent-sent image/file) out to theexternal channel.- Mirrors handle_outbound_message: puppet media is skipped (it originated+ Mirrors handle_outbound_message: human actor media is skipped (it originatedon the platform), the caption convention is unpacked (a `filename` keymeans the body is a caption), and the relayed post is recorded in themessage map so replies thread both ways. Any file type relays nativelyvia the adapter; a file whose bytes can't be fetched or that exceeds therelay cap gets a disclosed text notice rather than a silent drop.- A message carrying several files arrives as several Matrix events+ A message carrying several files arrives as several media eventssharing a group marker; they are buffered here and relayed as ONE- platform post. `client` is the bridge's Matrix client, used to fetch the+ platform post. `client` is the bridge's own client, used to fetch themedia bytes."""logger.debug(- "[BRIDGE-OUT] matrix media event from=%s room=%s body=%s",+ "[BRIDGE-OUT] room media from=%s room=%s body=%s",event.sender,room.room_id,event.body[:80] if event.body else "",)- if event.sender in self._puppet_matrix_ids:+ if event.sender in self._human_user_ids:return- if event.sender == self._bridge_client_matrix_user_id:+ if event.sender == self._workspace_consumer_transport_user_id:return- channel_id = self._find_channel(matrix_room_id=room.room_id)+ channel_id = self._find_channel(transport_room_id=room.room_id)if channel_id is None:logger.debug("[BRIDGE-OUT] no channel mapping for room %s", room.room_id)return@@ -2037,7 +2072,7 @@ class BridgeCore:await self._relay_outbound_media(channel_id, event, client)async def _relay_outbound_media(- self, channel_id: str, event: TransportMedia, client: ClientBase[Any]+ self, channel_id: str, event: TransportMedia, client: WorkspaceConsumer) -> None:event_content = event.contentsender_name = event.sender_name@@ -2069,7 +2104,7 @@ class BridgeCore:)message_ref: str | None- data = await self._download_matrix_media(client, event.uri, filename)+ data = await self._download_media(client, event.uri, filename)if data is None or len(data) > self._max_attachment_bytes:if data is not None:logger.warning(@@ -2213,23 +2248,24 @@ class BridgeCore:external_post_id=message_ref,)- async def _download_matrix_media(- self, client: ClientBase[Any], mxc: str | None, filename: str+ async def _download_media(+ self, client: WorkspaceConsumer, media_uri: str | None, filename: str) -> bytes | None:- """Fetch an mxc URI's bytes via the bridge client, or None on failure+ """Fetch a media URI's bytes via the workspace consumer, or None on failure(logged — the caller posts a disclosed fallback, never a silent drop)."""- if not mxc:- logger.error("[BRIDGE-OUT] media event for %s has no mxc URI", filename)+ if not media_uri:+ logger.error("[BRIDGE-OUT] media event for %s has no media URI", filename)return Noneif client.transport is None:logger.error(- "[BRIDGE-OUT] bridge client not connected; cannot fetch %s", mxc+ "[BRIDGE-OUT] workspace consumer not connected; cannot fetch %s",+ media_uri,)return Nonetry:- resp = await client.transport.download_media(mxc)+ resp = await client.transport.download_media(media_uri)except TransportError as exc:- logger.error("[BRIDGE-OUT] failed to download media %s: %s", mxc, exc)+ logger.error("[BRIDGE-OUT] failed to download media %s: %s", media_uri, exc)return Nonereturn resp.body@@ -2273,9 +2309,9 @@ class BridgeCore:# ── Message-map helpers ───────────────────────────────────────────────────def _prerecord_message_map(- self, matrix_event_id: str, external_post_id: str+ self, transport_event_id: str, external_post_id: str) -> None:- """Anchor a Matrix-event → external-post mapping in memory, synchronously,+ """Anchor a room-event → external-post mapping in memory, synchronously,so it resolves before the durable _record_message_map write commits._record_message_map awaits a DB round-trip that yields the event loop; a@@ -2285,7 +2321,7 @@ class BridgeCore:room_send returns, with NO await in between, and pop it once the row iscommitted. Same discipline as begin_provisioning for the room-mappingrace."""- self._pending_message_maps[matrix_event_id] = external_post_id+ self._pending_message_maps[transport_event_id] = external_post_idasync def _record_message_map(self,@@ -2294,7 +2330,7 @@ class BridgeCore:transport_event_id: str,external_post_id: str,) -> None:- """Persist a Matrix-event ↔ external-post correlation (idempotent)."""+ """Persist a room-event ↔ external-post correlation (idempotent)."""async with self._session_factory() as session:existing = await self._bridge_message_map_store.get_by_transport_event_id(session, self._bridge_id, transport_event_id@@ -2312,18 +2348,14 @@ class BridgeCore:)await session.commit()- async def _matrix_event_for_external_post(- self, external_post_id: str- ) -> str | None:+ async def _event_for_external_post(self, external_post_id: str) -> str | None:async with self._session_factory() as session:mapping = await self._bridge_message_map_store.get_by_external_post_id(session, self._bridge_id, external_post_id)return mapping.transport_event_id if mapping is not None else None- async def _external_post_for_matrix_event(- self, transport_event_id: str- ) -> str | None:+ async def _external_post_for_event(self, transport_event_id: str) -> str | None:pending = self._pending_message_maps.get(transport_event_id)if pending is not None:return pending@@ -2351,7 +2383,7 @@ class BridgeCore:def add_room_mapping(self,room_id: str,- matrix_room_id: str,+ transport_room_id: str,external_channel_id: str,tenant_id: str,) -> None:@@ -2364,13 +2396,13 @@ class BridgeCore:more to the point, without a read that would run under whatever tenanthappened to be bound at the time."""- key = (room_id, matrix_room_id)+ key = (room_id, transport_room_id)self._channel_to_room[external_channel_id] = keyself._room_to_channel[key] = external_channel_idself._room_tenants[room_id] = tenant_id- def remove_room_mapping(self, room_id: str, matrix_room_id: str) -> None:- key = (room_id, matrix_room_id)+ def remove_room_mapping(self, room_id: str, transport_room_id: str) -> None:+ key = (room_id, transport_room_id)channel_id = self._room_to_channel.pop(key, None)if channel_id is not None:self._channel_to_room.pop(channel_id, None)diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.pyindex 250f66835..4dc82cc5a 100644--- a/core/switch_core/bridges/collaboration/discord/adapter.py+++ b/core/switch_core/bridges/collaboration/discord/adapter.py@@ -22,7 +22,7 @@ from switch_core.bridges.collaboration.adapter import (ActivityMarkRefused,ActivitySnapshot,ChannelNotBindable,- CollaborationAdapter,+ PlatformAdapter,RemovalFailed,RequestCard,RichContent,@@ -487,7 +487,7 @@ class DiscordConnectionConfig(BridgeConnectionConfig):return self-class DiscordAdapter(CollaborationAdapter):+class DiscordAdapter(PlatformAdapter):"""Discord collaboration bridge adapter.Single-bot identity model like Slack: all agents post through one bot@@ -579,7 +579,7 @@ class DiscordAdapter(CollaborationAdapter):)# Fired the moment a shared connection is attached, so the start-time# work that needed it (agent-identity provisioning) can re-run. Set by- # BridgeCore; None on an own-connection bridge, which is never attached.+ # CollaborationCore; None on an own-connection bridge, which is never attached.self._on_attached: Callable[[], None] | None = None# (channel id, webhook name) -> webhook the bridge posts through there.self._webhooks: dict[tuple[int, str], discord.Webhook] = {}@@ -849,7 +849,7 @@ class DiscordAdapter(CollaborationAdapter):"""Post `content` as however many messages Discord's 2,000-char cap needs.Returns the ref of the FIRST message. That is the one the bridge maps- the Matrix event to, so a reply threads under the start of what was+ the room event to, so a reply threads under the start of what wassaid rather than its tail, and a thread created from it opens where themessage begins.diff --git a/core/switch_core/bridges/collaboration/discord/gateway.py b/core/switch_core/bridges/collaboration/discord/gateway.pyindex 6b9c982eb..972f15e48 100644--- a/core/switch_core/bridges/collaboration/discord/gateway.py+++ b/core/switch_core/bridges/collaboration/discord/gateway.py@@ -27,7 +27,7 @@ from typing import Anyimport discordfrom switch_core.bridges.agent.commands import Command as InRoomCommand-from switch_core.bridges.collaboration.adapter import CollaborationAdapter+from switch_core.bridges.collaboration.adapter import PlatformAdapterfrom switch_core.bridges.collaboration.discord.adapter import (ALLOWED_MESSAGE_TYPES,DiscordAdapter,@@ -106,7 +106,7 @@ class DiscordGatewayClient:def connection(self) -> DiscordConnection:return self._connection- def attach_if_live(self, adapter: CollaborationAdapter) -> None:+ def attach_if_live(self, adapter: PlatformAdapter) -> None:"""Hand a starting Discord bridge the shared connection, if it is up.Called as each bridge starts, before anything in it runs, so a newdiff --git a/core/switch_core/bridges/collaboration/install.py b/core/switch_core/bridges/collaboration/install.pyindex 28e912f42..736cf7117 100644--- a/core/switch_core/bridges/collaboration/install.py+++ b/core/switch_core/bridges/collaboration/install.py@@ -1,6 +1,6 @@"""Installing *our* app into someone else's workspace.-A `CollaborationAdapter` is what a bridge runs; this is what happens before+A `PlatformAdapter` is what a bridge runs; this is what happens beforethere is one. The distinction is not organisational — the two have genuinelydifferent lifetimes and genuinely different secrets:diff --git a/core/switch_core/bridges/collaboration/install_service.py b/core/switch_core/bridges/collaboration/install_service.pyindex c5a256d41..352b9b5df 100644--- a/core/switch_core/bridges/collaboration/install_service.py+++ b/core/switch_core/bridges/collaboration/install_service.py@@ -57,7 +57,7 @@ from dataclasses import dataclassfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.collaboration.adapter import CollaborationAdapter+from switch_core.bridges.collaboration.adapter import PlatformAdapterfrom switch_core.bridges.collaboration.install import (InboundWebhook,MessagingAppInstaller,@@ -132,7 +132,7 @@ class WebhookTarget:tenant_id: strplatform: strbridge_id: str- adapter: CollaborationAdapter+ adapter: PlatformAdapterclass InstallPlatformMismatch(RuntimeError):@@ -464,7 +464,7 @@ class MessagingInstallService:## The split is what lets the route acknowledge in time. Slack gives three# seconds and retries what it does not get an answer to, so a handler that- # posts to Matrix before replying turns one slow room into duplicate+ # posts to the room before replying turns one slow room into duplicate# messages. Everything up to and including `resolve` is fast enough to# answer inside, and `deliver` runs after the response has gone.diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.pyindex 66d1d08ec..51b24c07e 100644--- a/core/switch_core/bridges/collaboration/lifecycle_service.py+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py@@ -12,16 +12,20 @@ import aiohttpimport httpxfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.collaboration.adapter import CollaborationAdapter-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.adapter import PlatformAdapter+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.ingress import CallbackEndpoint, CallbackIngressfrom switch_core.bridges.collaboration.models import (BridgeConnectionConfig,BridgeCredentialError,BridgeOperationError,)-from switch_core.clients.bridge_client import BridgeClient, BridgeClientConfig+from switch_core.clients.actor import Actorfrom switch_core.clients.client_factory import ClientFactory+from switch_core.clients.workspace_consumer import (+ WorkspaceConsumer,+ WorkspaceConsumerConfig,+)from switch_core.config import SwitchConfigfrom switch_core.db.models import CollaborationBridgefrom switch_core.db.session_scope import tenant_session@@ -45,11 +49,13 @@ from switch_core.telemetry.snapshot import PLATFORMS, normalise_platformfrom switch_core.tenant_context import current_tenant_id, no_tenantif TYPE_CHECKING:- from switch_core.bridges.agent.protocol.connections import ConnectionRegistry+ from switch_core.bridges.agent.protocol.agent_connections import (+ AgentConnectionRegistry,+ )from switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.room_service import RoomService- from switch_core.session_activity.listener import SessionActivityListener- from switch_core.session_activity.service import SessionActivityService+ from switch_core.session_activity.listener import AgentSessionActivityListener+ from switch_core.session_activity.service import AgentSessionActivityService# Every platform SDK below is registered dynamically (`register_adapter`), so a# deployment that only wires up some of the five is plausible even though@@ -240,7 +246,7 @@ def _failure_reason(exc: BaseException) -> str:return "network"# These four are each a platform's own SDK saying it was reached and it- # refused — never Switch's homeserver or database, which speak neither+ # refused, never Switch's own database, which speaks neither# vendor's exception language, so the label stays accurate even though the# check is broad.if isinstance(exc, BridgeOperationError):@@ -265,20 +271,14 @@ def _failure_reason(exc: BaseException) -> str:return "unknown"-def _bridge_client_localpart(bridge_type: str, display_name: str) -> str:- """The Matrix localpart for a messaging app's own client.+def _workspace_consumer_localpart(bridge_type: str, display_name: str) -> str:+ """The localpart for a messaging app's own client.The random tail is what makes disconnecting and reconnecting work. Thereadable part is derived from the app's type and name, which an operator is- free to reuse — and the homeserver has no API for removing an account, so- the old one is still there when they do. Reusing the name meant either- colliding with it, or adopting an account whose password Switch no longer- holds: shared-secret registration reports an existing user as success- without applying the new one, so the second reads as a working connection- that can never log in.-- A fresh name each time costs an abandoned account on the homeserver, which- is already the case and is logged on removal.+ free to reuse, and ids are stable handles that existing history points at.+ A fresh name each time keeps a reconnection from colliding with an id the+ last connection already issued."""safe_name = re.sub(r"[^a-z0-9._=-]", "-", display_name.lower())[:16]return f"switch-bridge-{bridge_type}-{safe_name}-{uuid4().hex[:8]}"@@ -316,13 +316,13 @@ class CollaborationBridgeLifecycleService:client_store: ClientStore,client_lifecycle: ClientLifecycleService,room_service: RoomService,- matrix_admin: Provisioning,+ provisioning: Provisioning,session_factory: async_sessionmaker[AsyncSession],config: SwitchConfig,client_factory: ClientFactory,- session_activity_listener: SessionActivityListener,- session_activity_service: SessionActivityService,- connections: ConnectionRegistry,+ session_activity_listener: AgentSessionActivityListener,+ session_activity_service: AgentSessionActivityService,+ connections: AgentConnectionRegistry,telemetry: TelemetryService | None = None,) -> None:self._bridge_store = bridge_store@@ -334,21 +334,19 @@ class CollaborationBridgeLifecycleService:self._client_lifecycle = client_lifecycleself._telemetry = telemetryself._room_service = room_service- self._matrix_admin = matrix_admin+ self._provisioning = provisioningself._session_factory = session_factoryself._config = configself._client_factory = client_factoryself._session_activity_listener = session_activity_listenerself._session_activity_service = session_activity_serviceself._connections = connections- self._bridge_starting_listeners: list[- Callable[[CollaborationAdapter], None]- ] = []+ self._bridge_starting_listeners: list[Callable[[PlatformAdapter], None]] = []self._bridge_start_guards: list[BridgeStartGuard] = []- self._adapter_registry: dict[str, type[CollaborationAdapter]] = {}+ self._adapter_registry: dict[str, type[PlatformAdapter]] = {}self._config_registry: dict[str, type[BridgeConnectionConfig]] = {}- self._bridges: dict[str, BridgeCore] = {}+ self._bridges: dict[str, CollaborationCore] = {}self._tasks: dict[str, asyncio.Task[None]] = {}# How many times each bridge has failed to come up since this# process started. See `_note_connect_failure`.@@ -359,7 +357,7 @@ class CollaborationBridgeLifecycleService:# `_connect_duration_ms`.self._connect_started: dict[str, float] = {}# Read off the row at start, so reporting never depends on what the- # BridgeCore exposes.+ # CollaborationCore exposes.self._bridge_facts: dict[str, tuple[str, object]] = {}# Bridges the deployment's setup step registered rather than a person,# read off the row at start like `_bridge_facts`. Onboarding telemetry@@ -369,7 +367,7 @@ class CollaborationBridgeLifecycleService:# Reached the platform, as opposed to merely started.self._connected: set[str] = set()# bridge_id -> the host resource it holds exclusively while running- # (see CollaborationAdapter.exclusive_resource). Lets a second+ # (see PlatformAdapter.exclusive_resource). Lets a second# claimant be refused by name instead of failing on the resource.self._held_resources: dict[str, str] = {}# Started and not deliberately stopped. A crash removes a bridge from@@ -400,7 +398,8 @@ class CollaborationBridgeLifecycleService:## A process-wide lock is sufficient *because* switch-core is a# singleton: the chart fails the render for replicaCount != 1, since- # it holds live Matrix sessions in memory. If that ever changes, this+ # it keeps delivery state (event buffers, the invite and presence+ # buses, the message listener) in memory. If that ever changes, this# has to become a database constraint — the way the single-default# bridge invariant already is — because a lock in one process would# then be guarding nothing.@@ -409,7 +408,7 @@ class CollaborationBridgeLifecycleService:def register_adapter(self,bridge_type: str,- adapter_cls: type[CollaborationAdapter],+ adapter_cls: type[PlatformAdapter],config_cls: type[BridgeConnectionConfig],) -> None:self._adapter_registry[bridge_type] = adapter_cls@@ -418,7 +417,7 @@ class CollaborationBridgeLifecycleService:def get_registered_types(self) -> list[str]:return list(self._adapter_registry.keys())- def get_adapter(self, bridge_id: str) -> CollaborationAdapter | None:+ def get_adapter(self, bridge_id: str) -> PlatformAdapter | None:"""The live adapter for a running bridge, or None if it isn't running.Used to ask a platform for a channel deeplink without the caller having@@ -427,7 +426,7 @@ class CollaborationBridgeLifecycleService:return bridge.adapter if bridge is not None else Nonedef add_bridge_starting_listener(- self, listener: Callable[[CollaborationAdapter], None]+ self, listener: Callable[[PlatformAdapter], None]) -> None:"""Be handed each bridge's adapter as it starts, before it runs.@@ -466,7 +465,7 @@ class CollaborationBridgeLifecycleService:connection_config=connection_config,)- def iter_adapters(self) -> Iterator[CollaborationAdapter]:+ def iter_adapters(self) -> Iterator[PlatformAdapter]:"""The live adapter of every running bridge, as a snapshot.Platform-agnostic on purpose: a caller narrows with `isinstance` to the@@ -753,20 +752,20 @@ class CollaborationBridgeLifecycleService:# whose failures are logged and swallowed, so credentials that are wrong# would otherwise be stored, reported as success, and only surface later# as an unrelated-looking error. Failing here also avoids leaving an- # orphan Matrix identity behind for a bridge that was never viable.+ # orphan client identity behind for a bridge that was never viable.await adapter_cls.verify_credentials(connection_config)- bridge_client_record = await self._client_lifecycle.create_client(+ workspace_consumer_record = await self._client_lifecycle.create_client(client_type="bridge",display_name=f"bridge-{bridge_type}-{display_name}",- localpart=_bridge_client_localpart(bridge_type, display_name),+ localpart=_workspace_consumer_localpart(bridge_type, display_name),)bridge = CollaborationBridge(type=bridge_type,display_name=display_name,connection_config=connection_config, # type: ignore[arg-type]- client_id=bridge_client_record.id,+ client_id=workspace_consumer_record.id,status="active",channel_creation_enabled=channel_creation_enabled,preconfigured=preconfigured,@@ -901,13 +900,13 @@ class CollaborationBridgeLifecycleService:)async with tenant_session(self._session_factory, tenant_id) as session:- bridge_client_record = await self._client_store.get(+ workspace_consumer_record = await self._client_store.get(session, bridge.client_id)- if bridge_client_record is None:+ if workspace_consumer_record is None:raise ValueError(f"Bridge client not found: {bridge.client_id}")- bridge_core = BridgeCore(+ collaboration_core = CollaborationCore(bridge_id=bridge_id,bridge_tenant_id=tenant_id,bridge_type=bridge.type,@@ -920,10 +919,10 @@ class CollaborationBridgeLifecycleService:client_store=self._client_store,room_service=self._room_service,client_lifecycle=self._client_lifecycle,- matrix_admin=self._matrix_admin,+ provisioning=self._provisioning,session_factory=self._session_factory,- matrix_server_name=self._config.matrix_server_name,- bridge_client_matrix_user_id=bridge_client_record.matrix_user_id,+ id_server_name=self._config.id_server_name,+ workspace_consumer_transport_user_id=workspace_consumer_record.transport_user_id,max_attachment_bytes=self._config.agent_media_max_bytes,gateway_public_url=self._config.gateway_public_url,session_activity_listener=self._session_activity_listener,@@ -931,16 +930,18 @@ class CollaborationBridgeLifecycleService:connections=self._connections,)- bridge_client = BridgeClient(- bridge_core=bridge_core,- client_id=bridge_client_record.id,- tenant_id=bridge_client_record.tenant_id,- matrix_user_id=bridge_client_record.matrix_user_id,- display_name=bridge_client_record.display_name,- session_factory=self._session_factory,- client_store=self._client_store,- config=BridgeClientConfig(bridge_id=bridge_id),- transport_factory=self._client_factory.transport_for,+ workspace_consumer = WorkspaceConsumer(+ collaboration_core=collaboration_core,+ actor=Actor(+ client_id=workspace_consumer_record.id,+ tenant_id=workspace_consumer_record.tenant_id,+ transport_user_id=workspace_consumer_record.transport_user_id,+ display_name=workspace_consumer_record.display_name,+ session_factory=self._session_factory,+ client_store=self._client_store,+ config=WorkspaceConsumerConfig(bridge_id=bridge_id),+ transport_factory=self._client_factory.transport_for,+ ),)for listener in self._bridge_starting_listeners:@@ -954,9 +955,11 @@ class CollaborationBridgeLifecycleService:else:self._preconfigured.discard(bridge_id)task = asyncio.create_task(- self._run_bridge(bridge_id, tenant_id, bridge_core, bridge_client)+ self._run_bridge(+ bridge_id, tenant_id, collaboration_core, workspace_consumer+ ))- self._bridges[bridge_id] = bridge_core+ self._bridges[bridge_id] = collaboration_coreself._tasks[bridge_id] = taskself._started.add(bridge_id)self._platforms_seen.add(normalise_platform(bridge.type))@@ -977,6 +980,7 @@ class CollaborationBridgeLifecycleService:self._telemetry,"bridge_connected",{+ "bridge": "collaboration","bridge_platform": platform,"outcome": "failure","failure_reason": reason,@@ -1014,7 +1018,7 @@ class CollaborationBridgeLifecycleService:"""Make the bridge's rooms its recorded memberships before it starts.A bridge belongs in every room it carries, and that was expressed by- inviting its client and letting the homeserver hold the membership —+ inviting its client and letting the message bus hold the membership,so nothing wrote it down. Once `client_rooms` became what a clientreads its rooms from, a bridge that had never been re-invited was innone of them: it still received from the platform, because inbound@@ -1044,8 +1048,8 @@ class CollaborationBridgeLifecycleService:self,bridge_id: str,tenant_id: str,- bridge_core: BridgeCore,- bridge_client: BridgeClient,+ collaboration_core: CollaborationCore,+ workspace_consumer: WorkspaceConsumer,) -> None:"""The bridge's own long-lived task.@@ -1054,8 +1058,8 @@ class CollaborationBridgeLifecycleService:often as from boot, so without this the bridge would spend its wholelife acting as the operator who happened to restart it. Nothing hereis ambient afterwards: `_record_bridge_memberships` binds the bridge's- tenant for its own writes, `BridgeCore.start` binds it around each- piece of bridge-level loading it does, and `bridge_client.start()` —+ tenant for its own writes, `CollaborationCore.start` binds it around each+ piece of bridge-level loading it does, and `workspace_consumer.start()` —which runs until shutdown — binds nothing at all, leaving eachdelivery to bind the tenant of the room it is for."""@@ -1064,15 +1068,15 @@ class CollaborationBridgeLifecycleService:connected = Falsetry:await self._record_bridge_memberships(- bridge_id, tenant_id, bridge_client.client_id+ bridge_id, tenant_id, workspace_consumer.client_id)- await bridge_core.start()+ await collaboration_core.start()# The one point that means "connected": `start()` only- # launched this task and `bridge_client.start()` never returns.+ # launched this task and `workspace_consumer.start()` never returns.connected = Trueself._connected.add(bridge_id)await self._report_connector_up(bridge_id, platform, configured_at)- await bridge_client.start()+ await workspace_consumer.start()except Exception as exc:logger.exception("Bridge %s crashed", bridge_id)self._bridges.pop(bridge_id, None)@@ -1097,6 +1101,7 @@ class CollaborationBridgeLifecycleService:self._telemetry,"bridge_disconnected",{+ "bridge": "collaboration","bridge_platform": normalise_platform(platform),"reason": reason,},@@ -1108,6 +1113,7 @@ class CollaborationBridgeLifecycleService:self._telemetry,"bridge_connected",{+ "bridge": "collaboration","bridge_platform": normalise_platform(platform),"outcome": "failure","failure_reason": reason,@@ -1157,6 +1163,7 @@ class CollaborationBridgeLifecycleService:self._telemetry,"bridge_connected",{+ "bridge": "collaboration","bridge_platform": normalise_platform(platform),"outcome": "success","failure_reason": "none",@@ -1236,11 +1243,11 @@ class CollaborationBridgeLifecycleService:endpoint = self._callback_endpoints.pop(bridge_id, None)if endpoint is not None:await endpoint.withdraw()- bridge_core = self._bridges.get(bridge_id)+ collaboration_core = self._bridges.get(bridge_id)was_connected = bridge_id in self._connectedself._connected.discard(bridge_id)- if bridge_core:- await bridge_core.stop()+ if collaboration_core:+ await collaboration_core.stop()task = self._tasks.pop(bridge_id, None)if task and not task.done():@@ -1259,12 +1266,13 @@ class CollaborationBridgeLifecycleService:# `_bridges` membership is set before the connection is attempted, so# on its own it would report a bridge that never connected.- if bridge_core is not None and was_connected:+ if collaboration_core is not None and was_connected:platform, _ = self._bridge_facts.get(bridge_id, ("none", None))emit_safely(self._telemetry,"bridge_disconnected",{+ "bridge": "collaboration","bridge_platform": normalise_platform(platform),"reason": reason,},@@ -1289,9 +1297,9 @@ class CollaborationBridgeLifecycleService:"""Disconnect a messaging app and take its identities with it.Everything Switch created to talk to this platform goes: the bridge's- own Matrix client, and the puppet client behind every person Switch saw- on it. Leaving those behind is not a tidiness problem — the bridge- client's Matrix name is derived from the app's type and display name,+ own client, and the human actor behind every person Switch saw+ on it. Leaving those behind is not a tidiness problem: the bridge+ client's name is derived from the app's type and display name,so an operator who disconnects an app and reconnects one named the samecollided with the row left by the last one.@@ -1309,9 +1317,11 @@ class CollaborationBridgeLifecycleService:await self.stop(bridge_id)async with self._session_factory() as session:bridge = await self._bridge_store.get(session, bridge_id)- puppets = await self._external_user_store.get_by_bridge(session, bridge_id)+ human_actors = await self._external_user_store.get_by_bridge(+ session, bridge_id+ )- removed = [u.client_id for u in puppets if u.client_id]+ removed = [u.client_id for u in human_actors if u.client_id]if bridge is not None:removed.append(bridge.client_id)for client_id in removed:@@ -1336,14 +1346,8 @@ class CollaborationBridgeLifecycleService:await self._client_lifecycle.delete_record(session, client_id)await session.commit()- # The Matrix accounts themselves outlive this: the homeserver offers no- # deprovisioning call Switch can make. Said out loud because it is the- # reason a reconnection cannot reuse the old name — see- # `_bridge_client_localpart`.logger.info(- "Removed collaboration bridge %s and %d client identities; their "- "Matrix accounts remain on the homeserver, which has no API to "- "remove them",+ "Removed collaboration bridge %s and %d client identities",bridge_id,len(removed),)@@ -1371,26 +1375,26 @@ class CollaborationBridgeLifecycleService:self._connect_failures.pop(bridge_id, None)self._connect_started.pop(bridge_id, None)- def get(self, bridge_id: str) -> BridgeCore | None:+ def get(self, bridge_id: str) -> CollaborationCore | None:"""The running bridge for ``bridge_id``, if it is the bound tenant's.The registry holds every tenant's bridges, so a caller acting for onetenant must not be handed another's. With no tenant bound (boot andthe per-tenant fan-outs) there is nothing to compare against."""- bridge_core = self._bridges.get(bridge_id)- if bridge_core is None:+ collaboration_core = self._bridges.get(bridge_id)+ if collaboration_core is None:return Nonebound = current_tenant_id()- if bound is not None and bridge_core.tenant_id != bound:+ if bound is not None and collaboration_core.tenant_id != bound:logger.warning("Refused bridge %s to tenant %s: it belongs to tenant %s",bridge_id,bound,- bridge_core.tenant_id,+ collaboration_core.tenant_id,)return None- return bridge_core+ return collaboration_coredef expected_count(self) -> int:"""Bridges that were started and have not been stopped deliberately."""@@ -1415,7 +1419,7 @@ class CollaborationBridgeLifecycleService:The total answers "how many bridges died" and never "which", and whichis the first thing anyone asks — a Slack outage and a misconfiguredTeams app look identical in a single number. Read off `_bridge_facts`,- which is written at start from the row, so a bridge whose `BridgeCore`+ which is written at start from the row, so a bridge whose `CollaborationCore`has already been discarded by a crash is still attributable.Every platform this process has ever started a bridge for appears,@@ -1440,7 +1444,7 @@ class CollaborationBridgeLifecycleService:counts[name] = counts.get(name, 0) + (1 if alive else 0)return counts- def bridges_for_tenant(self, tenant_id: str) -> list[BridgeCore]:+ def bridges_for_tenant(self, tenant_id: str) -> list[CollaborationCore]:"""Running bridges belonging to `tenant_id`, and none other.`_bridges` is a flat, instance-wide dict, so this is the only way todiff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.pyindex e6b3c1810..a19f11b29 100644--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py@@ -32,7 +32,7 @@ from switch_core.agent_icon import default_icon_urlfrom switch_core.bridges.collaboration.adapter import (ActivityMark,ActivitySnapshot,- CollaborationAdapter,+ PlatformAdapter,RemovalFailed,RequestCard,RichContent,@@ -266,7 +266,7 @@ def _ephemeral(text: str) -> dict[str, Any]:return {"ephemeral_text": text, "skip_slack_parsing": True}-class MattermostAdapter(CollaborationAdapter):+class MattermostAdapter(PlatformAdapter):draws_session_activity: ClassVar[bool] = True#: A problem somebody has to act on still gets its own reply, so it@@ -522,7 +522,7 @@ class MattermostAdapter(CollaborationAdapter):name = await self._username_for(press.user_id)if name is None:# Refused rather than attributed to the raw id: the id is what the- # answer is judged against, but the name is what a puppet is+ # answer is judged against, but the name is what a human actor is# created under, and inventing one from an id makes a person who# cannot be looked up into a permanent participant named after a# lookup failure.@@ -1959,8 +1959,8 @@ class MattermostAdapter(CollaborationAdapter):async def get_external_user_id(self, username: str) -> str | None:"""Resolve a platform username to its current user id, or None if the- user does not exist. Used by the homeserver cutover to rebind a puppet's- ``external_user_id`` when Mattermost has been rebuilt and ids changed."""+ user does not exist. Used to rebind a human actor's ``external_user_id`` when+ Mattermost has been rebuilt and ids changed."""if not self._admin_driver or not self._main_loop:raise RuntimeError("Mattermost client not connected")try:diff --git a/core/switch_core/bridges/collaboration/models.py b/core/switch_core/bridges/collaboration/models.pyindex 5b53062ca..815e5a706 100644--- a/core/switch_core/bridges/collaboration/models.py+++ b/core/switch_core/bridges/collaboration/models.py@@ -42,8 +42,8 @@ class WebhookDeliveryUnsupported(RuntimeError):class Attachment(BaseModel):"""An inbound file attachment of any type, with its raw bytes.- `data` holds the downloaded file content; the bridge uploads it to the- Matrix media repository and discards the bytes afterwards.+ `data` holds the downloaded file content; the bridge stores it in+ Switch's media store and discards the bytes afterwards."""filename: str@@ -124,7 +124,7 @@ class InboundCommand(BaseModel):command: strargs: str# External platform's id for the command post (Mattermost post_id), so the- # command's bridged Matrix event can be mapped back to it and the result+ # command's bridged room event can be mapped back to it and the result# can be threaded under the originating command message. None when the# platform gives us no post id.message_ref: str | None = Nonediff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.pyindex 9a41ec5a0..74f9273e3 100644--- a/core/switch_core/bridges/collaboration/slack/adapter.py+++ b/core/switch_core/bridges/collaboration/slack/adapter.py@@ -22,7 +22,7 @@ from slack_sdk.web.async_client import AsyncWebClientfrom switch_core.bridges.collaboration.adapter import (ActivityMark,- CollaborationAdapter,+ PlatformAdapter,RemovalFailed,RequestCard,RichContent,@@ -326,7 +326,7 @@ class _ActivityStream:blocks: dict[str, dict[str, Any]] = field(default_factory=dict)-class SlackAdapter(CollaborationAdapter):+class SlackAdapter(PlatformAdapter):draws_session_activity: ClassVar[bool] = Trueseparate_attention_slot: ClassVar[bool] = Truechannel_mention: ClassVar[str | None] = "<!channel>"@@ -569,7 +569,7 @@ class SlackAdapter(CollaborationAdapter):) -> str | None:"""Post a Block Kit message, for what plain text cannot carry.- Slack-only and deliberately not on `CollaborationAdapter`: blocks are+ Slack-only and deliberately not on `PlatformAdapter`: blocks areSlack's own shape, and the platforms that need something like them needsomething different. `text` is what a notification and a client thatwill not render the blocks are left with, so it has to stand alone.@@ -1634,7 +1634,7 @@ class SlackAdapter(CollaborationAdapter):their name in the comment. The upload's shared-message ts is pulledfrom the response when Slack provides it (v2 completes the shareasynchronously, so it may be absent — then no ref is returned and- replies to the file won't thread back to Matrix).+ replies to the file won't thread back to the room)."""if not self._web_client:logger.error("Cannot send attachment: Slack client not connected")@@ -2823,7 +2823,7 @@ class SlackAdapter(CollaborationAdapter):self._last_user_message_ts[channel_id] = message_ts# App/bot posts (e.g. Datadog) carry no `user`; their identity lives in- # bot_id + bot_profile/username. Key the puppet on the stable bot_id and+ # bot_id + bot_profile/username. Key the human actor on the stable bot_id and# name it from the app's profile.bot_id = str(event.get("bot_id", ""))if not user_id and bot_id:diff --git a/core/switch_core/bridges/collaboration/teams/README.md b/core/switch_core/bridges/collaboration/teams/README.mdindex e6cba5ff2..2e98a8655 100644--- a/core/switch_core/bridges/collaboration/teams/README.md+++ b/core/switch_core/bridges/collaboration/teams/README.md@@ -31,7 +31,7 @@ listener:**Identity model:** a single Azure bot backs every Switch agent (like Slack).Each agent's messages render as an **Adaptive Card** headed with the agent's name-and avatar. Human users map to Matrix puppets keyed on their AAD object id. Both+and avatar. Human users map to human actors keyed on their AAD object id. Bothinbound paths funnel through one delivery + de-duplication path (keyed on theTeams message id); the bot's own posts are dropped to prevent loops.diff --git a/core/switch_core/bridges/collaboration/teams/adapter.py b/core/switch_core/bridges/collaboration/teams/adapter.pyindex c3284761c..03cff1ba8 100644--- a/core/switch_core/bridges/collaboration/teams/adapter.py+++ b/core/switch_core/bridges/collaboration/teams/adapter.py@@ -24,7 +24,7 @@ from pydantic.json_schema import SkipJsonSchemafrom switch_core.bridges.agent.commands import COMMANDS_BY_NAMEfrom switch_core.bridges.collaboration.adapter import (- CollaborationAdapter,+ PlatformAdapter,RemovalFailed,RequestCard,RichContent,@@ -562,7 +562,7 @@ class TeamsConnectionConfig(BridgeConnectionConfig):return self-class TeamsAdapter(CollaborationAdapter):+class TeamsAdapter(PlatformAdapter):"""Microsoft Teams collaboration adapter.Single-bot identity model (like Slack): one Azure bot app backs every Switch@@ -639,8 +639,8 @@ class TeamsAdapter(CollaborationAdapter):)if any(prepared.get(k) for k in keys):return prepared- # RSA keygen is CPU-bound and switch-core runs every live Matrix- # session on this loop, so it does not run on it.+ # RSA keygen is CPU-bound and switch-core runs every live client on+ # this loop, so it does not run on it.cert_pem, key_pem = await asyncio.to_thread(generate_encryption_keypair)prepared["encryption_certificate_id"] = f"switch-teams-{secrets.token_hex(8)}"prepared["encryption_public_certificate"] = cert_pem@@ -1166,7 +1166,7 @@ class TeamsAdapter(CollaborationAdapter):A caller that named a thread knows better than we do and wins. Whatthis covers is the caller that named none, which is any agent whose- reply was not itself threaded in Matrix: answer in the post the bridge+ reply was not itself threaded in the room: answer in the post the bridgelast saw this channel speak in, rather than opening a new one.The limitation, stated because it is real: "last" is per channel, so@@ -2278,7 +2278,7 @@ class TeamsAdapter(CollaborationAdapter):Teams omits the sender's name from some activities — 1:1 chats aboveall — and the fallback was the raw id, so `29:1AbCdEf…` became a- person's name: in the room title, on their Matrix account, and in the+ person's name: in the room title, on their client, and in thetext of every agent reply that addressed them. An id is never a name,so look one up instead, and only give up when Graph cannot say either.diff --git a/core/switch_core/bridges/collaboration/telegram/adapter.py b/core/switch_core/bridges/collaboration/telegram/adapter.pyindex 4ec226922..92bd2d9fc 100644--- a/core/switch_core/bridges/collaboration/telegram/adapter.py+++ b/core/switch_core/bridges/collaboration/telegram/adapter.py@@ -38,7 +38,7 @@ from switch_core.bridges.agent.commands import COMMANDS, COMMANDS_BY_NAME, Commafrom switch_core.bridges.collaboration.adapter import (ActivityMark,ActivityMarkRefused,- CollaborationAdapter,+ PlatformAdapter,RemovalFailed,RequestCard,RichContent,@@ -441,7 +441,7 @@ class TelegramConnectionConfig(BridgeConnectionConfig):bot_username: str-class TelegramAdapter(CollaborationAdapter):+class TelegramAdapter(PlatformAdapter):"""Telegram collaboration bridge adapter.Single-bot identity model. Telegram has no per-message identity override —diff --git a/core/switch_core/clients/actor.py b/core/switch_core/clients/actor.pynew file mode 100644index 000000000..1e8e94f63--- /dev/null+++ b/core/switch_core/clients/actor.py@@ -0,0 +1,429 @@+"""Who a message is from: a room member's identity, and what it can write.++An actor is one row in `clients` seen from the running process: an id, a name,+the rooms it belongs to, and a transport to write through. It reads nothing.+Reading is a `Consumer`'s job, and a consumer is built around the actor whose+rooms it reads, so members that only ever write (a Slack person's+`HumanActor`) run no read loop at all.+"""++from __future__ import annotations++import asyncio+import logging+import time+from typing import TYPE_CHECKING, ClassVar, Literal, TypedDict, Unpack++from pydantic import BaseModel+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.clients.admin_messages import (+ PLATFORM_MARKER,+ AdminMessageType,+ OnBehalfOf,+ admin_extra_content,+)+from switch_core.db.stores.client_store import ClientStore+from switch_core.transport import MessageTransport, TransportError++if TYPE_CHECKING:+ from collections.abc import Callable++ from switch_core.db.models import Agent++logger = logging.getLogger(__name__)++# How often `wait_joined` re-reads membership while it waits. An actor with a+# consumer hears its own join as it happens; one without has only this.+MEMBERSHIP_POLL_SECONDS = 0.25+++class ClientConfig(BaseModel):+ pass+++class ActorKwargs[ConfigT: ClientConfig](TypedDict):+ """What every `Actor` subclass must forward to `Actor`.++ Subclasses take their own arguments and pass the rest through. Spelled as+ `**kwargs: Any`, that pass-through is invisible to the type checker on both+ sides: the subclass cannot be told it is missing something, and a caller+ cannot be told it is passing something that no longer exists. A stale+ `device_id=` type-checked clean that way and took all four collaboration+ bridges down at startup — the credential had moved elsewhere and nothing+ said so until the process refused to start.+ """++ client_id: str+ tenant_id: str+ transport_user_id: str+ display_name: str+ session_factory: async_sessionmaker[AsyncSession]+ client_store: ClientStore+ config: ConfigT+ transport_factory: Callable[[Actor[ConfigT]], MessageTransport]+++# Who an actor is, as message metrics report it: the writer of a sent message+# and the reader of a delivered one. A plain `Actor` is a collaboration bridge's+# own member, the identity its `WorkspaceConsumer` reads for.+type ActorRole = Literal["human", "agent", "system", "bridge"]+++class Actor[ConfigT: ClientConfig]:+ config_class: type[ConfigT] = ClientConfig # type: ignore[assignment]+ role: ClassVar[ActorRole] = "bridge"++ def __init__(+ self,+ *,+ client_id: str,+ tenant_id: str,+ transport_user_id: str,+ display_name: str,+ session_factory: async_sessionmaker[AsyncSession],+ client_store: ClientStore,+ config: ConfigT,+ transport_factory: Callable[[Actor[ConfigT]], MessageTransport],+ ) -> None:+ self.client_id = client_id+ # The tenant of this actor's own row, carried rather than looked up.+ # An actor's task binds nothing on purpose and a consumer's handlers+ # bind some *room's* tenant, so neither context answers "which tenant+ # is this actor" — but every caller that builds one is holding the row+ # that says, so the answer travels with it instead of being asked of+ # the database again on the far side. Required, not defaulted: an+ # actor that does not know its tenant cannot write a scoped row.+ self.tenant_id = tenant_id+ self.transport_user_id = transport_user_id+ self.display_name = display_name+ self.session_factory = session_factory+ self.client_store = client_store+ self.config = config++ self._transport_factory = transport_factory+ self.transport: MessageTransport | None = None+ self.room_join_times: dict[str, int] = {}+ self._room_joined_events: dict[str, asyncio.Event] = {}+ self._ready = asyncio.Event()+ self._connected_at: int = 0++ async def connect(self) -> None:+ """Open the transport. Idempotent: a consumer connects the actor it+ reads for, and the lifecycle connects an actor that has none."""+ if self.transport is not None:+ return+ self._connected_at = int(time.time() * 1000)+ self.transport = self._transport_factory(self)+ await self.transport.connect()+ self._ready.set()++ async def close(self) -> None:+ if self.transport is not None:+ await self.transport.close()++ async def wait_ready(self) -> None:+ await self._ready.wait()++ async def set_display_name(self, display_name: str) -> None:+ """Change the name this actor shows under.++ The user id is an address and stays put; this is the label rooms+ render. Used to correct a human filed under a platform id before the+ platform would say who the person was.+ """+ await self._transport.set_display_name(display_name)+ self.display_name = display_name++ @property+ def _transport(self) -> MessageTransport:+ if self.transport is None:+ raise RuntimeError(+ f"Actor {self.transport_user_id} is not connected — call connect() first"+ )+ return self.transport++ # ── Membership ─────────────────────────────────────────────────────────────++ def _joined_event(self, room_id: str) -> asyncio.Event:+ event = self._room_joined_events.get(room_id)+ if event is None:+ event = asyncio.Event()+ self._room_joined_events[room_id] = event+ return event++ def mark_joined(self, room_id: str, joined_at_ms: int) -> None:+ self.room_join_times[room_id] = joined_at_ms+ self._joined_event(room_id).set()++ async def _is_joined_on_server(self, room_id: str) -> bool:+ return room_id in await self._transport.joined_rooms()++ async def wait_joined(self, room_id: str, timeout: float) -> bool:+ """Block until this actor is a member of `room_id`, up to `timeout`+ seconds. Returns True if joined, False on timeout. Callers that need to+ *send* into a room they have only just been invited to must await this+ first: any event that lands before a member's join is filtered out by+ the readers of that room.++ Membership is read, not only waited for. A join that predates the+ process is never redelivered, re-inviting an existing member is a+ no-op, and an actor with no consumer hears no joins at all — so the+ rows are checked on entry and again every `MEMBERSHIP_POLL_SECONDS`.+ """+ event = self._joined_event(room_id)+ if event.is_set():+ return True+ if await self._is_joined_on_server(room_id):+ self.mark_joined(room_id, self._connected_at)+ return True+ loop = asyncio.get_running_loop()+ deadline = loop.time() + timeout+ while True:+ remaining = deadline - loop.time()+ if remaining <= 0:+ return False+ try:+ await asyncio.wait_for(+ event.wait(), min(MEMBERSHIP_POLL_SECONDS, remaining)+ )+ return True+ except TimeoutError:+ pass+ if deadline - loop.time() <= 0:+ return False+ if await self._is_joined_on_server(room_id):+ self.mark_joined(room_id, self._connected_at)+ return True++ async def join_room(self, room_id: str) -> None:+ if await self._transport.join_room(room_id):+ self.mark_joined(room_id, int(time.time() * 1000))+ logger.info("Actor %s joined %s", self.transport_user_id, room_id)++ # ── Writing ────────────────────────────────────────────────────────────────++ async def send_message(+ self,+ room_id: str,+ body: str,+ *,+ metered: bool,+ format: Literal["text", "markdown"] = "text",+ mentions: list[str] | None = None,+ thread_root_id: str | None = None,+ extra_content: dict[str, object] | None = None,+ ) -> str | None:+ try:+ result = await self._transport.send_message(+ room_id,+ body,+ sender_name=self.display_name,+ metered=metered,+ format=format,+ mentions=mentions,+ thread_root_id=thread_root_id,+ extra_content=extra_content,+ )+ except TransportError as exc:+ logger.error("Failed to send message to %s: %s", room_id, exc)+ return None+ return result.event_id++ async def send_event(+ self, room_id: str, event_type: str, content: dict[str, object]+ ) -> str:+ """Send a custom event, e.g. one of the `com.switch.*` types.++ Raises rather than returning None: unlike a chat message, these events+ carry protocol state, and a caller that proceeds as though one was+ delivered when it was not corrupts whatever it was coordinating.+ """+ result = await self._transport.send_event(room_id, event_type, content)+ return result.event_id++ async def upload_media(self, data: bytes, content_type: str, filename: str) -> str:+ """Upload bytes to the media store and return the URI referencing them.++ Raises on failure — a media upload that silently returns None would+ produce a broken event referencing nothing.+ """+ result = await self._transport.upload_media(data, content_type, filename)+ return result.uri++ async def send_media(+ self,+ room_id: str,+ media_uri: str,+ filename: str,+ mimetype: str,+ size: int,+ *,+ metered: bool,+ msgtype: str,+ caption: str | None = None,+ thread_root_id: str | None = None,+ group: dict[str, object] | None = None,+ ) -> str | None:+ """Send an m.image / m.file event pointing at an uploaded media URI.++ When `caption` is provided it becomes the event `body` (with the real+ filename carried separately in `filename`, per the rich-media-caption+ convention); otherwise `body` is the filename. When `thread_root_id` is+ set the event is related into that thread (mirrors send_message).++ `group` marks this event as one part of a multi-attachment message —+ `{"id": ..., "index": i, "total": n}`. A media event carries+ exactly one file, so a message+ carrying several files is sent as n events sharing a group id, which+ receivers coalesce back into one logical message. Absent the field, an+ event is simply a group of one.+ """+ try:+ result = await self._transport.send_media(+ room_id,+ media_uri,+ filename,+ mimetype,+ size,+ sender_name=self.display_name,+ metered=metered,+ msgtype=msgtype,+ caption=caption,+ thread_root_id=thread_root_id,+ group=group,+ )+ except TransportError as exc:+ logger.error("Failed to send media to %s: %s", room_id, exc)+ return None+ return result.event_id++ async def set_typing(self, room_id: str, is_typing: bool) -> None:+ await self._transport.set_typing(room_id, is_typing)+++class HumanActor(Actor[ClientConfig]):+ """A person on another platform, as a member of Switch rooms.++ One per person per collaboration bridge (client type `user`). The bridge+ writes their messages through it; nothing reads for it, because what the+ room says reaches that person through the bridge's `WorkspaceConsumer`.+ """++ role: ClassVar[ActorRole] = "human"+++class AgentActor(Actor[ClientConfig]):+ """An agent, as a member of Switch rooms (client type `agent`).++ Carries the agent row it stands for: the bridge writes the agent's replies+ through it, found by agent id. The row is loaded by the agent's consumer+ when it starts, and refreshed there when it may have been edited.+ """++ role: ClassVar[ActorRole] = "agent"++ def __init__(self, **kwargs: Unpack[ActorKwargs[ClientConfig]]) -> None:+ super().__init__(**kwargs)+ self._agent: Agent | None = None++ @property+ def agent(self) -> Agent:+ if self._agent is None:+ raise RuntimeError("Agent not loaded — its consumer has not started")+ return self._agent++ @property+ def agent_id(self) -> str | None:+ return self._agent.id if self._agent is not None else None++ def set_agent(self, agent: Agent) -> None:+ self._agent = agent+++class SystemActor(Actor[ClientConfig]):+ """Switch itself, as a member of every room (client type `admin`).++ Writes command answers, notices and a template's kickoff. What it answers+ is read by its `CommandConsumer`.+ """++ role: ClassVar[ActorRole] = "system"++ # ── Platform messages ───────────────────────────────────────────────────++ async def send_platform_message(+ self,+ room_id: str,+ body: str,+ *,+ thread_root_id: str | None = None,+ on_behalf_of: OnBehalfOf | None = None,+ reply_in_channel: bool = False,+ ) -> str | None:+ """Send an addressed message as the Switch platform.++ Unlike an admin notice it carries no ADMIN_MARKER and IS addressed to+ agents. ``on_behalf_of`` names the person whose authority it carries:+ each addressed agent applies its policy to that person, so the+ platform can say what they could have said and nothing more. Without+ it the message is the platform's own, which agents deny unless a rule+ opts them in.+ """+ marker_value: dict[str, object] = {}+ if on_behalf_of is not None:+ marker_value["on_behalf_of"] = {+ "user_id": on_behalf_of.user_id,+ "name": on_behalf_of.name,+ **(+ {"agent_id": on_behalf_of.agent_id}+ if on_behalf_of.agent_id is not None+ else {}+ ),+ }+ if reply_in_channel:+ # Only meaningful for a threaded message: the agents it addresses+ # answer at the top level instead of under it.+ marker_value["reply_in_channel"] = True+ return await self.send_message(+ room_id,+ body,+ format="markdown",+ thread_root_id=thread_root_id,+ extra_content={PLATFORM_MARKER: marker_value},+ metered=False,+ )++ # ── Admin notices ─────────────────────────────────────────────────────────++ async def send_notice(self, room_id: str, body: str) -> None:+ """Post a system notice about the room's run: that it was paused,+ continued or stopped. Like every admin message it addresses nobody,+ so no agent wakes on it."""+ await self.send_admin(+ room_id,+ body,+ message_type=AdminMessageType.RUN_NOTICE,+ thread_root_id=None,+ )++ # ── Helpers ───────────────────────────────────────────────────────────────++ async def send_admin(+ self,+ room_id: str,+ body: str,+ *,+ message_type: AdminMessageType,+ thread_root_id: str | None,+ mentions: list[str] | None = None,+ ) -> None:+ await self.send_message(+ room_id,+ body,+ format="markdown",+ mentions=mentions,+ thread_root_id=thread_root_id,+ extra_content=admin_extra_content(message_type),+ metered=False,+ )diff --git a/core/switch_core/clients/admin_messages.py b/core/switch_core/clients/admin_messages.pyindex 32d1c2ea0..95a7ba49c 100644--- a/core/switch_core/clients/admin_messages.py+++ b/core/switch_core/clients/admin_messages.py@@ -5,7 +5,7 @@ from enum import StrEnumfrom typing import NamedTuple# Content flag stamped on the no-session / busy-elsewhere auto-reply (see-# AgentClient.on_message). Its first job is to mark a message as itself an+# AgentConsumer.on_message). Its first job is to mark a message as itself an# auto-reply so that another offline agent addressed by it does NOT emit a# second auto-reply — two session-less agents tagging each other would# otherwise ping-pong identical "no session" replies forever. It also lets the@@ -24,7 +24,8 @@ AUTO_REPLY_FLAG = "com.switch.auto_reply"# (including the admin client itself) never react to it with warnings or# auto-replies.# The marker rides as a field on a plain m.room.message whose body is the-# human-readable default text, so a vanilla Matrix client still renders it.+# human-readable default text, so a reader that ignores the marker still+# renders it.ADMIN_MARKER = "com.switch.admin"# Marker for a message the Switch platform posts. Unlike ADMIN_MARKER it ISdiff --git a/core/switch_core/clients/agent_client.py b/core/switch_core/clients/agent_consumer.pysimilarity index 95%rename from core/switch_core/clients/agent_client.pyrename to core/switch_core/clients/agent_consumer.pyindex 8e323aba1..bd44bf79a 100644--- a/core/switch_core/clients/agent_client.py+++ b/core/switch_core/clients/agent_consumer.py@@ -6,7 +6,7 @@ import randomimport refrom collections.abc import Mappingfrom dataclasses import dataclass, field-from typing import TYPE_CHECKING, Literal, NamedTuple, Unpack+from typing import TYPE_CHECKING, Literal, NamedTuplefrom switch_core.attachments import parse_attachment_groupfrom switch_core.bridges.agent.commands import (@@ -15,7 +15,7 @@ from switch_core.bridges.agent.commands import (_addressed_by_name_or_role,dispatch_command,)-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistryfrom switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.bridges.agent.protocol.presence import (agents_present_in,@@ -34,17 +34,14 @@ from switch_core.bridges.agent.protocol.types import (TaskUpdatePayload,)from switch_core.budgets import BudgetExceeded, BudgetGuard+from switch_core.clients.actor import AgentActorfrom switch_core.clients.admin_messages import (AUTO_REPLY_FLAG,PLATFORM_MARKER,platform_on_behalf_of,platform_replies_in_channel,)-from switch_core.clients.client_base import (- ClientBase,- ClientBaseKwargs,- ClientConfig,-)+from switch_core.clients.consumer import Consumerfrom switch_core.clients.mentions import (NAME_CHAR as _NAME_CHAR,)@@ -205,7 +202,7 @@ _ADDRESSING_UNCLAIMED_MESSAGE = ADDRESSING_UNCLAIMED_MESSAGEclass _GateOutcome(NamedTuple):"""Whether a message that tags this agent really addresses it, plus therefusal 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."""+ so the caller can close its database session before posting."""addressed: boolrefusal: str | None@@ -229,10 +226,18 @@ def _role_elsewhere_message(other_room_name: str) -> str:return _elsewhere_message([other_room_name], holds_role_here=True)-class AgentClient(ClientBase[ClientConfig]):+class AgentConsumer(Consumer[AgentActor]):+ """Reads the rooms an agent is in, and decides what reaches the agent.++ One per agent. Applies addressing, queues what should wake the agent in+ its event buffer for the SSE stream, and posts the replies an agent cannot+ give itself (greetings, offline and refusal notices) through its actor.+ """+def __init__(self,*,+ actor: AgentActor,event_buffer: EventBuffer,agent_store: AgentStore,room_store: RoomStore,@@ -242,11 +247,10 @@ class AgentClient(ClientBase[ClientConfig]):agent_session_store: AgentSessionStore,room_role_store: RoomRoleStore,external_user_store: ExternalUserStore,- connections: ConnectionRegistry,+ connections: AgentConnectionRegistry,frontend_base_url: str | None,- **kwargs: Unpack[ClientBaseKwargs[ClientConfig]],) -> None:- super().__init__(**kwargs)+ super().__init__(actor=actor)self._event_buffer = event_bufferself._agent_store = agent_storeself._room_store = room_store@@ -260,7 +264,6 @@ class AgentClient(ClientBase[ClientConfig]):self._frontend_base_url = (frontend_base_url.rstrip("/") if frontend_base_url else None)- self._agent: Agent | None = None# Addressing is decided from stores, not from this client, so the same# rules can decide for a message read out of the log.self._addressing = AddressingResolver(@@ -281,9 +284,7 @@ class AgentClient(ClientBase[ClientConfig]):@propertydef agent(self) -> Agent:- if self._agent is None:- raise RuntimeError("Agent not loaded — call start() first")- return self._agent+ return self.actor.agentasync def _fresh_agent(self, session: AsyncSession) -> Agent:"""Re-read the agent row and refresh the cached snapshot.@@ -300,7 +301,7 @@ class AgentClient(ClientBase[ClientConfig]):"""fresh = await self._agent_store.get(session, self.agent.id)if fresh is not None:- self._agent = fresh+ self.actor.set_agent(fresh)return self.agentasync def start(self) -> None:@@ -317,7 +318,7 @@ class AgentClient(ClientBase[ClientConfig]):agent = await self._agent_store.get_by_client_id(session, self.client_id)if agent is None:raise RuntimeError(f"No agent found for client: {self.client_id}")- self._agent = agent+ self.actor.set_agent(agent)await super().start()# ── Event hooks ───────────────────────────────────────────────────────────@@ -341,7 +342,7 @@ class AgentClient(ClientBase[ClientConfig]):greeting = f"Hi! I'm {name} — how can I help?"else:greeting = random.choice(AGENT_GREETINGS).format(name=name)- await self.send_message(+ await self.actor.send_message(room.room_id, greeting, format="markdown", metered=False)@@ -371,7 +372,9 @@ class AgentClient(ClientBase[ClientConfig]):another way when they speak — and the log, which records the Switchname, disagree with what was delivered live."""- client = await self.client_store.get_by_matrix_user_id(session, event.state_key)+ client = await self.client_store.get_by_transport_user_id(+ session, event.state_key+ )if client is not None:return client.display_namefallback = event.display_name or event.state_key.split(":")[0].lstrip("@")@@ -434,7 +437,7 @@ class AgentClient(ClientBase[ClientConfig]):reply_thread_root = thread_id if thread_id is not None else event.event_id# 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+ # nothing is posted to the room 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.@@ -488,7 +491,7 @@ class AgentClient(ClientBase[ClientConfig]):if not sender_name:sender_name = event.senderlogger.error(- "Message received without sender name, using matrix name: %s",+ "Message received without sender name, using the sender id: %s",sender_name,)@@ -549,15 +552,15 @@ class AgentClient(ClientBase[ClientConfig]):if not sender_name:sender_name = event.senderlogger.error(- "Media received without sender name, using matrix name: %s",+ "Media received without sender name, using the sender id: %s",sender_name,)# Mirror on_message: surface the thread this media belongs to (if any).thread_id = event.thread_root_id- # Several files posted as one message arrive as separate Matrix events- # sharing a group marker (Matrix has no multi-attachment event). Hold+ # Several files posted as one message arrive as separate media events+ # sharing a group marker (a media event carries one file). Hold# them until the group is complete, then emit ONE payload carrying all# of them, so the agent sees one message with N attachments.group = parse_attachment_group(content)@@ -854,7 +857,7 @@ class AgentClient(ClientBase[ClientConfig]):) -> None:"""Post a command result as this agent (an agent-owned command like`!run-cmd` answers in the agent's own voice, not as a system message)."""- await self.send_message(+ await self.actor.send_message(room_id,body,format=format,@@ -862,15 +865,19 @@ class AgentClient(ClientBase[ClientConfig]):metered=False,)- async def _resolve_room_meta(self, matrix_room_id: str) -> RoomMeta | None:- if matrix_room_id in self._room_meta:- return self._room_meta[matrix_room_id]+ async def _resolve_room_meta(self, transport_room_id: str) -> RoomMeta | None:+ if transport_room_id in self._room_meta:+ return self._room_meta[transport_room_id]async with tenant_session(self.session_factory, self.tenant_id) as session:- room = await self._room_store.get_by_matrix_room_id(session, matrix_room_id)+ room = await self._room_store.get_by_transport_room_id(+ session, transport_room_id+ )if room is None:- logger.error("Room not found for matrix room ID: %s", matrix_room_id)- self._room_meta[matrix_room_id] = None+ logger.error(+ "Room not found for transport room id: %s", transport_room_id+ )+ self._room_meta[transport_room_id] = Nonereturn Noneagent_greetings_enabled = True@@ -886,7 +893,7 @@ class AgentClient(ClientBase[ClientConfig]):agent_greetings_enabled=agent_greetings_enabled,channel_type=room.channel_type,)- self._room_meta[matrix_room_id] = meta+ self._room_meta[transport_room_id] = metareturn metaasync def _reply_when_unavailable_here(@@ -1119,8 +1126,8 @@ class AgentClient(ClientBase[ClientConfig]):)return self.agent.id in live- async def _is_direct_room(self, matrix_room_id: str) -> bool:- meta = await self._resolve_room_meta(matrix_room_id)+ async def _is_direct_room(self, transport_room_id: str) -> bool:+ meta = await self._resolve_room_meta(transport_room_id)return meta is not None and meta.channel_type == "direct"# ── Task event forwarding ────────────────────────────────────────────────@@ -1128,7 +1135,7 @@ class AgentClient(ClientBase[ClientConfig]):async def on_task_delegate(self, room: RoomRef, event: TaskDelegate) -> None:if event.performer_agent_id != self.agent.id:return- await self.send_message(+ await self.actor.send_message(room.room_id, "Working on it.", format="markdown", metered=False)meta = await self._resolve_room_meta(room.room_id)@@ -1267,7 +1274,7 @@ class AgentClient(ClientBase[ClientConfig]):"""return self._addressing.addressed_without_lookup(agent=self.agent,- agent_matrix_id=self.matrix_user_id,+ agent_user_id=self.transport_user_id,channel_type=meta.channel_type,message=self._as_incoming(event),)@@ -1286,7 +1293,7 @@ class AgentClient(ClientBase[ClientConfig]):return await self._addressing.addresses(session,agent=self.agent,- agent_matrix_id=self.matrix_user_id,+ agent_user_id=self.transport_user_id,room_id=meta.room_id,channel_type=meta.channel_type,message=self._as_incoming(event),@@ -1296,11 +1303,11 @@ class AgentClient(ClientBase[ClientConfig]):self,session: AsyncSession,agent: Agent,- matrix_sender: str,+ sender_user_id: str,room_id: str,content: Mapping[str, object] | None = None,) -> AddressingDecision:- """Whether `matrix_sender` may address this agent in `room_id`, per the+ """Whether `sender_user_id` may address this agent in `room_id`, per theagent's scoped addressing policy.`agent` is the freshly-read row rather than the cached snapshot: the@@ -1313,7 +1320,7 @@ class AgentClient(ClientBase[ClientConfig]):session,agent=agent,room_id=room_id,- sender=matrix_sender,+ sender=sender_user_id,content=content,)@@ -1356,7 +1363,7 @@ class AgentClient(ClientBase[ClientConfig]):async def _post_auto_reply(self,- matrix_room_id: str,+ transport_room_id: str,event: InboundMessage,msg: str,thread_root_id: str | None,@@ -1365,8 +1372,8 @@ class AgentClient(ClientBase[ClientConfig]):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,+ await self.actor.send_message(+ transport_room_id,msg if already_tagged else f"@{handle} {msg}",format="markdown",mentions=[event.sender],@@ -1405,8 +1412,9 @@ class AgentClient(ClientBase[ClientConfig]):Prefers the bridge-provided `sender_name` (the external username, whichthe collaboration bridge rewrites into a real @mention on Slack /- Mattermost); falls back to the mxid localpart for a native Matrix user- (paired with `mentions=[event.sender]` so Matrix renders a pill).+ Mattermost); falls back to the participant id's localpart for a client with no+ bridge-provided name (paired with `mentions=[event.sender]` so the+ mention renders as a pill)."""content = event.contentperson = platform_on_behalf_of(content)@@ -1420,7 +1428,7 @@ class AgentClient(ClientBase[ClientConfig]):def _is_mentioned(self, event: InboundMessage) -> bool:return self._addressing.mentions_name(agent=self.agent,- agent_matrix_id=self.matrix_user_id,+ agent_user_id=self.transport_user_id,message=self._as_incoming(event),)diff --git a/core/switch_core/clients/bridge_client.py b/core/switch_core/clients/bridge_client.pydeleted file mode 100644index 9a781fde0..000000000--- a/core/switch_core/clients/bridge_client.py+++ /dev/null@@ -1,49 +0,0 @@-from __future__ import annotations--import logging-from typing import TYPE_CHECKING, Unpack--from switch_core.clients.client_base import (- ClientBase,- ClientBaseKwargs,- ClientConfig,-)-from switch_core.transport import InboundMedia, InboundMessage, RoomRef--if TYPE_CHECKING:- from switch_core.bridges.collaboration.bridge_core import BridgeCore--logger = logging.getLogger(__name__)---class BridgeClientConfig(ClientConfig):- bridge_id: str---class BridgeClient(ClientBase[BridgeClientConfig]):- config_class = BridgeClientConfig-- def __init__(- self,- *,- bridge_core: BridgeCore,- **kwargs: Unpack[ClientBaseKwargs[BridgeClientConfig]],- ) -> None:- super().__init__(**kwargs)- self._bridge_core = bridge_core-- async def on_message(self, room: RoomRef, event: InboundMessage) -> None:- logger.debug(- "[BRIDGE-CLIENT] on_message room=%s sender=%s",- room.room_id,- event.sender,- )- await self._bridge_core.handle_outbound_message(room, event)-- async def on_media(self, room: RoomRef, event: InboundMedia) -> None:- logger.debug(- "[BRIDGE-CLIENT] on_media room=%s sender=%s",- room.room_id,- event.sender,- )- await self._bridge_core.handle_outbound_media(room, event, self)diff --git a/core/switch_core/clients/client_base.py b/core/switch_core/clients/client_base.pydeleted file mode 100644index b9cc288b6..000000000--- a/core/switch_core/clients/client_base.py+++ /dev/null@@ -1,577 +0,0 @@-from __future__ import annotations--import asyncio-import logging-import time-from typing import TYPE_CHECKING, Literal, TypedDict--from pydantic import BaseModel-from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker--from switch_core.db.stores.client_store import ClientStore-from switch_core.events import (- AgentRuntimeStateEvent,- CommandEvent,- LlmCallReport,- SwitchEvent,- TaskAccept,- TaskCancel,- TaskDelegate,- TaskFinalise,- TaskUpdate,- ToolCallReport,-)-from switch_core.transport import (- InboundCustomEvent,- InboundEvent,- InboundMedia,- InboundMembership,- InboundMessage,- MessageTransport,- RoomRef,- TransportError,- TransportHandlers,-)--if TYPE_CHECKING:- from collections.abc import Callable--logger = logging.getLogger(__name__)--SYNC_MAX_RETRIES = 5-SYNC_BACKOFF_BASE = 1.0-SYNC_BACKOFF_CAP = 60.0---class ClientConfig(BaseModel):- pass---class ClientBaseKwargs[ConfigT: ClientConfig](TypedDict):- """What every `ClientBase` subclass must forward to `ClientBase`.-- Subclasses take their own arguments and pass the rest through. Spelled as- `**kwargs: Any`, that pass-through is invisible to the type checker on both- sides: the subclass cannot be told it is missing something, and a caller- cannot be told it is passing something that no longer exists. A stale- `device_id=` type-checked clean that way and took all four collaboration- bridges down at startup — the credential had moved elsewhere and nothing- said so until the process refused to start.-- Declaring the shape here and unpacking it restores both checks without- making every subclass restate eleven parameters.- """-- client_id: str- tenant_id: str- matrix_user_id: str- display_name: str- session_factory: async_sessionmaker[AsyncSession]- client_store: ClientStore- config: ConfigT- transport_factory: Callable[[ClientBase[ConfigT]], MessageTransport]---class ClientBase[ConfigT: ClientConfig]:- config_class: type[ConfigT] = ClientConfig # type: ignore[assignment]-- def __init__(- self,- *,- client_id: str,- tenant_id: str,- matrix_user_id: str,- display_name: str,- session_factory: async_sessionmaker[AsyncSession],- client_store: ClientStore,- config: ConfigT,- transport_factory: Callable[[ClientBase[ConfigT]], MessageTransport],- ) -> None:- self.client_id = client_id- # The tenant of this client's own row, carried rather than looked up.- # A client's task binds nothing on purpose and its handlers bind some- # *room's* tenant, so neither context answers "which tenant is this- # client" — but every caller that builds a client is holding the row- # that says, so the answer travels with the client instead of being- # asked of the database again on the far side. Required, not- # defaulted: a client that does not know its tenant cannot write a- # scoped row, and there is no sensible value to fall back to.- self.tenant_id = tenant_id- self.matrix_user_id = matrix_user_id- self.display_name = display_name- self.session_factory = session_factory- self.client_store = client_store- self.config = config-- self._transport_factory = transport_factory- self.transport: MessageTransport | None = None- self.room_join_times: dict[str, int] = {}- self._room_joined_events: dict[str, asyncio.Event] = {}- # Rooms this client has already announced its arrival in. Distinct from- # `room_join_times`, which is membership bookkeeping recorded as early as- # possible (an explicit join, a membership lookup) so `wait_joined` and- # the `_should_ignore` cutoff are accurate. Membership being known is not- # evidence the arrival was announced.- self._self_join_dispatched: set[str] = set()- self._ready = asyncio.Event()- self._startup_ts: int = 0- self._running: bool = False-- async def wait_ready(self) -> None:- await self._ready.wait()-- async def set_display_name(self, display_name: str) -> None:- """Change the name this client shows under.-- The user id is an address and stays put; this is the label rooms- render. Used to correct a puppet filed under a platform id before the- platform would say who the person was.- """- await self._transport.set_display_name(display_name)- self.display_name = display_name-- def _joined_event(self, room_id: str) -> asyncio.Event:- event = self._room_joined_events.get(room_id)- if event is None:- event = asyncio.Event()- self._room_joined_events[room_id] = event- return event-- def _mark_joined(self, room_id: str, joined_at_ms: int) -> None:- self.room_join_times[room_id] = joined_at_ms- self._joined_event(room_id).set()-- async def _is_joined_on_server(self, room_id: str) -> bool:- return room_id in await self._transport.joined_rooms()-- async def wait_joined(self, room_id: str, timeout: float) -> bool:- """Block until this client is a member of `room_id`, up to `timeout`- seconds. Returns True if joined, False on timeout. Callers that need to- *send* into a room they have only just been invited to must await this- first: any event that lands before a member's join is filtered out by- `_should_ignore`.-- A join delivered to this client sets the event, but a join that- predates the process is never redelivered — delivery starts at each- room's head — and re-inviting an existing member is a no-op. Membership- is therefore read directly before waiting."""- event = self._joined_event(room_id)- if event.is_set():- return True- if await self._is_joined_on_server(room_id):- self._mark_joined(room_id, self._startup_ts)- return True- try:- await asyncio.wait_for(event.wait(), timeout)- except TimeoutError:- return False- return True-- @property- def _transport(self) -> MessageTransport:- if self.transport is None:- raise RuntimeError(- f"Client {self.matrix_user_id} is not connected — call start() first"- )- return self.transport-- # ── Lifecycle ──────────────────────────────────────────────────────────────-- async def start(self) -> None:- self._startup_ts = int(time.time() * 1000)- self._running = True-- await self._create_client()- self.setup()-- logger.info("Client %s starting sync loop", self.matrix_user_id)- retries = 0- while self._running:- try:- await self._transport.receive_forever()- retries = 0- except Exception:- if not self._running:- break- retries += 1- if retries > SYNC_MAX_RETRIES:- logger.error(- "Client %s exceeded %d sync retries, giving up",- self.matrix_user_id,- SYNC_MAX_RETRIES,- )- raise- delay = min(SYNC_BACKOFF_BASE * (2 ** (retries - 1)), SYNC_BACKOFF_CAP)- logger.exception(- "Sync loop error for %s (attempt %d/%d), retrying in %.1fs",- self.matrix_user_id,- retries,- SYNC_MAX_RETRIES,- delay,- )- await asyncio.sleep(delay)-- async def stop(self) -> None:- logger.info("Stopping client %s", self.matrix_user_id)- self._running = False- await self.teardown()- if self.transport is not None:- await self.transport.close()-- def setup(self) -> None:- self._transport.register_handlers(- TransportHandlers(- on_message=self._handle_message,- on_media=self._handle_media,- on_reaction=self._handle_reaction,- on_member_event=self._handle_member_event,- on_custom_event=self._handle_custom_event,- on_invite=self._handle_invite,- on_removed=self._handle_removed,- )- )-- async def teardown(self) -> None:- pass-- async def _create_client(self) -> None:- self.transport = self._transport_factory(self)- await self.transport.connect()- self._ready.set()-- # ── Internal event handlers (filtering + dispatch to hooks) ────────────────-- async def _handle_message(self, room: RoomRef, event: InboundMessage) -> None:- if self._should_ignore(room, event):- return- try:- await self.on_message(room, event)- except Exception:- logger.exception(- "Error in on_message for %s in %s", self.matrix_user_id, room.room_id- )-- async def _handle_media(self, room: RoomRef, event: InboundMedia) -> None:- if self._should_ignore(room, event):- return- try:- await self.on_media(room, event)- except Exception:- logger.exception(- "Error in on_media for %s in %s", self.matrix_user_id, room.room_id- )-- async def _handle_reaction(self, room: RoomRef, event: InboundEvent) -> None:- if self._should_ignore(room, event):- return- try:- await self.on_reaction(room, event)- except Exception:- logger.exception(- "Error in on_reaction for %s in %s", self.matrix_user_id, room.room_id- )-- async def _handle_member_event(- self, room: RoomRef, event: InboundMembership- ) -> None:- if event.state_key == self.matrix_user_id:- if event.membership == "join":- self._mark_joined(room.room_id, event.timestamp)- # A membership-preserving update (display name, avatar) re-fires- # m.room.member with membership == "join"; only a transition into- # membership is an arrival. Joins predating this process are not- # ours to announce, and the room is recorded so a redelivery of- # the same join does not announce it twice.- if (- event.prev_membership != "join"- and event.timestamp >= self._startup_ts- and room.room_id not in self._self_join_dispatched- ):- self._self_join_dispatched.add(room.room_id)- try:- await self.on_self_join(room, event)- except Exception:- logger.exception(- "Error in on_self_join for %s in %s",- self.matrix_user_id,- room.room_id,- )- return- if event.membership in ("leave", "ban"):- # Departing ends the visit: being added back is a fresh arrival.- self._self_join_dispatched.discard(room.room_id)- if self._should_ignore(room, event):- return- try:- await self.on_member_event(room, event)- except Exception:- logger.exception(- "Error in on_member_event for %s in %s",- self.matrix_user_id,- room.room_id,- )-- async def _handle_invite(self, room: RoomRef, event: InboundMembership) -> None:- try:- await self.on_invite(room, event)- except Exception:- logger.exception(- "Error in on_invite for %s in %s", self.matrix_user_id, room.room_id- )-- async def _handle_removed(self, room: RoomRef, event: InboundMembership) -> None:- # Departing ends the visit, the same way a leave delivered as a member- # event does: being added back is a fresh arrival.- self._self_join_dispatched.discard(room.room_id)- try:- await self.on_removed(room, event)- except Exception:- logger.exception(- "Error in on_removed for %s in %s", self.matrix_user_id, room.room_id- )-- _EVENT_DISPATCH: dict[str, tuple[type[SwitchEvent], str]] = {- "com.switch.command": (CommandEvent, "on_command"),- "com.switch.report.tool_call": (ToolCallReport, "on_tool_call_report"),- "com.switch.report.llm_call": (LlmCallReport, "on_llm_call_report"),- "com.switch.task.delegate": (TaskDelegate, "on_task_delegate"),- "com.switch.task.accept": (TaskAccept, "on_task_accept"),- "com.switch.task.update": (TaskUpdate, "on_task_update"),- "com.switch.task.finalise": (TaskFinalise, "on_task_finalise"),- "com.switch.task.cancel": (TaskCancel, "on_task_cancel"),- "com.switch.agent.runtime_state": (- AgentRuntimeStateEvent,- "on_agent_runtime_state",- ),- }-- async def _handle_custom_event(- self, room: RoomRef, event: InboundCustomEvent- ) -> None:- if self._should_ignore(room, event):- return-- entry = self._EVENT_DISPATCH.get(event.event_type)- if entry is None:- if event.event_type.startswith("com.switch.observe."):- logger.warning(- "Observe event %s not yet supported in %s",- event.event_type,- room.room_id,- )- else:- logger.error(- "Unhandled custom event type %s in %s",- event.event_type,- room.room_id,- )- return-- event_class, method_name = entry- try:- typed_event = event_class(- **event.content,- )- except Exception:- logger.exception(- "Failed to parse %s event in %s", event.event_type, room.room_id- )- return-- # Command results reply into the command's thread. When the command was- # typed inside an existing thread the bridge relates it to that thread's- # root (m.thread); use that root so the result stays in that thread.- # Otherwise the command itself roots the thread — use its own event id.- # The command message keeps its own id as well, so two commands in one- # thread are distinct. Neither id is part of the event content, so- # inject them here.- if isinstance(typed_event, CommandEvent):- typed_event.message_id = event.event_id- typed_event.thread_id = event.thread_root_id or event.event_id-- try:- await getattr(self, method_name)(room, typed_event)- except Exception:- logger.exception(- "Error in handler for %s in %s", event.event_type, room.room_id- )-- # ── Filtering ──────────────────────────────────────────────────────────────-- def _should_ignore(self, room: RoomRef, event: InboundEvent) -> bool:- if event.sender == self.matrix_user_id:- return True-- if event.timestamp:- join_time = self.room_join_times.get(room.room_id, self._startup_ts)- if event.timestamp < join_time:- return True-- return False-- # ── Event hooks (subclasses override) ──────────────────────────────────────-- async def on_message(self, room: RoomRef, event: InboundMessage) -> None:- pass-- async def on_media(self, room: RoomRef, event: InboundMedia) -> None:- pass-- async def on_reaction(self, room: RoomRef, event: InboundEvent) -> None:- pass-- async def on_self_join(self, room: RoomRef, event: InboundMembership) -> None:- pass-- async def on_member_event(self, room: RoomRef, event: InboundMembership) -> None:- pass-- async def on_invite(self, room: RoomRef, event: InboundMembership) -> None:- logger.info(- "Client %s auto-accepting invite to %s", self.matrix_user_id, room.room_id- )- await self.join_room(room.room_id)-- async def on_removed(self, room: RoomRef, event: InboundMembership) -> None:- """This client has been taken out of a room while it was running.-- Nothing to do for a client that holds no events of its own — the- transport has already stopped reading the room. A client that hands- events to something with a memory overrides this and empties it.- """-- async def on_command(self, room: RoomRef, event: CommandEvent) -> None:- pass-- async def on_tool_call_report(self, room: RoomRef, event: ToolCallReport) -> None:- pass-- async def on_llm_call_report(self, room: RoomRef, event: LlmCallReport) -> None:- pass-- async def on_task_delegate(self, room: RoomRef, event: TaskDelegate) -> None:- pass-- async def on_task_accept(self, room: RoomRef, event: TaskAccept) -> None:- pass-- async def on_task_update(self, room: RoomRef, event: TaskUpdate) -> None:- pass-- async def on_task_finalise(self, room: RoomRef, event: TaskFinalise) -> None:- pass-- async def on_task_cancel(self, room: RoomRef, event: TaskCancel) -> None:- pass-- async def on_agent_runtime_state(- self, room: RoomRef, event: AgentRuntimeStateEvent- ) -> None:- pass-- # ── Message sending ────────────────────────────────────────────────────────-- async def send_message(- self,- room_id: str,- body: str,- *,- metered: bool,- format: Literal["text", "markdown"] = "text",- mentions: list[str] | None = None,- thread_root_id: str | None = None,- extra_content: dict[str, object] | None = None,- ) -> str | None:- try:- result = await self._transport.send_message(- room_id,- body,- sender_name=self.display_name,- metered=metered,- format=format,- mentions=mentions,- thread_root_id=thread_root_id,- extra_content=extra_content,- )- except TransportError as exc:- logger.error("Failed to send message to %s: %s", room_id, exc)- return None- return result.event_id-- async def send_event(- self, room_id: str, event_type: str, content: dict[str, object]- ) -> str:- """Send a custom event, e.g. one of the `com.switch.*` types.-- Raises rather than returning None: unlike a chat message, these events- carry protocol state, and a caller that proceeds as though one was- delivered when it was not corrupts whatever it was coordinating.- """- result = await self._transport.send_event(room_id, event_type, content)- return result.event_id-- async def upload_media(self, data: bytes, content_type: str, filename: str) -> str:- """Upload bytes to the media store and return the URI referencing them.-- Raises on failure — a media upload that silently returns None would- produce a broken event referencing nothing.- """- result = await self._transport.upload_media(data, content_type, filename)- return result.uri-- async def send_media(- self,- room_id: str,- mxc: str,- filename: str,- mimetype: str,- size: int,- *,- metered: bool,- msgtype: str,- caption: str | None = None,- thread_root_id: str | None = None,- group: dict[str, object] | None = None,- ) -> str | None:- """Send an m.image / m.file event pointing at an uploaded mxc URI.-- When `caption` is provided it becomes the event `body` (with the real- filename carried separately in `filename`, per the rich-media-caption- convention); otherwise `body` is the filename. When `thread_root_id` is- set the event is related into that thread (mirrors send_message).-- `group` marks this event as one part of a multi-attachment message —- `{"id": ..., "index": i, "total": n}`. Matrix has no native- multi-attachment event (MSC4274 / MSC2881 are unmerged), so a message- carrying several files is sent as n events sharing a group id, which- receivers coalesce back into one logical message. Absent the field, an- event is simply a group of one.- """- try:- result = await self._transport.send_media(- room_id,- mxc,- filename,- mimetype,- size,- sender_name=self.display_name,- metered=metered,- msgtype=msgtype,- caption=caption,- thread_root_id=thread_root_id,- group=group,- )- except TransportError as exc:- logger.error("Failed to send media to %s: %s", room_id, exc)- return None- return result.event_id-- async def set_typing(self, room_id: str, is_typing: bool) -> None:- await self._transport.set_typing(room_id, is_typing)-- # ── Room operations ────────────────────────────────────────────────────────-- async def join_room(self, room_id: str) -> None:- if await self._transport.join_room(room_id):- self._mark_joined(room_id, int(time.time() * 1000))- logger.info("Client %s joined %s", self.matrix_user_id, room_id)diff --git a/core/switch_core/clients/client_factory.py b/core/switch_core/clients/client_factory.pyindex a68fb64ee..5fd33da4a 100644--- a/core/switch_core/clients/client_factory.py+++ b/core/switch_core/clients/client_factory.py@@ -5,7 +5,8 @@ from typing import Anyfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.clients.client_base import ClientBase, ClientConfig+from switch_core.clients.actor import Actor, ClientConfig+from switch_core.clients.consumer import Consumerfrom switch_core.config import SwitchConfigfrom switch_core.db.models import Clientfrom switch_core.db.stores.client_store import ClientStore@@ -48,24 +49,39 @@ class ClientFactory:self._invites = invitesself._ephemeral = ephemeralself._registry: dict[- str, tuple[type[ClientBase[ClientConfig]], dict[str, object]]+ str,+ tuple[+ type[Actor[ClientConfig]],+ type[Consumer[Any]] | None,+ dict[str, object],+ ],] = {}def register(self,client_type: str,- cls: type[ClientBase[ClientConfig]],- **extra_kwargs: object,+ actor_cls: type[Actor[ClientConfig]],+ consumer_cls: type[Consumer[Any]] | None = None,+ **consumer_kwargs: object,) -> None:- self._registry[client_type] = (cls, extra_kwargs)+ """What a `clients` row of `client_type` becomes when it runs.- def create(self, record: Client) -> ClientBase[ClientConfig]:+ Every row is an actor. A type that reads rooms also names a consumer,+ built around that actor with `consumer_kwargs`; a type that only+ writes (a person on another platform, a bridge's own identity) names+ none, and runs no read loop.+ """+ self._registry[client_type] = (actor_cls, consumer_cls, consumer_kwargs)++ def create(+ self, record: Client+ ) -> tuple[Actor[ClientConfig], Consumer[Any] | None]:entry = self._registry.get(record.type)if entry is None:raise ValueError(f"Unknown client type: {record.type!r}")- cls, extra_kwargs = entry- config = cls.config_class.model_validate(record.config or {})- return cls(+ actor_cls, consumer_cls, consumer_kwargs = entry+ config = actor_cls.config_class.model_validate(record.config or {})+ actor = actor_cls(client_id=record.id,# Straight off the row this client *is*. `create_client` writes# that row inside a session with the tenant bound and the factory@@ -73,16 +89,18 @@ class ClientFactory:# flushed carries its tenant here as surely as one read back at# boot does.tenant_id=record.tenant_id,- matrix_user_id=record.matrix_user_id,+ transport_user_id=record.transport_user_id,display_name=record.display_name,session_factory=self._session_factory,client_store=self._client_store,config=config,transport_factory=self.transport_for,- **extra_kwargs,)+ if consumer_cls is None:+ return actor, None+ return actor, consumer_cls(actor=actor, **consumer_kwargs)- def transport_for(self, client: ClientBase[Any]) -> MessageTransport:+ def transport_for(self, client: Actor[Any]) -> MessageTransport:"""The transport every client in the process runs on.Public because not every client is built by `create`: a collaboration@@ -91,10 +109,11 @@ class ClientFactory:so that every client in the process is built the same way."""return PostgresTransport(- user_id=client.matrix_user_id,+ user_id=client.transport_user_id,client_id=client.client_id,tenant_id=client.tenant_id,display_name=client.display_name,+ actor_role=client.role,session_factory=self._session_factory,room_store=self._room_store,message_store=self._message_store,diff --git a/core/switch_core/clients/client_lifecycle_service.py b/core/switch_core/clients/client_lifecycle_service.pyindex 72ff96a76..8a6f6c74a 100644--- a/core/switch_core/clients/client_lifecycle_service.py+++ b/core/switch_core/clients/client_lifecycle_service.py@@ -3,12 +3,13 @@ from __future__ import annotationsimport asyncioimport loggingimport uuid+from typing import Anyfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.clients.agent_client import AgentClient-from switch_core.clients.client_base import ClientBase, ClientConfig+from switch_core.clients.actor import Actor, AgentActor, ClientConfigfrom switch_core.clients.client_factory import ClientFactory+from switch_core.clients.consumer import Consumerfrom switch_core.config import SwitchConfigfrom switch_core.db.models import Client, Tenantfrom switch_core.db.session_scope import tenant_session@@ -26,23 +27,26 @@ class ClientLifecycleService:def __init__(self,*,- matrix_admin: Provisioning,+ provisioning: Provisioning,client_store: ClientStore,tenant_store: TenantStore,client_factory: ClientFactory,session_factory: async_sessionmaker[AsyncSession],config: SwitchConfig,) -> None:- self._matrix_admin = matrix_admin+ self._provisioning = provisioningself._client_store = client_storeself._tenant_store = tenant_storeself._client_factory = client_factoryself._session_factory = session_factoryself._config = config- self._clients: dict[str, ClientBase[ClientConfig]] = {}+ # Every running row is an actor; the ones that read rooms also have a+ # consumer, keyed by the same client id.+ self._clients: dict[str, Actor[ClientConfig]] = {}+ self._consumers: dict[str, Consumer[Any]] = {}self._client_types: dict[str, str] = {}- # Which tenant each running client's row belongs to. The client- # carries the same value (`ClientBase.tenant_id`); this is the index+ # Which tenant each running client's row belongs to. The actor+ # carries the same value (`Actor.tenant_id`); this is the index# on it, keyed like `_clients` and `_client_types` so the three are# populated and emptied together and a caller picking clients *out* of# a registry that holds every tenant's at once can say which tenant it@@ -51,7 +55,7 @@ class ClientLifecycleService:self._tasks: dict[str, asyncio.Task[None]] = {}def _make_user_id(self, localpart: str) -> str:- return f"@{localpart}:{self._config.matrix_server_name}"+ return f"@{localpart}:{self._config.id_server_name}"COLLAB_CLIENT_TYPES = ("bridge", "user")@@ -179,11 +183,7 @@ class ClientLifecycleService:logger.info("Starting %d clients", len(records))for record in records:- client = self._client_factory.create(record)- self._clients[record.id] = client- self._client_types[record.id] = record.type- self._client_tenants[record.id] = record.tenant_id- self._start_task(record.id, client)+ self._register(record)async def create_client(self,@@ -196,11 +196,11 @@ class ClientLifecycleService:client_id = str(uuid.uuid4())if localpart is None:localpart = f"switch-{client_type}-{client_id[:8]}"- matrix_user_id = self._make_user_id(localpart)+ transport_user_id = self._make_user_id(localpart)record = Client(id=client_id,- matrix_user_id=matrix_user_id,+ transport_user_id=transport_user_id,display_name=display_name,type=client_type,config=config,@@ -209,19 +209,27 @@ class ClientLifecycleService:await self._client_store.create(session, record)await session.commit()- logger.info("Created client %s (%s)", display_name, matrix_user_id)+ logger.info("Created client %s (%s)", display_name, transport_user_id)return record- def start_client(self, record: Client) -> ClientBase[ClientConfig]:- client = self._client_factory.create(record)- self._clients[record.id] = client- self._client_types[record.id] = record.type- self._client_tenants[record.id] = record.tenant_id- self._start_task(record.id, client)+ def start_client(self, record: Client) -> Actor[ClientConfig]:+ actor = self._register(record)logger.info(- "Started client %s (%s)", record.display_name, record.matrix_user_id+ "Started client %s (%s)", record.display_name, record.transport_user_id)- return client+ return actor++ def _register(self, record: Client) -> Actor[ClientConfig]:+ actor, consumer = self._client_factory.create(record)+ self._clients[record.id] = actor+ if consumer is not None:+ self._consumers[record.id] = consumer+ else:+ self._consumers.pop(record.id, None)+ self._client_types[record.id] = record.type+ self._client_tenants[record.id] = record.tenant_id+ self._start_task(record.id, actor, consumer)+ return actorasync def create_and_start(self,@@ -230,7 +238,7 @@ class ClientLifecycleService:display_name: str,localpart: str | None = None,config: dict[str, object] | None = None,- ) -> ClientBase[ClientConfig]:+ ) -> Actor[ClientConfig]:record = await self.create_client(client_type=client_type,display_name=display_name,@@ -240,11 +248,15 @@ class ClientLifecycleService:return self.start_client(record)async def stop(self, client_id: str) -> None:- client = self._clients.get(client_id)- if client is None:+ actor = self._clients.get(client_id)+ if actor is None:logger.warning("Cannot stop unknown client %s", client_id)return- await client.stop()+ consumer = self._consumers.pop(client_id, None)+ if consumer is not None:+ await consumer.stop()+ else:+ await actor.close()task = self._cancel_task(client_id)if task is not None:await asyncio.gather(task, return_exceptions=True)@@ -255,8 +267,12 @@ class ClientLifecycleService:async def stop_all(self) -> None:logger.info("Stopping all %d clients", len(self._clients))- for client in self._clients.values():- await client.stop()+ for client_id, actor in self._clients.items():+ consumer = self._consumers.get(client_id)+ if consumer is not None:+ await consumer.stop()+ else:+ await actor.close()tasks = list(self._tasks.values())for task in tasks:task.cancel()@@ -266,6 +282,7 @@ class ClientLifecycleService:# garbage collector, in a context that is not the task's.await asyncio.gather(*tasks, return_exceptions=True)self._clients.clear()+ self._consumers.clear()self._client_types.clear()self._client_tenants.clear()self._tasks.clear()@@ -275,7 +292,7 @@ class ClientLifecycleService:The counterpart to `stop`, and separate from it on purpose. A clientrow is only ever deleted alongside whatever owned the client — a- bridge and the puppets it minted, an agent — and those rows have to go+ bridge and the human actors it minted, an agent — and those rows have to goin one transaction or not at all: the owner's delete commits firstotherwise, and a failure after it leaves clients nothing points at andnothing will retry.@@ -287,26 +304,26 @@ class ClientLifecycleService:"""await self._client_store.delete(session, client_id)- def get(self, client_id: str) -> ClientBase[ClientConfig] | None:+ def get(self, client_id: str) -> Actor[ClientConfig] | None:return self._clients.get(client_id)def running_count(self) -> int:- """Clients believed to be running right now.+ """Consumers believed to be running right now: the read loops.- A crashed client removes itself, so this falling is the only signal.+ A crashed consumer removes itself and its actor, so this falling is the+ only signal. Actors with no consumer have no loop to crash."""- return len(self._clients)+ return len(self._consumers)- def get_by_agent_id(self, agent_id: str) -> ClientBase[ClientConfig] | None:- for client in self._clients.values():- if isinstance(client, AgentClient) and client._agent is not None:- if client._agent.id == agent_id:- return client # type: ignore[return-value]+ def get_by_agent_id(self, agent_id: str) -> AgentActor | None:+ for actor in self._clients.values():+ if isinstance(actor, AgentActor) and actor.agent_id == agent_id:+ return actorreturn Nonedef get_by_type(self, client_type: str, tenant_id: str- ) -> list[ClientBase[ClientConfig]]:+ ) -> list[Actor[ClientConfig]]:"""This tenant's running clients of `client_type`.The tenant is required rather than optional, and that is the fix for a@@ -327,7 +344,12 @@ class ClientLifecycleService:and self._client_tenants.get(client_id) == tenant_id]- def _start_task(self, client_id: str, client: ClientBase[ClientConfig]) -> None:+ def _start_task(+ self,+ client_id: str,+ actor: Actor[ClientConfig],+ consumer: Consumer[Any] | None,+ ) -> None:# A client row is one running task. Anything that starts a second for# the same row — a boot sweep reaching a client that registration# already started, a bridge restarting its own — replaces the first,@@ -337,7 +359,7 @@ class ClientLifecycleService:# finally reaches it, it runs the teardown for both: the live client# for that user goes deaf to invitations it never saw arrive.self._cancel_task(client_id)- task = asyncio.create_task(self._run_client(client_id, client))+ task = asyncio.create_task(self._run_client(client_id, actor, consumer))self._tasks[client_id] = taskdef _cancel_task(self, client_id: str) -> asyncio.Task[None] | None:@@ -347,20 +369,23 @@ class ClientLifecycleService:return taskasync def _run_client(- self, client_id: str, client: ClientBase[ClientConfig]+ self,+ client_id: str,+ actor: Actor[ClientConfig],+ consumer: Consumer[Any] | None,) -> None:"""A client's long-lived task, deliberately ambient-free.`no_tenant` because a task keeps the context of whoever created it,and the creators differ: boot, a gateway request that added an agent,- or an inbound bridge message that minted a puppet mid-conversation.- A puppet in particular is reused for every room the person it stands+ or an inbound bridge message that minted a human actor mid-conversation.+ A human actor in particular is reused for every room the person it standsfor speaks in, so the first room's tenant is exactly the value thatmust not survive into the second. Everything the client does bindsthe tenant of the room it is acting on.Nothing in here runs unbound, and nothing has to ask the database- which tenant this client is in. A `ClientBase` carries its own+ which tenant this client is in. An `Actor` carries its own`tenant_id`, taken from the `clients` row it was built from, and handsit to its transport; `joined_rooms` and every media read then gothrough an ordinary `tenant_session` under that tenant. An exemption@@ -368,18 +393,24 @@ class ClientLifecycleService:already holding.The room goes with it for the same reason: the inbound handler that- mints a puppet has that room bound as log context, and the puppet's+ mints a human actor has that room bound as log context, and the human actor'sown log lines must not name it for the rest of its life. Each deliverybinds its room."""with no_tenant(), log_context(room_id=None):try:- await client.start()+ if consumer is not None:+ await consumer.start()+ else:+ await actor.connect()except Exception:logger.exception(- "Client %s (%s) crashed", client.display_name, client.matrix_user_id+ "Client %s (%s) crashed",+ actor.display_name,+ actor.transport_user_id,)self._clients.pop(client_id, None)+ self._consumers.pop(client_id, None)self._client_types.pop(client_id, None)self._client_tenants.pop(client_id, None)self._tasks.pop(client_id, None)diff --git a/core/switch_core/clients/admin_client.py b/core/switch_core/clients/command_consumer.pysimilarity index 67%rename from core/switch_core/clients/admin_client.pyrename to core/switch_core/clients/command_consumer.pyindex 767137bd1..bc3ec8d40 100644--- a/core/switch_core/clients/admin_client.py+++ b/core/switch_core/clients/command_consumer.py@@ -1,23 +1,18 @@from __future__ import annotationsimport logging-from typing import TYPE_CHECKING, Literal, Unpack+from typing import TYPE_CHECKING, Literalfrom switch_core.agent_display_name import agent_label_with_identifierfrom switch_core.bridges.agent.commands import dispatch_admin_command-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.clients.actor import SystemActorfrom switch_core.clients.admin_messages import (ADMIN_MARKER,- PLATFORM_MARKER,AdminMessageType,- OnBehalfOf,admin_extra_content,)-from switch_core.clients.client_base import (- ClientBase,- ClientBaseKwargs,- ClientConfig,-)+from switch_core.clients.consumer import Consumerfrom switch_core.clients.mentions import (mention_regex,strip_emphasis,@@ -41,9 +36,8 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)-class AdminClient(ClientBase[ClientConfig]):- """The always-present system client that lives in every room and emits- first-class admin/system messages.+class CommandConsumer(Consumer[SystemActor]):+ """Reads every room for Switch itself, and answers through its SystemActor.Two jobs:1. Observe room messages and post heads-up notices when a message tags an@@ -52,25 +46,25 @@ class AdminClient(ClientBase[ClientConfig]):render their results as admin messages.Every admin message carries the admin marker so it renders natively per- bridge and never triggers another client (loop-safe). The admin client is- not an agent — it holds no Agent row — so it reasons purely from the stores.+ bridge and never triggers another member (loop-safe). The system is not an+ agent — it holds no Agent row — so it reasons purely from the stores."""def __init__(self,*,+ actor: SystemActor,agent_store: AgentStore,room_store: RoomStore,room_role_store: RoomRoleStore,- connections: ConnectionRegistry,+ connections: AgentConnectionRegistry,document_store: DocumentStore,reference_store: ReferenceStore,agent_session_store: AgentSessionStore,room_service: RoomService,frontend_base_url: str | None,- **kwargs: Unpack[ClientBaseKwargs[ClientConfig]],) -> None:- super().__init__(**kwargs)+ super().__init__(actor=actor)self._agent_store = agent_storeself._room_store = room_storeself._room_role_store = room_role_store@@ -82,7 +76,7 @@ class AdminClient(ClientBase[ClientConfig]):self._frontend_base_url = (frontend_base_url.rstrip("/") if frontend_base_url else None)- # matrix_room_id -> RoomMeta (None when no Switch room maps).+ # transport_room_id -> RoomMeta (None when no Switch room maps).self._room_meta_cache: dict[str, RoomMeta | None] = {}# ── Event hooks ───────────────────────────────────────────────────────────@@ -120,7 +114,7 @@ class AdminClient(ClientBase[ClientConfig]):) -> None:"""Post a command result as an admin/system message (renders nativelyper bridge via the admin rail)."""- await self.send_message(+ await self.actor.send_message(room_id,body,format=format,@@ -129,63 +123,6 @@ class AdminClient(ClientBase[ClientConfig]):metered=False,)- # ── Platform messages ───────────────────────────────────────────────────-- async def send_platform_message(- self,- room_id: str,- body: str,- *,- thread_root_id: str | None = None,- on_behalf_of: OnBehalfOf | None = None,- reply_in_channel: bool = False,- ) -> str | None:- """Send an addressed message as the Switch platform.-- Unlike an admin notice it carries no ADMIN_MARKER and IS addressed to- agents. ``on_behalf_of`` names the person whose authority it carries:- each addressed agent applies its policy to that person, so the- platform can say what they could have said and nothing more. Without- it the message is the platform's own, which agents deny unless a rule- opts them in.- """- marker_value: dict[str, object] = {}- if on_behalf_of is not None:- marker_value["on_behalf_of"] = {- "user_id": on_behalf_of.user_id,- "name": on_behalf_of.name,- **(- {"agent_id": on_behalf_of.agent_id}- if on_behalf_of.agent_id is not None- else {}- ),- }- if reply_in_channel:- # Only meaningful for a threaded message: the agents it addresses- # answer at the top level instead of under it.- marker_value["reply_in_channel"] = True- return await self.send_message(- room_id,- body,- format="markdown",- thread_root_id=thread_root_id,- extra_content={PLATFORM_MARKER: marker_value},- metered=False,- )-- # ── Admin notices ─────────────────────────────────────────────────────────-- async def send_notice(self, room_id: str, body: str) -> None:- """Post a system notice about the room's run: that it was paused,- continued or stopped. Like every admin message it addresses nobody,- so no agent wakes on it."""- await self._send_admin(- room_id,- body,- message_type=AdminMessageType.RUN_NOTICE,- thread_root_id=None,- )-async def _warn_unreachable_roles(self,room: RoomRef,@@ -220,7 +157,7 @@ class AdminClient(ClientBase[ClientConfig]):f"your message may go unanswered. Run `!roles` to see "f"availability, or have an agent assume it.")- await self._send_admin(+ await self.actor.send_admin(room.room_id,notice,message_type=AdminMessageType.UNREACHABLE_ROLE,@@ -277,7 +214,7 @@ class AdminClient(ClientBase[ClientConfig]):f"reach {pronoun}. Add the agent from the room's detail page in the "f"gateway, or have an agent with room-management tools invite it.")- await self._send_admin(+ await self.actor.send_admin(room.room_id,notice,message_type=AdminMessageType.ABSENT_AGENT,@@ -287,32 +224,14 @@ class AdminClient(ClientBase[ClientConfig]):# ── Helpers ────────────────────────────────────────────────────────────────- async def _send_admin(- self,- room_id: str,- body: str,- *,- message_type: AdminMessageType,- thread_root_id: str | None,- mentions: list[str] | None = None,- ) -> None:- await self.send_message(- room_id,- body,- format="markdown",- mentions=mentions,- thread_root_id=thread_root_id,- extra_content=admin_extra_content(message_type),- metered=False,- )-def _sender_handle(self, event: InboundMessage) -> str:"""The @-handle to tag the message sender with.Prefers the bridge-provided `sender_name` (the external username, whichthe collaboration bridge rewrites into a real @mention on Slack /- Mattermost); falls back to the mxid localpart for a native Matrix user- (paired with `mentions=[event.sender]` so Matrix renders a pill).+ Mattermost); falls back to the participant id's localpart for a client with no+ bridge-provided name (paired with `mentions=[event.sender]` so the+ mention renders as a pill)."""content = event.contentname = content.get("sender_name")@@ -320,14 +239,16 @@ class AdminClient(ClientBase[ClientConfig]):return str(name)return str(event.sender).split(":")[0].lstrip("@")- async def _resolve_room_meta(self, matrix_room_id: str) -> RoomMeta | None:- if matrix_room_id in self._room_meta_cache:- return self._room_meta_cache[matrix_room_id]+ async def _resolve_room_meta(self, transport_room_id: str) -> RoomMeta | None:+ if transport_room_id in self._room_meta_cache:+ return self._room_meta_cache[transport_room_id]async with tenant_session(self.session_factory, self.tenant_id) as session:- room = await self._room_store.get_by_matrix_room_id(session, matrix_room_id)+ room = await self._room_store.get_by_transport_room_id(+ session, transport_room_id+ )if room is None:- logger.error("Room not found for matrix room ID: %s", matrix_room_id)- self._room_meta_cache[matrix_room_id] = None+ logger.error("Room not found for transport room id: %s", transport_room_id)+ self._room_meta_cache[transport_room_id] = Nonereturn Nonemeta = RoomMeta(room_id=room.id,@@ -335,9 +256,9 @@ class AdminClient(ClientBase[ClientConfig]):bridge_id=room.bridge_id,channel_type=room.channel_type,)- self._room_meta_cache[matrix_room_id] = meta+ self._room_meta_cache[transport_room_id] = metareturn meta- async def _is_direct_room(self, matrix_room_id: str) -> bool:- meta = await self._resolve_room_meta(matrix_room_id)+ async def _is_direct_room(self, transport_room_id: str) -> bool:+ meta = await self._resolve_room_meta(transport_room_id)return meta is not None and meta.channel_type == "direct"diff --git a/core/switch_core/clients/consumer.py b/core/switch_core/clients/consumer.pynew file mode 100644index 000000000..b85d9a030--- /dev/null+++ b/core/switch_core/clients/consumer.py@@ -0,0 +1,393 @@+"""Who reads a room: the delivery loop and the hooks it calls.++A consumer is built around an `Actor`. It reads the rooms that actor belongs+to from its own cursor, filters what that actor should not see (its own+messages, anything from before it joined), and hands the rest to the hooks a+subclass overrides. When a hook needs to answer, it writes through the actor.+"""++from __future__ import annotations++import asyncio+import logging+import time+from typing import TYPE_CHECKING, Any++from switch_core.events import (+ AgentRuntimeStateEvent,+ CommandEvent,+ LlmCallReport,+ SwitchEvent,+ TaskAccept,+ TaskCancel,+ TaskDelegate,+ TaskFinalise,+ TaskUpdate,+ ToolCallReport,+)+from switch_core.transport import (+ InboundCustomEvent,+ InboundEvent,+ InboundMedia,+ InboundMembership,+ InboundMessage,+ MessageTransport,+ RoomRef,+ TransportHandlers,+)++if TYPE_CHECKING:+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++ from switch_core.clients.actor import Actor+ from switch_core.db.stores.client_store import ClientStore++logger = logging.getLogger(__name__)++SYNC_MAX_RETRIES = 5+SYNC_BACKOFF_BASE = 1.0+SYNC_BACKOFF_CAP = 60.0+++class Consumer[ActorT: Actor[Any]]:+ def __init__(self, *, actor: ActorT) -> None:+ self.actor = actor+ # Rooms this consumer has already announced its actor's arrival in.+ # Distinct from the actor's `room_join_times`, which is membership+ # bookkeeping recorded as early as possible (an explicit join, a+ # membership lookup) so `wait_joined` and the `_should_ignore` cutoff+ # are accurate. Membership being known is not evidence the arrival was+ # announced.+ self._self_join_dispatched: set[str] = set()+ self._startup_ts: int = 0+ self._running: bool = False++ # The identity a consumer reads for is its actor's. Read-only views, so+ # the hooks below can say whose room this is without reaching through.++ @property+ def client_id(self) -> str:+ return self.actor.client_id++ @property+ def tenant_id(self) -> str:+ return self.actor.tenant_id++ @property+ def transport_user_id(self) -> str:+ return self.actor.transport_user_id++ @property+ def display_name(self) -> str:+ return self.actor.display_name++ @property+ def session_factory(self) -> async_sessionmaker[AsyncSession]:+ return self.actor.session_factory++ @property+ def client_store(self) -> ClientStore:+ return self.actor.client_store++ @property+ def transport(self) -> MessageTransport | None:+ return self.actor.transport++ @property+ def _transport(self) -> MessageTransport:+ return self.actor._transport++ async def wait_ready(self) -> None:+ await self.actor.wait_ready()++ # ── Lifecycle ──────────────────────────────────────────────────────────────++ async def start(self) -> None:+ self._startup_ts = int(time.time() * 1000)+ self._running = True++ await self.actor.connect()+ self.setup()++ logger.info("Consumer %s starting delivery loop", self.transport_user_id)+ retries = 0+ while self._running:+ try:+ await self._transport.receive_forever()+ retries = 0+ except Exception:+ if not self._running:+ break+ retries += 1+ if retries > SYNC_MAX_RETRIES:+ logger.error(+ "Consumer %s exceeded %d delivery retries, giving up",+ self.transport_user_id,+ SYNC_MAX_RETRIES,+ )+ raise+ delay = min(SYNC_BACKOFF_BASE * (2 ** (retries - 1)), SYNC_BACKOFF_CAP)+ logger.exception(+ "Delivery loop error for %s (attempt %d/%d), retrying in %.1fs",+ self.transport_user_id,+ retries,+ SYNC_MAX_RETRIES,+ delay,+ )+ await asyncio.sleep(delay)++ async def stop(self) -> None:+ logger.info("Stopping consumer %s", self.transport_user_id)+ self._running = False+ await self.teardown()+ await self.actor.close()++ def setup(self) -> None:+ self._transport.register_handlers(+ TransportHandlers(+ on_message=self._handle_message,+ on_media=self._handle_media,+ on_reaction=self._handle_reaction,+ on_member_event=self._handle_member_event,+ on_custom_event=self._handle_custom_event,+ on_invite=self._handle_invite,+ on_removed=self._handle_removed,+ )+ )++ async def teardown(self) -> None:+ pass++ # ── Internal event handlers (filtering + dispatch to hooks) ────────────────++ async def _handle_message(self, room: RoomRef, event: InboundMessage) -> None:+ if self._should_ignore(room, event):+ return+ try:+ await self.on_message(room, event)+ except Exception:+ logger.exception(+ "Error in on_message for %s in %s", self.transport_user_id, room.room_id+ )++ async def _handle_media(self, room: RoomRef, event: InboundMedia) -> None:+ if self._should_ignore(room, event):+ return+ try:+ await self.on_media(room, event)+ except Exception:+ logger.exception(+ "Error in on_media for %s in %s", self.transport_user_id, room.room_id+ )++ async def _handle_reaction(self, room: RoomRef, event: InboundEvent) -> None:+ if self._should_ignore(room, event):+ return+ try:+ await self.on_reaction(room, event)+ except Exception:+ logger.exception(+ "Error in on_reaction for %s in %s",+ self.transport_user_id,+ room.room_id,+ )++ async def _handle_member_event(+ self, room: RoomRef, event: InboundMembership+ ) -> None:+ if event.state_key == self.transport_user_id:+ if event.membership == "join":+ self.actor.mark_joined(room.room_id, event.timestamp)+ # A membership-preserving update (display name, avatar) re-fires+ # m.room.member with membership == "join"; only a transition into+ # membership is an arrival. Joins predating this process are not+ # ours to announce, and the room is recorded so a redelivery of+ # the same join does not announce it twice.+ if (+ event.prev_membership != "join"+ and event.timestamp >= self._startup_ts+ and room.room_id not in self._self_join_dispatched+ ):+ self._self_join_dispatched.add(room.room_id)+ try:+ await self.on_self_join(room, event)+ except Exception:+ logger.exception(+ "Error in on_self_join for %s in %s",+ self.transport_user_id,+ room.room_id,+ )+ return+ if event.membership in ("leave", "ban"):+ # Departing ends the visit: being added back is a fresh arrival.+ self._self_join_dispatched.discard(room.room_id)+ if self._should_ignore(room, event):+ return+ try:+ await self.on_member_event(room, event)+ except Exception:+ logger.exception(+ "Error in on_member_event for %s in %s",+ self.transport_user_id,+ room.room_id,+ )++ async def _handle_invite(self, room: RoomRef, event: InboundMembership) -> None:+ try:+ await self.on_invite(room, event)+ except Exception:+ logger.exception(+ "Error in on_invite for %s in %s", self.transport_user_id, room.room_id+ )++ async def _handle_removed(self, room: RoomRef, event: InboundMembership) -> None:+ # Departing ends the visit, the same way a leave delivered as a member+ # event does: being added back is a fresh arrival.+ self._self_join_dispatched.discard(room.room_id)+ try:+ await self.on_removed(room, event)+ except Exception:+ logger.exception(+ "Error in on_removed for %s in %s", self.transport_user_id, room.room_id+ )++ _EVENT_DISPATCH: dict[str, tuple[type[SwitchEvent], str]] = {+ "com.switch.command": (CommandEvent, "on_command"),+ "com.switch.report.tool_call": (ToolCallReport, "on_tool_call_report"),+ "com.switch.report.llm_call": (LlmCallReport, "on_llm_call_report"),+ "com.switch.task.delegate": (TaskDelegate, "on_task_delegate"),+ "com.switch.task.accept": (TaskAccept, "on_task_accept"),+ "com.switch.task.update": (TaskUpdate, "on_task_update"),+ "com.switch.task.finalise": (TaskFinalise, "on_task_finalise"),+ "com.switch.task.cancel": (TaskCancel, "on_task_cancel"),+ "com.switch.agent.runtime_state": (+ AgentRuntimeStateEvent,+ "on_agent_runtime_state",+ ),+ }++ async def _handle_custom_event(+ self, room: RoomRef, event: InboundCustomEvent+ ) -> None:+ if self._should_ignore(room, event):+ return++ entry = self._EVENT_DISPATCH.get(event.event_type)+ if entry is None:+ if event.event_type.startswith("com.switch.observe."):+ logger.warning(+ "Observe event %s not yet supported in %s",+ event.event_type,+ room.room_id,+ )+ else:+ logger.error(+ "Unhandled custom event type %s in %s",+ event.event_type,+ room.room_id,+ )+ return++ event_class, method_name = entry+ try:+ typed_event = event_class(+ **event.content,+ )+ except Exception:+ logger.exception(+ "Failed to parse %s event in %s", event.event_type, room.room_id+ )+ return++ # Command results reply into the command's thread. When the command was+ # typed inside an existing thread the bridge relates it to that thread's+ # root; use that root so the result stays in that thread. Otherwise the+ # command itself roots the thread — use its own event id. The command+ # message keeps its own id as well, so two commands in one thread are+ # distinct. Neither id is part of the event content, so inject them here.+ if isinstance(typed_event, CommandEvent):+ typed_event.message_id = event.event_id+ typed_event.thread_id = event.thread_root_id or event.event_id++ try:+ await getattr(self, method_name)(room, typed_event)+ except Exception:+ logger.exception(+ "Error in handler for %s in %s", event.event_type, room.room_id+ )++ # ── Filtering ──────────────────────────────────────────────────────────────++ def _should_ignore(self, room: RoomRef, event: InboundEvent) -> bool:+ if event.sender == self.transport_user_id:+ return True++ if event.timestamp:+ join_time = self.actor.room_join_times.get(room.room_id, self._startup_ts)+ if event.timestamp < join_time:+ return True++ return False++ # ── Event hooks (subclasses override) ──────────────────────────────────────++ async def on_message(self, room: RoomRef, event: InboundMessage) -> None:+ pass++ async def on_media(self, room: RoomRef, event: InboundMedia) -> None:+ pass++ async def on_reaction(self, room: RoomRef, event: InboundEvent) -> None:+ pass++ async def on_self_join(self, room: RoomRef, event: InboundMembership) -> None:+ pass++ async def on_member_event(self, room: RoomRef, event: InboundMembership) -> None:+ pass++ async def on_invite(self, room: RoomRef, event: InboundMembership) -> None:+ logger.info(+ "Consumer %s auto-accepting invite to %s",+ self.transport_user_id,+ room.room_id,+ )+ await self.actor.join_room(room.room_id)++ async def on_removed(self, room: RoomRef, event: InboundMembership) -> None:+ """This consumer's actor has been taken out of a room while it was+ running.++ Nothing to do for a consumer that holds no events of its own — the+ transport has already stopped reading the room. A consumer that hands+ events to something with a memory overrides this and empties it.+ """++ async def on_command(self, room: RoomRef, event: CommandEvent) -> None:+ pass++ async def on_tool_call_report(self, room: RoomRef, event: ToolCallReport) -> None:+ pass++ async def on_llm_call_report(self, room: RoomRef, event: LlmCallReport) -> None:+ pass++ async def on_task_delegate(self, room: RoomRef, event: TaskDelegate) -> None:+ pass++ async def on_task_accept(self, room: RoomRef, event: TaskAccept) -> None:+ pass++ async def on_task_update(self, room: RoomRef, event: TaskUpdate) -> None:+ pass++ async def on_task_finalise(self, room: RoomRef, event: TaskFinalise) -> None:+ pass++ async def on_task_cancel(self, room: RoomRef, event: TaskCancel) -> None:+ pass++ async def on_agent_runtime_state(+ self, room: RoomRef, event: AgentRuntimeStateEvent+ ) -> None:+ passdiff --git a/core/switch_core/clients/workspace_consumer.py b/core/switch_core/clients/workspace_consumer.pynew file mode 100644index 000000000..394b19b10--- /dev/null+++ b/core/switch_core/clients/workspace_consumer.py@@ -0,0 +1,60 @@+from __future__ import annotations++import logging+from typing import TYPE_CHECKING++from switch_core.clients.actor import Actor, ClientConfig+from switch_core.clients.consumer import Consumer+from switch_core.logging_context import log_context+from switch_core.transport import InboundMedia, InboundMessage, RoomRef++if TYPE_CHECKING:+ from switch_core.bridges.collaboration.collaboration_core import CollaborationCore++logger = logging.getLogger(__name__)+++class WorkspaceConsumerConfig(ClientConfig):+ bridge_id: str+++class WorkspaceConsumer(Consumer[Actor[WorkspaceConsumerConfig]]):+ """Reads every room a collaboration bridge mirrors, for its workspace.++ One per bridge (client type `bridge`). Everything new in those rooms is+ handed to the bridge's `CollaborationCore`, which drops what came from the+ platform and posts the rest to it. Its actor is the bridge's own identity+ in the room; it writes nothing, because the people on the platform write+ through their own `HumanActor`s.+ """++ def __init__(+ self,+ *,+ actor: Actor[WorkspaceConsumerConfig],+ collaboration_core: CollaborationCore,+ ) -> None:+ super().__init__(actor=actor)+ self._collaboration_core = collaboration_core++ async def on_message(self, room: RoomRef, event: InboundMessage) -> None:+ logger.debug(+ "[WORKSPACE-CONSUMER] on_message room=%s sender=%s",+ room.room_id,+ event.sender,+ )+ with log_context(+ bridge="collaboration", platform=self._collaboration_core.bridge_type+ ):+ await self._collaboration_core.handle_outbound_message(room, event)++ async def on_media(self, room: RoomRef, event: InboundMedia) -> None:+ logger.debug(+ "[WORKSPACE-CONSUMER] on_media room=%s sender=%s",+ room.room_id,+ event.sender,+ )+ with log_context(+ bridge="collaboration", platform=self._collaboration_core.bridge_type+ ):+ await self._collaboration_core.handle_outbound_media(room, event, self)diff --git a/core/switch_core/config.py b/core/switch_core/config.pyindex 1c52fc49e..d976e4f6e 100644--- a/core/switch_core/config.py+++ b/core/switch_core/config.py@@ -1,3 +1,4 @@+import osimport reimport sslimport uuid@@ -5,7 +6,7 @@ from pathlib import Pathfrom typing import Literalfrom urllib.parse import urlsplit-from pydantic import model_validator+from pydantic import AliasChoices, Field, model_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDict# A Postgres time value: a bare count of milliseconds, or a count with a unit.@@ -19,7 +20,7 @@ _DB_ROLE_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,62}$")class SwitchConfig(BaseSettings):- model_config = SettingsConfigDict(env_prefix="")+ model_config = SettingsConfigDict(env_prefix="", populate_by_name=True)db_host: strdb_port: str@@ -67,10 +68,15 @@ class SwitchConfig(BaseSettings):# deployment with no tenant isolation in it.db_require_restricted_role: bool = True- # The server half of every client's `@localpart:server` id. Not a- # homeserver address — nothing is contacted at it — but the ids are stable+ # The server half of every member's `@localpart:server` id. Not a+ # server address — nothing is contacted at it — but the ids are stable# public handles, so the shape outlives the homeserver that chose it.- matrix_server_name: str+ # Read from ID_SERVER_NAME; MATRIX_SERVER_NAME, its name until the+ # lexicon refactor, is still accepted for one release so deployments+ # and the Console's managed servers keep starting (deprecated).+ id_server_name: str = Field(+ validation_alias=AliasChoices("id_server_name", "matrix_server_name")+ )agent_registration_token: str# JWT auth@@ -973,3 +979,18 @@ class SwitchConfig(BaseSettings):# additionally proves it was issued for the host we asked for.context.check_hostname = self.db_ssl_mode == "verify-full"return {"ssl": context}+++def deprecated_env_names() -> list[str]:+ """Settings read from a name kept only for compatibility, as warnings.++ Checked against the environment rather than the parsed config, which+ cannot tell which of a field's names supplied it.+ """+ warnings = []+ if "MATRIX_SERVER_NAME" in os.environ and "ID_SERVER_NAME" not in os.environ:+ warnings.append(+ "MATRIX_SERVER_NAME is deprecated and will stop being read in a later "+ "release; set ID_SERVER_NAME instead."+ )+ return warningsdiff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.pyindex a08245db9..02658f66c 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -398,7 +398,10 @@ class Client(TenantScoped, Base):)id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)- matrix_user_id: Mapped[str] = mapped_column(Text, nullable=False)+ # The column keeps its Matrix-era name; the attribute says what it is.+ transport_user_id: Mapped[str] = mapped_column(+ "matrix_user_id", Text, nullable=False+ )display_name: Mapped[str] = mapped_column(Text, nullable=False)type: Mapped[str] = mapped_column(Text, nullable=False)config: Mapped[dict | None] = mapped_column(JSONB, nullable=True)@@ -467,7 +470,7 @@ class Agent(TenantScoped, Base):icon_url: Mapped[str | None] = mapped_column(Text, nullable=True)# Human-readable name shown to people ("Switch Dev") next to the machine# identifier `name` carries ("switchdev"). NULL means none was chosen and- # the display layer falls back to `name`. Never the Matrix client display+ # the display layer falls back to `name`. Never the client display# name: that stays the identifier, because it is what bridges match on to# recognise an agent's own echo.display_name: Mapped[str | None] = mapped_column(Text, nullable=True)@@ -713,7 +716,10 @@ class Room(TenantScoped, Base):)id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)- matrix_room_id: Mapped[str] = mapped_column(Text, nullable=False)+ # The column keeps its Matrix-era name; the attribute says what it is.+ transport_room_id: Mapped[str] = mapped_column(+ "matrix_room_id", Text, nullable=False+ )name: Mapped[str] = mapped_column(Text, nullable=False)description: Mapped[str] = mapped_column(Text, nullable=False)bridge_id: Mapped[str | None] = mapped_column(Text, nullable=True)@@ -761,7 +767,7 @@ class Room(TenantScoped, Base):)# When set, the room is archived: hidden from the default active room lists# (gateway + agent MCP tools) but otherwise fully intact and retrievable —- # members, Matrix room, and bridge channel are untouched. NULL = active.+ # members, room, and bridge channel are untouched. NULL = active.# Archiving is metadata-only and reversible (unarchive clears this).archived_at: Mapped[str | None] = mapped_column(DateTime(timezone=True), nullable=True@@ -1901,7 +1907,7 @@ class Message(TenantScoped, Base):Every participant in a room is a Switch-owned client, so recording eachsend captures the whole room exactly once — including messages a human- originates on a bridged platform, which enter through that user's puppet.+ originates on a bridged platform, which enter through that user's human actor.`content` is the full event body as sent. The columns beside it aredenormalised out of it for querying; for a custom `com.switch.*` event@@ -2212,7 +2218,7 @@ class ApprovalRequest(TenantScoped, Base):)-class SessionActivityItem(TenantScoped, Base):+class AgentSessionActivityItem(TenantScoped, Base):"""One step of a turn as a platform draws it: the turn itself, a message,a tool call, or a notice.@@ -2389,7 +2395,7 @@ for _table, _triggers in (ApprovalRequest.__table__,(CREATE_APPROVAL_INSERT_TRIGGER, CREATE_APPROVAL_STATE_TRIGGER),),- (SessionActivityItem.__table__, (CREATE_ACTIVITY_TRIGGER,)),+ (AgentSessionActivityItem.__table__, (CREATE_ACTIVITY_TRIGGER,)),):for _ddl in (CREATE_SESSION_ACTIVITY_NOTIFY_FUNCTION, *_triggers):event.listen(_table, "after_create", DDL(_ddl).execute_if(dialect="postgresql"))diff --git a/core/switch_core/db/notify_ddl.py b/core/switch_core/db/notify_ddl.pyindex 268efba32..04403d15a 100644--- a/core/switch_core/db/notify_ddl.py+++ b/core/switch_core/db/notify_ddl.py@@ -1,8 +1,7 @@"""The database side of message delivery: a trigger that announces new rows.-Delivery used to be the message bus pushing an event at a long-lived sync-connection. It becomes the table announcing its own inserts, and a listener-reading the rows back.+Delivery is the table announcing its own inserts, and a listener reading the+rows back.**The notification is a hint, never the payload.** It carries a room, aposition and a row id, and a consumer reads the row itself. That is what makes@@ -13,8 +12,8 @@ make the queue authoritative, and Postgres's notification queue is neitherdurable nor replayable.**It is a trigger rather than a call in the writer** so that it cannot be-forgotten. Anything that inserts a row — the recorder today, a backfill-tomorrow, a human with psql — announces it, and the announcement commits with+forgotten. Anything that inserts a row (a send, a backfill, a human with+psql) announces it, and the announcement commits withthe row or not at all. `NOTIFY` is only delivered on commit, so a listenernever learns about a row it could not then read.@@ -23,7 +22,7 @@ save wakeups, but each one needs a `LISTEN` issued before the first row itshould catch, which is a race the consumer has to close by reading the tableanyway — so the correctness machinery is identical and the subscription churnis pure cost. See `switch_core/messages/notify.py` for the in-process fan-out-that replaces it.+that does the filtering.The migration that installs this on a real database carries its own verbatimcopy: a migration is frozen at the moment it was written and must not changediff --git a/core/switch_core/db/stores/client_store.py b/core/switch_core/db/stores/client_store.pyindex 2105e388e..0dc1044f3 100644--- a/core/switch_core/db/stores/client_store.py+++ b/core/switch_core/db/stores/client_store.py@@ -12,15 +12,15 @@ class ClientStore:async def get(self, session: AsyncSession, client_id: str) -> Client | None:return await session.get(Client, client_id)- async def get_by_matrix_user_id(- self, session: AsyncSession, matrix_user_id: str+ async def get_by_transport_user_id(+ self, session: AsyncSession, transport_user_id: str) -> Client | None:- """Resolve a client by its Matrix user id within the bound tenant.+ """Resolve a client by its participant id (`transport_user_id`) within the bound tenant.Scoped explicitly rather than left to row-level security:`matrix_user_id` is unique per tenant(`uq_clients_tenant_matrix_user_id`), not globally, so the moment a- second tenant has a client with the same puppet id, an unfiltered read+ second tenant has a client with the same human actor id, an unfiltered readhere matches both rows and raises `MultipleResultsFound` out ofmessage routing and provisioning, which resolve the sending clientfrom an inbound event this way.@@ -28,7 +28,7 @@ class ClientStore:result = await session.execute(select(Client).where(Client.tenant_id == require_tenant_id(),- Client.matrix_user_id == matrix_user_id,+ Client.transport_user_id == transport_user_id,))return result.scalar_one_or_none()diff --git a/core/switch_core/db/stores/message_store.py b/core/switch_core/db/stores/message_store.pyindex 31f45203e..42638fa45 100644--- a/core/switch_core/db/stores/message_store.py+++ b/core/switch_core/db/stores/message_store.py@@ -112,9 +112,8 @@ class MessageStore:ids collide in the hash serialise against each other needlessly andare otherwise unaffected.- The cost is per-room serialisation of a single INSERT on a path that- has already returned to the caller — the send completed before- recording began. Rooms do not contend with each other.+ The cost is per-room serialisation of a single INSERT. Rooms do not+ contend with each other."""await session.execute(text("SELECT pg_advisory_xact_lock(hashtext(:room_id))"),diff --git a/core/switch_core/db/stores/room_store.py b/core/switch_core/db/stores/room_store.pyindex 1e154f199..af0096ea6 100644--- a/core/switch_core/db/stores/room_store.py+++ b/core/switch_core/db/stores/room_store.py@@ -49,10 +49,10 @@ class RoomStore:return Nonereturn row[0], row[1] is not None- async def get_by_matrix_room_id(- self, session: AsyncSession, matrix_room_id: str+ async def get_by_transport_room_id(+ self, session: AsyncSession, transport_room_id: str) -> Room | None:- """Resolve a room by its Matrix room id within the bound tenant.+ """Resolve a room by its transport room id (`transport_room_id`) within the bound tenant.Scoped explicitly rather than left to row-level security:`matrix_room_id` is unique per tenant@@ -62,16 +62,16 @@ class RoomStore:every inbound-event path that resolves a room this way (provisioning,the Postgres transport, admin commands). Every caller that reachesthis by now already knows its tenant — `PostgresTransport` and the- two `ClientBase` subclasses carry it on the row they were built from,+ two `Actor` subclasses carry it on the row they were built from,and `PostgresProvisioning` is only ever called from `room_service`inside a `tenant_scope` bound to the room it is acting on — so thereis no bootstrap case left that needs an unfiltered fallback, the same- as `ClientStore.get_by_matrix_user_id`.+ as `ClientStore.get_by_transport_user_id`."""result = await session.execute(select(Room).where(Room.tenant_id == require_tenant_id(),- Room.matrix_room_id == matrix_room_id,+ Room.transport_room_id == transport_room_id,))return result.scalar_one_or_none()@@ -448,19 +448,22 @@ class RoomStore: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.+ """`{client_id: transport_user_id}` for the agents this room has as members.Resolved from the database rather than from the running clientregistry, so it answers correctly before the agent clients havefinished booting."""result = await session.execute(- select(Client.id, Client.matrix_user_id)+ select(Client.id, Client.transport_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()}+ return {+ client_id: transport_user_id+ for client_id, transport_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))diff --git a/core/switch_core/db/stores/session_activity_store.py b/core/switch_core/db/stores/session_activity_store.pyindex c271fbc25..e55f722d1 100644--- a/core/switch_core/db/stores/session_activity_store.py+++ b/core/switch_core/db/stores/session_activity_store.py@@ -12,7 +12,7 @@ from typing import TYPE_CHECKINGfrom sqlalchemy import delete, func, select, updatefrom sqlalchemy.dialects.postgresql import insert-from switch_core.db.models import Agent, ApprovalRequest, SessionActivityItem+from switch_core.db.models import Agent, AgentSessionActivityItem, ApprovalRequestif TYPE_CHECKING:from sqlalchemy.ext.asyncio import AsyncSession@@ -100,7 +100,7 @@ class ApprovalRequestStore:return list(result.scalars())-class SessionActivityStore:+class AgentSessionActivityStore:async def status_for_update(self,session: AsyncSession,@@ -111,18 +111,20 @@ class SessionActivityStore:) -> str | None:"""The row's stored status, locked until the transaction ends, or None."""status: str | None = await session.scalar(- select(SessionActivityItem.status)+ select(AgentSessionActivityItem.status).where(- SessionActivityItem.agent_id == agent_id,- SessionActivityItem.session_id == session_id,- SessionActivityItem.turn_id == turn_id,- SessionActivityItem.item_id == item_id,+ AgentSessionActivityItem.agent_id == agent_id,+ AgentSessionActivityItem.session_id == session_id,+ AgentSessionActivityItem.turn_id == turn_id,+ AgentSessionActivityItem.item_id == item_id,).with_for_update())return status- async def upsert(self, session: AsyncSession, item: SessionActivityItem) -> bool:+ async def upsert(+ self, session: AsyncSession, item: AgentSessionActivityItem+ ) -> bool:"""Record `item` unless a revision at least as new is stored.True when this call inserted the row or moved it forward. An equal or@@ -130,11 +132,11 @@ class SessionActivityStore:"""values = {column.key: getattr(item, column.key)- for column in SessionActivityItem.__table__.columns+ for column in AgentSessionActivityItem.__table__.columnsif column.key not in ("created_at", "updated_at")and not (column.key == "tenant_id" and item.tenant_id is None)}- statement = insert(SessionActivityItem).values(**values)+ statement = insert(AgentSessionActivityItem).values(**values)moved = {key: statement.excluded[key]for key in (@@ -153,50 +155,54 @@ class SessionActivityStore:result = await session.execute(statement.on_conflict_do_update(index_elements=[- SessionActivityItem.tenant_id,- SessionActivityItem.agent_id,- SessionActivityItem.session_id,- SessionActivityItem.turn_id,- SessionActivityItem.item_id,+ AgentSessionActivityItem.tenant_id,+ AgentSessionActivityItem.agent_id,+ AgentSessionActivityItem.session_id,+ AgentSessionActivityItem.turn_id,+ AgentSessionActivityItem.item_id,],set_={**moved, "updated_at": func.now()},- where=SessionActivityItem.revision < statement.excluded.revision,- ).returning(SessionActivityItem.item_id)+ where=AgentSessionActivityItem.revision < statement.excluded.revision,+ ).returning(AgentSessionActivityItem.item_id))return result.scalar_one_or_none() is not Noneasync def turn(self, session: AsyncSession, agent_id: str, session_id: str, turn_id: str- ) -> list[SessionActivityItem]:+ ) -> list[AgentSessionActivityItem]:"""Every step of one turn, in the order each was first reported."""result = await session.execute(- select(SessionActivityItem)+ select(AgentSessionActivityItem).where(- SessionActivityItem.agent_id == agent_id,- SessionActivityItem.session_id == session_id,- SessionActivityItem.turn_id == turn_id,+ AgentSessionActivityItem.agent_id == agent_id,+ AgentSessionActivityItem.session_id == session_id,+ AgentSessionActivityItem.turn_id == turn_id,+ )+ .order_by(+ AgentSessionActivityItem.created_at, AgentSessionActivityItem.item_id)- .order_by(SessionActivityItem.created_at, SessionActivityItem.item_id))return list(result.scalars())async def turns_of_session(self, session: AsyncSession, agent_id: str, session_id: str- ) -> list[SessionActivityItem]:+ ) -> list[AgentSessionActivityItem]:"""The turn rows of one session, oldest first."""result = await session.execute(- select(SessionActivityItem)+ select(AgentSessionActivityItem).where(- SessionActivityItem.agent_id == agent_id,- SessionActivityItem.session_id == session_id,- SessionActivityItem.item_id == TURN_ITEM_ID,+ AgentSessionActivityItem.agent_id == agent_id,+ AgentSessionActivityItem.session_id == session_id,+ AgentSessionActivityItem.item_id == TURN_ITEM_ID,)- .order_by(SessionActivityItem.created_at)+ .order_by(AgentSessionActivityItem.created_at))return list(result.scalars())async def prune_before(self, session: AsyncSession, cutoff: datetime) -> int:result = await session.execute(- delete(SessionActivityItem).where(SessionActivityItem.updated_at < cutoff)+ delete(AgentSessionActivityItem).where(+ AgentSessionActivityItem.updated_at < cutoff+ ))return int(result.rowcount or 0) # type: ignore[attr-defined]diff --git a/core/switch_core/db/tenant_lookup.py b/core/switch_core/db/tenant_lookup.pyindex 43241edd8..b7f60ad10 100644--- a/core/switch_core/db/tenant_lookup.py+++ b/core/switch_core/db/tenant_lookup.py@@ -91,7 +91,7 @@ was one more, `tenant_of_client`, and it was the one called most: everyclient's transport asked it, once per transport, and so did every agentclient's `start`. Both were built from a `clients` row that names the tenantin a column, so the question was asked of the database with the answer already-in hand. `ClientBase` and `PostgresTransport` now take a `tenant_id` the way+in hand. `Actor` and `PostgresTransport` now take a `tenant_id` the waythey take a `client_id`, and revision `b1d7c4f0a92e` drops the function. Thetest that keeps the list honest is the one that would have let this stand: afunction nobody needs is still a function every role could call, so the shorterdiff --git a/core/switch_core/delivery/addressing.py b/core/switch_core/delivery/addressing.pyindex 8ae2cb93e..f2bbe9c73 100644--- a/core/switch_core/delivery/addressing.py+++ b/core/switch_core/delivery/addressing.py@@ -13,7 +13,7 @@ ordinary room chatter when so. Nothing here sends anything; deciding is all itdoes, and the refusal wording travels back with the decision so the caller doesnot have to re-derive why.-This used to live on `AgentClient`, where every answer was reached through a+This used to live on the agent client (now `AgentConsumer`), where every answer was reached through alive Matrix client. It takes a message as data instead — a sender, a body, acontent dict — so the same rules decide for a message read out of the log asfor one that arrived on the bus. That equivalence is the point: two code paths@@ -80,7 +80,7 @@ ADDRESSING_UNCLAIMED_MESSAGE = (class IncomingMessage:"""What addressing needs to know about a message, and nothing else.- `formatted_body` is where a Matrix client puts a rendered mention pill,+ `formatted_body` is where a rendered mention pill goes,which is the one addressing signal that has no plain-text equivalent. It isabsent on media events and on anything read back from the log that neverhad one, so it is never the only thing consulted.@@ -145,7 +145,7 @@ class AddressingResolver:self,*,agent: Agent,- agent_matrix_id: str,+ agent_user_id: str,channel_type: str | None,message: IncomingMessage,) -> bool | None:@@ -161,7 +161,7 @@ class AddressingResolver:if channel_type == "direct":return Trueif self.mentions_name(- agent=agent, agent_matrix_id=agent_matrix_id, message=message+ agent=agent, agent_user_id=agent_user_id, message=message):return Trueif "@" not in message.body:@@ -173,7 +173,7 @@ class AddressingResolver:session: AsyncSession,*,agent: Agent,- agent_matrix_id: str,+ agent_user_id: str,room_id: str,channel_type: str | None,message: IncomingMessage,@@ -192,7 +192,7 @@ class AddressingResolver:"""decided = self.addressed_without_lookup(agent=agent,- agent_matrix_id=agent_matrix_id,+ agent_user_id=agent_user_id,channel_type=channel_type,message=message,)@@ -207,7 +207,7 @@ class AddressingResolver:)def mentions_name(- self, *, agent: Agent, agent_matrix_id: str, message: IncomingMessage+ self, *, agent: Agent, agent_user_id: str, message: IncomingMessage) -> bool:"""An `@name` at a token boundary, or a rendered mention pill.@@ -215,7 +215,7 @@ class AddressingResolver:scan is what catches everything else — media captions carry noformatted body, and neither does a bridged message."""- if message.formatted_body and agent_matrix_id in message.formatted_body:+ if message.formatted_body and agent_user_id in message.formatted_body:return Truereturn (mention_regex(agent.name).search(strip_emphasis(message.body)) is not None@@ -380,7 +380,7 @@ class AddressingResolver:async def resolve_sender(self,session: AsyncSession,- matrix_user_id: str,+ transport_user_id: str,content: Mapping[str, object] | None = None,) -> SenderPrincipal | None:"""Map a sender's mxid to the principal a policy is written about.@@ -401,7 +401,9 @@ class AddressingResolver:owner — and `owner_user_id` is who owns an agent sender, None for ahuman."""- client = await self._client_store.get_by_matrix_user_id(session, matrix_user_id)+ client = await self._client_store.get_by_transport_user_id(+ session, transport_user_id+ )if client is None:return Noneagent = await self._agent_store.get_by_client_id(session, client.id)diff --git a/core/switch_core/gateway/agent_sessions.py b/core/switch_core/gateway/agent_sessions.pyindex 0a01a8150..98f3f1035 100644--- a/core/switch_core/gateway/agent_sessions.py+++ b/core/switch_core/gateway/agent_sessions.py@@ -20,7 +20,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.db.models import ApprovalRequest, Userfrom switch_core.gateway.auth import get_current_userfrom switch_core.gateway.dependencies import get_session_factory-from switch_core.session_activity.service import SessionActivityService, SwitchUser+from switch_core.session_activity.service import AgentSessionActivityService, SwitchUserfrom switch_core.sessions.contract import (Answer,ApprovalResult,@@ -162,7 +162,7 @@ async def open_approvals(user: CurrentUser, factory: Factory) -> list[ApprovalRequestView]:"""Open requests of the agents the signed-in person owns."""- rows = await SessionActivityService(factory).open_for_owner(user.id)+ rows = await AgentSessionActivityService(factory).open_for_owner(user.id)return [ApprovalRequestView.of(row) for row in rows]@@ -178,7 +178,7 @@ async def answer_approval(user: CurrentUser,factory: Factory,) -> ApprovalRequestView:- row = await SessionActivityService(factory).answer_approval(+ row = await AgentSessionActivityService(factory).answer_approval(agent_id,session_id,request_id,diff --git a/core/switch_core/gateway/agents.py b/core/switch_core/gateway/agents.pyindex 3c22733f8..08256356d 100644--- a/core/switch_core/gateway/agents.py+++ b/core/switch_core/gateway/agents.py@@ -10,6 +10,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.agent_display_name import InvalidDisplayName, normalise_display_namefrom switch_core.agent_icon import InvalidIconUrl, normalise_icon_urlfrom switch_core.authz import Principal, require_manage+from switch_core.bridges.agent.protocol.agent_core import AgentCore, AgentExistsErrorfrom switch_core.bridges.agent.protocol.agent_detail import (AgentOptionsNotEditable,apply_agent_options,@@ -17,7 +18,6 @@ from switch_core.bridges.agent.protocol.agent_detail import (build_agent_summary,list_agent_summaries,)-from switch_core.bridges.agent.protocol.service import AgentExistsError, ProtocolServicefrom switch_core.bridges.agent.protocol.types import (IntegrationProfile,TaskProtocolConfig,@@ -72,7 +72,7 @@ async def delete_agent_by_name(agent_name: str,session: Annotated[AsyncSession, Depends(get_session)],agent_store: Annotated[AgentStore, Depends(get_agent_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> dict[str, bool]:@@ -103,7 +103,7 @@ async def delete_agent(agent_id: str,session: Annotated[AsyncSession, Depends(get_session)],agent_store: Annotated[AgentStore, Depends(get_agent_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> dict[str, bool]:@@ -146,7 +146,7 @@ async def list_known_agent_types() -> list[KnownAgentType]:async def register_known_agent(req: RegisterKnownAgentRequest,user: Annotated[User, Depends(get_current_user)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> RegisterAgentResponse:spec = KNOWN_AGENTS.get(req.agent_type)if spec is None:@@ -198,7 +198,7 @@ async def register_known_agent(async def register_known_subagents(req: RegisterKnownSubagentsRequest,user: Annotated[User, Depends(get_current_user)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],session: Annotated[AsyncSession, Depends(get_session)],agent_store: Annotated[AgentStore, Depends(get_agent_store)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],@@ -476,7 +476,7 @@ async def update_agent_display_name(async def register_other_agent(req: RegisterOtherAgentRequest,user: Annotated[User, Depends(get_current_user)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],) -> RegisterAgentResponse:# External agent registered without a known profile — give it a conservative# default profile (session_passive, no task capabilities).@@ -522,7 +522,7 @@ async def update_addressing_policy(agent_store: Annotated[AgentStore, Depends(get_agent_store)],room_store: Annotated[RoomStore, Depends(get_room_store)],user_store: Annotated[UserStore, Depends(get_user_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> AgentDetail:@@ -578,7 +578,7 @@ async def get_agent_detail(agent_store: Annotated[AgentStore, Depends(get_agent_store)],room_store: Annotated[RoomStore, Depends(get_room_store)],user_store: Annotated[UserStore, Depends(get_user_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],_user: Annotated[User, Depends(get_current_user)],) -> AgentDetail:agent = await agent_store.get(session, agent_id)diff --git a/core/switch_core/gateway/app.py b/core/switch_core/gateway/app.pyindex b33f31680..75ba6e889 100644--- a/core/switch_core/gateway/app.py+++ b/core/switch_core/gateway/app.py@@ -3,8 +3,8 @@ from __future__ import annotationsfrom fastapi import FastAPIfrom starlette.middleware.sessions import SessionMiddleware+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.event_buffer import EventBuffer-from switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.agent.server_connectors.lifecycle import (ServerSideConnectorLifecycleService,)@@ -80,7 +80,7 @@ def create_gateway_app(usage_store: UsageStore,budget_store: BudgetStore,resource_service: ResourceService,- protocol: ProtocolService,+ protocol: AgentCore,install_service: MessagingInstallService | None,invite_mailer: InviteMailer | None,config: SwitchConfig,diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.pyindex aedab0964..826261353 100644--- a/core/switch_core/gateway/collaborations.py+++ b/core/switch_core/gateway/collaborations.py@@ -539,8 +539,8 @@ async def _require_directory_account("""Raise unless the platform's directory really lists this account.This is an existence check, not an ownership one — anyone may claim any- real account, deliberately. What it prevents is provisioning a Matrix- puppet for an id that came from nowhere: the claim body is user-supplied,+ real account, deliberately. What it prevents is provisioning a+ human actor for an id that came from nowhere: the claim body is user-supplied,and the row it creates is permanent.Only reached for an account Switch has never seen. One it has recorded is@@ -626,7 +626,7 @@ async def claim_bridge_identity(# Nobody has seen this person speak yet, which is the normal case right# after connecting a workspace. Provision the identity now rather than# making them post something first — but only once the platform agrees- # the account exists. Provisioning mints a Matrix puppet, so taking the+ # the account exists. Provisioning mints a human actor, so taking the# request's word for it would let any signed-in user conjure accounts# for people who do not exist.await _require_directory_account(@@ -635,8 +635,8 @@ async def claim_bridge_identity(external_user_id=payload.external_user_id,username=payload.username,)- bridge_core = collab_lifecycle.get(bridge_id)- if bridge_core is None:+ collaboration_core = collab_lifecycle.get(bridge_id)+ if collaboration_core is None:raise HTTPException(status_code=409,detail=(@@ -645,7 +645,7 @@ async def claim_bridge_identity(),)try:- external_user = await bridge_core.ensure_external_user(+ external_user = await collaboration_core.ensure_external_user(external_user_id=payload.external_user_id,external_username=payload.username,)diff --git a/core/switch_core/gateway/dependencies.py b/core/switch_core/gateway/dependencies.pyindex 7e1f4bdef..ff6b06d16 100644--- a/core/switch_core/gateway/dependencies.py+++ b/core/switch_core/gateway/dependencies.py@@ -5,8 +5,8 @@ from typing import Anyfrom sqlalchemy.ext.asyncio import AsyncSession+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.event_buffer import EventBuffer-from switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.agent.server_connectors.lifecycle import (ServerSideConnectorLifecycleService,)@@ -63,7 +63,7 @@ def init_dependencies(usage_store: UsageStore,budget_store: BudgetStore,resource_service: ResourceService,- protocol: ProtocolService,+ protocol: AgentCore,install_service: MessagingInstallService | None,invite_mailer: InviteMailer | None,config: SwitchConfig,@@ -154,7 +154,7 @@ def get_session_factory() -> Any:def get_room_yaml_service() -> RoomYamlService:- protocol: ProtocolService = _state["protocol"]+ protocol: AgentCore = _state["protocol"]return protocol.room_yaml_service()@@ -234,7 +234,7 @@ def get_config() -> SwitchConfig:return _state["config"] # type: ignore[no-any-return]-def get_protocol() -> ProtocolService:+def get_protocol() -> AgentCore:return _state["protocol"] # type: ignore[no-any-return]diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.pyindex e09451c9b..c8b13f180 100644--- a/core/switch_core/gateway/rooms.py+++ b/core/switch_core/gateway/rooms.py@@ -8,7 +8,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Request, Responsefrom sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.authz import Action, Principal, can, require, require_manage-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.collaboration.models import (BridgeOperationError,ChannelType,@@ -115,7 +115,7 @@ async def _build_room_detail(room_store: RoomStore,bridge_store: CollaborationBridgeStore,external_user_store: ExternalUserStore,- protocol: ProtocolService,+ protocol: AgentCore,) -> RoomDetail:agent_ids = await room_store.get_agent_ids(session, room.id)client_ids = await room_store.get_client_ids(session, room.id)@@ -169,8 +169,8 @@ async def _build_room_detail(write_visibility=room.write_visibility,created_at=str(room.created_at),archived=room.archived_at is not None,- transport_room_id=room.matrix_room_id,- matrix_room_id=room.matrix_room_id,+ transport_room_id=room.transport_room_id,+ matrix_room_id=room.transport_room_id,external_channel_id=room.external_channel_id,instructions=room.instructions,protection_config=room.protection_config,@@ -186,7 +186,7 @@ async def _build_room_detail(async def _list_room_role_details(- session: AsyncSession, room_id: str, protocol: ProtocolService+ session: AsyncSession, room_id: str, protocol: AgentCore) -> list[RoomRoleDetail]:"""List a room's roles with their live holder agent names (empty if free).@@ -340,7 +340,7 @@ async def create_room(room_store: Annotated[RoomStore, Depends(get_room_store)],bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],) -> RoomDetail:_validate_create(req)@@ -497,7 +497,7 @@ async def get_room(room_store: Annotated[RoomStore, Depends(get_room_store)],bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:@@ -516,7 +516,7 @@ async def patch_room(room_store: Annotated[RoomStore, Depends(get_room_store)],bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:@@ -556,7 +556,7 @@ async def list_room_roles(room_id: str,session: Annotated[AsyncSession, Depends(get_session)],room_store: Annotated[RoomStore, Depends(get_room_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> list[RoomRoleDetail]:@@ -570,7 +570,7 @@ async def create_room_role(req: RoomRoleCreateRequest,session: Annotated[AsyncSession, Depends(get_session)],room_store: Annotated[RoomStore, Depends(get_room_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> list[RoomRoleDetail]:@@ -599,7 +599,7 @@ async def patch_room_role(req: RoomRoleUpdateRequest,session: Annotated[AsyncSession, Depends(get_session)],room_store: Annotated[RoomStore, Depends(get_room_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> list[RoomRoleDetail]:@@ -620,7 +620,7 @@ async def delete_room_role(name: str,session: Annotated[AsyncSession, Depends(get_session)],room_store: Annotated[RoomStore, Depends(get_room_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> list[RoomRoleDetail]:@@ -642,7 +642,7 @@ async def put_room_group(room_store: Annotated[RoomStore, Depends(get_room_store)],bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:@@ -673,7 +673,7 @@ async def put_protection(room_store: Annotated[RoomStore, Depends(get_room_store)],bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:@@ -700,7 +700,7 @@ async def put_observe(room_store: Annotated[RoomStore, Depends(get_room_store)],bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:@@ -727,7 +727,7 @@ async def post_room_agents(room_store: Annotated[RoomStore, Depends(get_room_store)],bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:@@ -760,7 +760,7 @@ async def patch_room_agent(room_store: Annotated[RoomStore, Depends(get_room_store)],bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:@@ -788,7 +788,7 @@ async def delete_room_agent(room_store: Annotated[RoomStore, Depends(get_room_store)],bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:@@ -815,7 +815,7 @@ async def post_room_users(room_store: Annotated[RoomStore, Depends(get_room_store)],bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:@@ -841,7 +841,7 @@ async def _set_archived(room_store: RoomStore,bridge_store: CollaborationBridgeStore,external_user_store: ExternalUserStore,- protocol: ProtocolService,+ protocol: AgentCore,user: User,is_admin: bool,) -> RoomDetail:@@ -866,12 +866,12 @@ async def archive_room(room_store: Annotated[RoomStore, Depends(get_room_store)],bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:""": hide it from the default active list. Reversible and- metadata-only — the Matrix room, members, and bridge channel are intact."""+ metadata-only: the room, members, and bridge channel are intact."""return await _set_archived(room_id,True,@@ -894,7 +894,7 @@ async def unarchive_room(room_store: Annotated[RoomStore, Depends(get_room_store)],bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:diff --git a/core/switch_core/gateway/subagent_registration.py b/core/switch_core/gateway/subagent_registration.pyindex de8229736..1fe3b89c1 100644--- a/core/switch_core/gateway/subagent_registration.py+++ b/core/switch_core/gateway/subagent_registration.py@@ -2,7 +2,7 @@The DB/auth/registration wiring lives in the gateway route; the name-derivation,in-batch dedup, and parent-option inheritance are factored out here so they can-be unit-tested without a database or a ProtocolService.+be unit-tested without a database or an AgentCore."""from __future__ import annotationsdiff --git a/core/switch_core/gateway/template_runs.py b/core/switch_core/gateway/template_runs.pyindex fcaa5b925..c46f4e19a 100644--- a/core/switch_core/gateway/template_runs.py+++ b/core/switch_core/gateway/template_runs.py@@ -16,8 +16,8 @@ from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.agent_runs import RunRefused, RunState, run_control-from switch_core.bridges.agent.protocol.service import ProtocolService-from switch_core.db.models import Room, SessionActivityItem, User+from switch_core.bridges.agent.protocol.agent_core import AgentCore+from switch_core.db.models import AgentSessionActivityItem, Room, Userfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.session_activity_store import TURN_ITEM_ID@@ -68,7 +68,7 @@ class TemplateRun(BaseModel):async def _run(session: AsyncSession,- protocol: ProtocolService,+ protocol: AgentCore,room_store: RoomStore,agent_store: AgentStore,root_id: str,@@ -126,7 +126,7 @@ async def _run(async def _working(- session: AsyncSession, protocol: ProtocolService, room_ids: list[str]+ session: AsyncSession, protocol: AgentCore, room_ids: list[str]) -> bool:"""Whether a turn is open in any of these rooms, for an agent that isstill connected: a turn whose session died never records its end."""@@ -134,12 +134,12 @@ async def _working(if not live or not room_ids:return Falseopen_turn = await session.execute(- select(SessionActivityItem.agent_id)+ select(AgentSessionActivityItem.agent_id).where(- SessionActivityItem.room_id.in_(room_ids),- SessionActivityItem.item_id == TURN_ITEM_ID,- SessionActivityItem.status.not_in(TURN_ENDED),- SessionActivityItem.agent_id.in_(live),+ AgentSessionActivityItem.room_id.in_(room_ids),+ AgentSessionActivityItem.item_id == TURN_ITEM_ID,+ AgentSessionActivityItem.status.not_in(TURN_ENDED),+ AgentSessionActivityItem.agent_id.in_(live),).limit(1))@@ -149,7 +149,7 @@ async def _working(@router.get("/template-runs")async def list_template_runs(session: Annotated[AsyncSession, Depends(get_session)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],room_store: Annotated[RoomStore, Depends(get_room_store)],agent_store: Annotated[AgentStore, Depends(get_agent_store)],user: Annotated[User, Depends(get_current_user)],@@ -180,7 +180,7 @@ async def _control(root_id: str,state: RunState,session: AsyncSession,- protocol: ProtocolService,+ protocol: AgentCore,room_store: RoomStore,agent_store: AgentStore,user: User,@@ -225,7 +225,7 @@ async def _control(async def stop_template_run(root_room_id: str,session: Annotated[AsyncSession, Depends(get_session)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],room_store: Annotated[RoomStore, Depends(get_room_store)],agent_store: Annotated[AgentStore, Depends(get_agent_store)],user: Annotated[User, Depends(get_current_user)],@@ -249,7 +249,7 @@ async def stop_template_run(async def continue_template_run(root_room_id: str,session: Annotated[AsyncSession, Depends(get_session)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],room_store: Annotated[RoomStore, Depends(get_room_store)],agent_store: Annotated[AgentStore, Depends(get_agent_store)],user: Annotated[User, Depends(get_current_user)],diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.pyindex 6f84fe4ce..6b7ef191f 100644--- a/core/switch_core/gateway/tenants.py+++ b/core/switch_core/gateway/tenants.py@@ -12,7 +12,7 @@ from sqlalchemy import selectfrom sqlalchemy.exc import DBAPIError, IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.config import SwitchConfigfrom switch_core.db.models import (@@ -1261,7 +1261,7 @@ async def remove_member(user_store: Annotated[UserStore, Depends(get_user_store)],agent_store: Annotated[AgentStore, Depends(get_agent_store)],api_key_store: Annotated[ApiKeyStore, Depends(get_api_key_store)],- protocol: Annotated[ProtocolService, Depends(get_protocol)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],_admin: Annotated[User, Depends(require_tenant_admin)],is_owner: Annotated[bool, Depends(get_tenant_is_owner)],) -> dict[str, bool]:diff --git a/core/switch_core/logging_context.py b/core/switch_core/logging_context.pyindex 7dc1b7436..5cd811bb2 100644--- a/core/switch_core/logging_context.py+++ b/core/switch_core/logging_context.py@@ -54,6 +54,11 @@ CONTEXT_FIELDS: tuple[str, ...] = ("user_id","console_id","console_name",+ # Which bridge a line belongs to ("collaboration" or "agent"), and for a+ # collaboration bridge its platform. Log prefixes like [BRIDGE-IN] stay;+ # these say which side, as fields a search can filter on.+ "bridge",+ "platform",)@@ -68,6 +73,8 @@ class LogContext:# people can share one sign-in, so `user_id` alone cannot tell them apart.console_id: str | None = Noneconsole_name: str | None = None+ bridge: str | None = None+ platform: str | None = None_EMPTY = LogContext()@@ -167,10 +174,9 @@ class LogContextFilter(logging.Filter):record.tenant_id = (context.tenant_id or current_tenant_id() or self._default_tenant_id)- record.request_id = context.request_id- record.agent_id = context.agent_id- record.room_id = context.room_id- record.user_id = context.user_id- record.console_id = context.console_id- record.console_name = context.console_name+ # Every other field by name, so a field added to CONTEXT_FIELDS+ # reaches the formatters without a second edit here.+ for name in CONTEXT_FIELDS:+ if name != "tenant_id":+ setattr(record, name, getattr(context, name))return Truediff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex 9ff1207d9..8e40c76c4 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -24,12 +24,12 @@ from sqlalchemy.ext.asyncio import (from sqlalchemy.pool import NullPoolfrom switch_core.bridges.agent.app import create_agent_bridge_app-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (HEARTBEAT_TTL_SECONDS,- ConnectionRegistry,+ AgentConnectionRegistry,)+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.event_buffer import EventBuffer-from switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.agent.registration_bootstrap import (BOOTSTRAP_KEY_LABEL,BOOTSTRAP_KEY_TYPE,@@ -80,12 +80,12 @@ from switch_core.bridges.collaboration.telegram.adapter import (TelegramConnectionConfig,)from switch_core.bridges.resource.service import ResourceService-from switch_core.clients.admin_client import AdminClient-from switch_core.clients.agent_client import AgentClient-from switch_core.clients.client_base import ClientBase+from switch_core.clients.actor import Actor, AgentActor, HumanActor, SystemActor+from switch_core.clients.agent_consumer import AgentConsumerfrom switch_core.clients.client_factory import ClientFactoryfrom switch_core.clients.client_lifecycle_service import ClientLifecycleService-from switch_core.config import SwitchConfig+from switch_core.clients.command_consumer import CommandConsumer+from switch_core.config import SwitchConfig, deprecated_env_namesfrom switch_core.crypto import encrypt_tokenfrom switch_core.db.boot_lock import boot_lockfrom switch_core.db.engine import (@@ -145,12 +145,12 @@ from switch_core.observability.runtime import EventLoopLagfrom switch_core.provisioning import Provisioningfrom switch_core.provisioning.postgres import PostgresProvisioningfrom switch_core.room_service import RoomService-from switch_core.session_activity.listener import SessionActivityListener+from switch_core.session_activity.listener import AgentSessionActivityListenerfrom switch_core.session_activity.maintenance import (maintenance_loop as session_activity_maintenance_loop,)from switch_core.session_activity.outcomes import ApprovalOutcomes-from switch_core.session_activity.service import SessionActivityService+from switch_core.session_activity.service import AgentSessionActivityServicefrom switch_core.telemetry.reporter import SnapshotReporterfrom switch_core.telemetry.service import TelemetryServicefrom switch_core.telemetry.setup import build_telemetry@@ -177,7 +177,7 @@ _CONNECTION_SWEEP_INTERVAL = 2.0_FORCED_EXIT_GRACE_SECONDS = 3.0-async def _runtime_state_sweep_loop(protocol: ProtocolService) -> None:+async def _runtime_state_sweep_loop(protocol: AgentCore) -> None:# `no_tenant` for the reason every other long-lived task does it: a task# keeps the context of whoever created it, and nothing in here may depend# on that. Boot binds nothing today, so this changes no behaviour — it@@ -191,7 +191,7 @@ async def _runtime_state_sweep_loop(protocol: ProtocolService) -> None:logger.exception("Runtime-state sweep failed")-async def _connection_sweep_loop(protocol: ProtocolService, lag: EventLoopLag) -> None:+async def _connection_sweep_loop(protocol: AgentCore, lag: EventLoopLag) -> None:"""Expire connections whose client has stopped beating.Skips a round after the event loop has been blocked. A stall stops us@@ -212,7 +212,7 @@ async def _connection_sweep_loop(protocol: ProtocolService, lag: EventLoopLag) -lag.record(overslept)if overslept > HEARTBEAT_TTL_SECONDS / 2:logger.warning(- "Connection sweep skipped: the event loop was blocked for %.1fs, "+ "AgentConnection sweep skipped: the event loop was blocked for %.1fs, ""so heartbeats could not be processed and every connection would ""look lapsed. Something is blocking the loop — that is the bug, ""not the connections.",@@ -222,14 +222,14 @@ async def _connection_sweep_loop(protocol: ProtocolService, lag: EventLoopLag) -try:for conn in protocol.connections.sweep():logger.info(- "Connection %s for agent %s expired (heartbeat lapsed, "+ "AgentConnection %s for agent %s expired (heartbeat lapsed, ""%d beats received)",conn.id,conn.agent_id,conn.beats,)except Exception:- logger.exception("Connection sweep failed")+ logger.exception("AgentConnection sweep failed")# The innermost of three nested budgets: under@@ -367,7 +367,7 @@ async def run(config: SwitchConfig) -> None:message_listener = MessageListener(lambda: create_unpooled_engine(config))# The same arrangement for session activity and approval requests: their# tables announce each change with the row attached, and this pushes it on.- session_activity_listener = SessionActivityListener(+ session_activity_listener = AgentSessionActivityListener(lambda: create_unpooled_engine(config))@@ -460,7 +460,7 @@ async def run(config: SwitchConfig) -> None:await resource_service.log_builtin_shadowing(session)# ── Provisioning ─────────────────────────────────────────────────────────- matrix_admin: Provisioning = PostgresProvisioning(+ provisioning: Provisioning = PostgresProvisioning(session_factory=session_factory,room_store=room_store,client_store=client_store,@@ -472,7 +472,7 @@ async def run(config: SwitchConfig) -> None:# the agent bridge because the room clients are wired first and read# presence from it — an agent is reachable if it has a live connection OR a# fresh heartbeat row (CHOO-1857 stage B).- connections = ConnectionRegistry()+ connections = AgentConnectionRegistry()# ── Client factory ───────────────────────────────────────────────────────client_factory = ClientFactory(@@ -489,7 +489,8 @@ async def run(config: SwitchConfig) -> None:)client_factory.register("agent",- AgentClient,+ AgentActor,+ AgentConsumer,event_buffer=event_buffer,agent_store=agent_store,room_store=room_store,@@ -502,12 +503,14 @@ async def run(config: SwitchConfig) -> None:connections=connections,frontend_base_url=config.frontend_base_url,)- client_factory.register("user", ClientBase)- client_factory.register("bridge", ClientBase)+ # Members that only write: a person on another platform, and a bridge's own+ # identity (its reader, the WorkspaceConsumer, is built by the bridge).+ client_factory.register("user", HumanActor)+ client_factory.register("bridge", Actor)# ── Client lifecycle ─────────────────────────────────────────────────────client_lifecycle = ClientLifecycleService(- matrix_admin=matrix_admin,+ provisioning=provisioning,client_store=client_store,tenant_store=tenant_store,client_factory=client_factory,@@ -525,19 +528,19 @@ async def run(config: SwitchConfig) -> None:client_store=client_store,client_lifecycle=client_lifecycle,room_service=None, # type: ignore[arg-type] # set after RoomService creation- matrix_admin=matrix_admin,+ provisioning=provisioning,session_factory=session_factory,config=config,client_factory=client_factory,session_activity_listener=session_activity_listener,- session_activity_service=SessionActivityService(session_factory),+ session_activity_service=AgentSessionActivityService(session_factory),connections=connections,telemetry=telemetry,)# ── Room service ─────────────────────────────────────────────────────────room_service = RoomService(- matrix_admin=matrix_admin,+ provisioning=provisioning,room_store=room_store,agent_store=agent_store,client_lifecycle=client_lifecycle,@@ -549,12 +552,13 @@ async def run(config: SwitchConfig) -> None:)collab_lifecycle._room_service = room_service- # Registered after RoomService is built: the admin client owns the+ # Registered after RoomService is built: the command consumer owns the# `!invite-agent` command, which reuses RoomService to add agents to the# room (and any bridged channel).client_factory.register("admin",- AdminClient,+ SystemActor,+ CommandConsumer,agent_store=agent_store,room_store=room_store,room_role_store=room_role_store,@@ -583,7 +587,7 @@ async def run(config: SwitchConfig) -> None:session_factory=session_factory,config=config,approval_outcomes=ApprovalOutcomes(- session_activity_listener, SessionActivityService(session_factory)+ session_activity_listener, AgentSessionActivityService(session_factory)),connections=connections,telemetry=telemetry,@@ -733,7 +737,7 @@ async def run(config: SwitchConfig) -> None:bridges_running=collab_lifecycle.running_count,bridges_running_by_platform=collab_lifecycle.running_by_platform,bridges_configured=collab_lifecycle.expected_count,- clients_running=client_lifecycle.running_count,+ consumers_running=client_lifecycle.running_count,connectors_running=connector_lifecycle.running_count,connectors_configured=connector_lifecycle.expected_count,agents_connected=lambda: len(connections.live_agent_ids()),@@ -879,7 +883,7 @@ async def run(config: SwitchConfig) -> None:client_lifecycle,collab_lifecycle,connector_lifecycle,- matrix_admin,+ provisioning,discord_gateway,discord_gateway_task,)@@ -1328,7 +1332,7 @@ async def _shutdown(client_lifecycle: ClientLifecycleService,collab_lifecycle: CollaborationBridgeLifecycleService,connector_lifecycle: ServerSideConnectorLifecycleService,- matrix_admin: Provisioning,+ provisioning: Provisioning,discord_gateway: DiscordGatewayClient | None,discord_gateway_task: asyncio.Task[None] | None,) -> None:@@ -1347,7 +1351,7 @@ async def _shutdown(if discord_gateway is not None:await discord_gateway.stop()await client_lifecycle.stop_all()- await matrix_admin.close()+ await provisioning.close()# `should_exit` starts uvicorn's shutdown, which runs the lifespan's# teardown; this sleep is all the time that teardown gets.@@ -1433,6 +1437,8 @@ def main() -> None:configure_logging(config, running_version)logger.info("Starting switch-core %s", running_version or "(version unknown)")+ for warning in deprecated_env_names():+ logger.warning(warning)asyncio.run(_migrate_and_grant(config))diff --git a/core/switch_core/observability/bootstrap.py b/core/switch_core/observability/bootstrap.pyindex ba314575a..dfd4966a2 100644--- a/core/switch_core/observability/bootstrap.py+++ b/core/switch_core/observability/bootstrap.py@@ -21,8 +21,8 @@ from switch_core.logging_context import LogContextFilterfrom switch_core.observability.catalogue import (AGENTS_CONNECTED,BRIDGES_RUNNING,- CLIENTS_RUNNING,CONNECTORS_RUNNING,+ CONSUMERS_RUNNING,DB_POOL_IN_USE,DB_POOL_OVERFLOW,DB_POOL_SIZE,@@ -80,7 +80,7 @@ class RuntimeProbes:bridges_running: Callable[[], int]bridges_running_by_platform: Callable[[], Mapping[str, int]]bridges_configured: Callable[[], int]- clients_running: Callable[[], int]+ consumers_running: Callable[[], int]connectors_running: Callable[[], int]connectors_configured: Callable[[], int]agents_connected: Callable[[], int]@@ -121,9 +121,13 @@ class Observability:def _state_readings(probes: RuntimeProbes) -> Callable[[], Iterator[GaugeReading]]:def readings() -> Iterator[GaugeReading]:yield GaugeReading(AGENTS_CONNECTED, float(probes.agents_connected()), {})- yield GaugeReading(CLIENTS_RUNNING, float(probes.clients_running()), {})+ yield GaugeReading(CONSUMERS_RUNNING, float(probes.consumers_running()), {})for platform, running in probes.bridges_running_by_platform().items():- yield GaugeReading(BRIDGES_RUNNING, float(running), {"platform": platform})+ yield GaugeReading(+ BRIDGES_RUNNING,+ float(running),+ {"bridge": "collaboration", "platform": platform},+ )yield GaugeReading(CONNECTORS_RUNNING, float(probes.connectors_running()), {})stats = probes.pool_stats()diff --git a/core/switch_core/observability/catalogue.py b/core/switch_core/observability/catalogue.pyindex e3470f493..16502642b 100644--- a/core/switch_core/observability/catalogue.py+++ b/core/switch_core/observability/catalogue.py@@ -148,47 +148,63 @@ MESSAGES_SENT = _spec("{message}","Messages accepted into the room, counted after the write commits. ""`kind:ephemeral` is the exception: presence-like state is delivered live "- "and never stored.",+ "and never stored. `actor` is who wrote it: human, agent, system or bridge.","kind",+ "actor",)MESSAGES_DELIVERED = _spec("switch.messages.delivered","sum","{message}",- "Messages handed to a client's handler.",+ "Messages handed to a client's handler. `actor` is who read it: agent, "+ "system or bridge. Never human, because a human actor reads nothing.","kind",+ "actor",)SEND_FAILURES = _spec("switch.messages.send_failures","sum","{failure}","Sends that raised before the row was committed. Without this a database "- "outage shows as an absence, which is what a quiet room looks like too.",+ "outage shows as an absence, which is what a quiet room looks like too. "+ "`actor` is who was writing.","kind",+ "actor",)DELIVERY_FAILURES = _spec("switch.messages.delivery_failures","sum","{failure}","Delivery-loop iterations that raised. The loop survives these by design, "- "which is what makes them invisible without a counter.",+ "which is what makes them invisible without a counter. `actor` is whose "+ "loop it was.",+ "actor",)DELIVERY_LAG = _spec("switch.messages.delivery_lag","histogram","ms","Age of a message when it reached a client's handler — whether the room is "- "keeping up, measured per delivery rather than inferred from a queue.",+ "keeping up, measured per delivery rather than inferred from a queue. "+ "`actor` is who read it.","kind",+ "actor",)-# ── Collaboration bridges ────────────────────────────────────────────────────-# `platform` is one of the registered adapter types, bounded by the code.+# ── Bridges ──────────────────────────────────────────────────────────────────+# Both bridges report the same metrics. `bridge` is "collaboration" or+# "agent". For a collaboration bridge `platform` is one of the registered+# adapter types, bounded by the code; the agent bridge reports "switch",+# because agents speak Switch's own protocol. On the agent side an event in is+# an operation an agent called (`event` is the operation's name, bounded by the+# registry), an event out is one delivered on its stream, and a call is an+# operation's run.BRIDGE_EVENTS_IN = _spec("switch.bridge.events_in","sum","{event}",- "Events accepted from a collaboration platform.",+ "Events accepted by a bridge: from a platform, or operations from an agent.",+ "bridge","platform","event",)@@ -196,8 +212,10 @@ BRIDGE_EVENTS_OUT = _spec("switch.bridge.events_out","sum","{event}",- "Relays attempted out to a collaboration platform — the denominator "+ "Relays attempted out through a bridge, to a platform or down an agent's "+ "stream — the denominator ""`switch.bridge.errors` is a fraction of.",+ "bridge","platform","kind",)@@ -206,6 +224,7 @@ BRIDGE_ERRORS = _spec("sum","{error}","Bridge operations that raised, by direction.",+ "bridge","platform","direction",)@@ -216,6 +235,7 @@ BRIDGES_RUNNING = _spec("Collaboration bridges with a live task, by platform. A configured bridge ""missing here has crashed — and without `platform` the total says how many ""died and never which, which is the first thing anyone asks.",+ "bridge","platform",)BRIDGE_CALL_DURATION = _spec(@@ -225,6 +245,7 @@ BRIDGE_CALL_DURATION = _spec("Round trip for one outbound call to a collaboration platform. The bridge ""counters say whether relays are failing; this says whether they are ""arriving late, which is what a room that feels unresponsive actually is.",+ "bridge","platform","kind",)@@ -258,11 +279,13 @@ AGENTS_CONNECTED = _spec("{agent}","Agents holding a live protocol connection.",)-CLIENTS_RUNNING = _spec(- "switch.clients.running",+CONSUMERS_RUNNING = _spec(+ "switch.consumers.running","gauge",- "{client}",- "Room clients with a live task.",+ "{consumer}",+ "Room consumers with a live read loop. Actors that only write (a person on "+ "another platform) run no loop and are not counted. A collaboration "+ "bridge's workspace consumer counts under switch.bridges.running.",)CONNECTORS_RUNNING = _spec("switch.connectors.running",@@ -344,7 +367,7 @@ CATALOGUE: dict[str, MetricSpec] = {AGENT_EVENTS_DROPPED,AGENT_CONNECTIONS_EXPIRED,AGENTS_CONNECTED,- CLIENTS_RUNNING,+ CONSUMERS_RUNNING,CONNECTORS_RUNNING,RUNTIME_MEMORY_RSS,RUNTIME_CPU_SECONDS,diff --git a/core/switch_core/provisioning/postgres.py b/core/switch_core/provisioning/postgres.pyindex c640ab8b1..51e235188 100644--- a/core/switch_core/provisioning/postgres.py+++ b/core/switch_core/provisioning/postgres.py@@ -99,7 +99,7 @@ class PostgresProvisioning:ClientRoom, {"client_id": client_id, "room_id": switch_room_id})- # By client id, not `user_id`: `clients.matrix_user_id` is unique per+ # By client id, not `user_id`: `clients.transport_user_id` is unique per# tenant, and every tenant's admin client carries the same one, so# waking "the client for @switch-admin" would wake whichever tenant's# transport last claimed the slot. `_resolve` above has already turned@@ -167,10 +167,12 @@ class PostgresProvisioning:async def _resolve(self, session: AsyncSession, transport_room_id: str, user_id: str) -> tuple[str, str, str]:- room = await self._room_store.get_by_matrix_room_id(session, transport_room_id)+ room = await self._room_store.get_by_transport_room_id(+ session, transport_room_id+ )if room is None:raise ProvisioningError(f"{transport_room_id} is not a Switch room")- client = await self._client_store.get_by_matrix_user_id(session, user_id)+ client = await self._client_store.get_by_transport_user_id(session, user_id)if client is None:raise ProvisioningError(f"{user_id} is not a Switch client")return room.id, client.id, client.display_namediff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.pyindex c87556f14..b7bdaf06e 100644--- a/core/switch_core/room_service.py+++ b/core/switch_core/room_service.py@@ -1,10 +1,10 @@"""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+Invite and kick calls write on their own database session, separate from the+caller's, and the two commit independently. That splits atomicity, and the+split has a deliberate direction: **transport membership must never exceedwhat the database records.** Write the membership row before inviting; revoke-the Matrix membership before dropping the row. A crash in the window then+the transport membership before dropping the row. A crash in the window thenleaves an agent Switch believes is a member but which cannot see the room —under-privileged, visible, and repairable — rather than one silently reading aroom Switch has no record of it being in.@@ -48,7 +48,7 @@ from switch_core.telemetry.snapshot import (from switch_core.tenant_context import tenant_scopeif TYPE_CHECKING:- from switch_core.bridges.collaboration.bridge_core import BridgeCore+ from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.lifecycle_service import (CollaborationBridgeLifecycleService,)@@ -159,7 +159,7 @@ class RoomService:def __init__(self,*,- matrix_admin: Provisioning,+ provisioning: Provisioning,room_store: RoomStore,agent_store: AgentStore,client_lifecycle: ClientLifecycleService,@@ -169,7 +169,7 @@ class RoomService:session_factory: async_sessionmaker[AsyncSession],telemetry: TelemetryService | None = None,) -> None:- self._matrix_admin = matrix_admin+ self._provisioning = provisioningself._room_store = room_storeself._agent_store = agent_storeself._client_lifecycle = client_lifecycle@@ -253,7 +253,7 @@ class RoomService:async def _validate_attachments(self, config: RoomCreateConfig) -> None:"""Resolve existence + access for refs/packages/linked-rooms before- touching Matrix. Race-time failures during attach are caught later+ provisioning anything. Race-time failures during attach are caught laterand surfaced via failed_attachments; this catches the common cases(bad ids, no access) cheaply."""@@ -414,7 +414,7 @@ class RoomService:@staticmethodasync def _add_users_to_channel(- bridge_core: BridgeCore,+ collaboration_core: CollaborationCore,external_channel_id: str,user_names: list[str],) -> list[dict[str, Any]]:@@ -427,7 +427,7 @@ class RoomService:a log line, leaving a room that silently lacked the people it was askedfor."""- resolved = await bridge_core.resolve_external_user_id_map(user_names)+ resolved = await collaboration_core.resolve_external_user_id_map(user_names)failures: list[dict[str, Any]] = [{"kind": "user",@@ -441,7 +441,7 @@ class RoomService:# rather than passing the caller's full name list beside a shorter list# of ids — an adapter that zips them would otherwise mis-attribute.names = list(resolved)- failed_ids = await bridge_core.adapter.add_users_to_channel(+ failed_ids = await collaboration_core.adapter.add_users_to_channel(external_channel_id, names, [resolved[name] for name in names])by_id = {resolved[name]: name for name in names}@@ -457,7 +457,7 @@ class RoomService:@staticmethodasync def _ensure_channel_capture(- bridge_core: BridgeCore,+ collaboration_core: CollaborationCore,external_channel_id: str,channel_type: ChannelType,) -> None:@@ -471,7 +471,7 @@ class RoomService:capture is a single bridge-wide stream, and idempotent for those whereit is not."""- await bridge_core.adapter.ensure_channel_subscriptions(+ await collaboration_core.adapter.ensure_channel_subscriptions([(external_channel_id, channel_type)])@@ -485,7 +485,7 @@ class RoomService:for alias in (config.aliases or {}).values():validate_alias_format(alias)# Validate the group up front so a bad id fails before we provision a- # Matrix room / external channel.+ # room / external channel.if config.group_id is not None:async with self._session_factory() as session:if await session.get(RoomGroup, config.group_id) is None:@@ -495,24 +495,30 @@ class RoomService:channel_type = config.channel_typeexternal_channel_id = config.external_channel_idbridge_id = await self._resolve_bridge_id(config)- bridge_core = None+ collaboration_core = Noneif bridge_id:await self._require_tenant_bridge(bridge_id)- bridge_core = self._collab_lifecycle.get(bridge_id)- if bridge_core is None:+ collaboration_core = self._collab_lifecycle.get(bridge_id)+ if collaboration_core is None:raise ValueError(f"Bridge not running: {bridge_id}")# A channel the platform delivered to this bridge is its own by# construction; one named by the caller has to be shown to be.if (- bridge_core+ collaboration_coreand external_channel_id is not Noneand config.created_by_kind != "system"):- await bridge_core.adapter.require_bindable_channel(external_channel_id)+ await collaboration_core.adapter.require_bindable_channel(+ external_channel_id+ )- if bridge_core and external_channel_id is not None and channel_type is None:- channel_type = await bridge_core.adapter.get_channel_type(+ if (+ collaboration_core+ and external_channel_id is not None+ and channel_type is None+ ):+ channel_type = await collaboration_core.adapter.get_channel_type(external_channel_id)@@ -521,18 +527,20 @@ class RoomService:is_dm = (channel_type == "direct"- and bridge_core is not None+ and collaboration_core is not Noneand external_channel_id is None)if is_dm:self._validate_dm_room(config, agent_ids)- if bridge_core and external_channel_id is None:+ if collaboration_core and external_channel_id is None:await self._require_channel_creation(bridge_id) # type: ignore[arg-type]if is_dm:user_name = (config.user_names or [])[0]agent_name = (await self._resolve_ids_to_names(agent_ids))[0]- ext_id_map = await bridge_core.resolve_external_user_id_map([user_name])+ ext_id_map = await collaboration_core.resolve_external_user_id_map(+ [user_name]+ )user_external_id = ext_id_map.get(user_name)if user_external_id is None:raise ValueError(@@ -540,13 +548,15 @@ class RoomService:"this bridge. The user must have interacted with Switch on ""the platform before a DM can be opened with them.")- external_channel_id = await bridge_core.adapter.create_dm_channel(- agent_name=agent_name,- user_name=user_name,- user_external_id=user_external_id,+ external_channel_id = (+ await collaboration_core.adapter.create_dm_channel(+ agent_name=agent_name,+ user_name=user_name,+ user_external_id=user_external_id,+ ))else:- external_channel_id = await bridge_core.adapter.create_channel(+ external_channel_id = await collaboration_core.adapter.create_channel(config.name,config.description,channel_type=channel_type,@@ -557,15 +567,15 @@ class RoomService:# it, which fires an inbound join; without this guard that join would# not see the not-yet-committed mapping and would auto-create a second# room for the same channel (CHOO-1660).- if bridge_core and external_channel_id:- bridge_core.begin_provisioning(external_channel_id)+ if collaboration_core and external_channel_id:+ collaboration_core.begin_provisioning(external_channel_id)try:- matrix_room_id = await self._matrix_admin.create_room(+ transport_room_id = await self._provisioning.create_room(config.name, config.description)room = Room(- matrix_room_id=matrix_room_id,+ transport_room_id=transport_room_id,name=config.name,description=config.description,channel_type=channel_type,@@ -612,16 +622,16 @@ class RoomService:await self._seed_aliases(session, room.id, agent_ids, config)await session.commit()- if bridge_core and external_channel_id:- bridge_core.add_room_mapping(- room.id, matrix_room_id, external_channel_id, room.tenant_id+ if collaboration_core and external_channel_id:+ collaboration_core.add_room_mapping(+ room.id, transport_room_id, external_channel_id, room.tenant_id)finally:- if bridge_core and external_channel_id:- bridge_core.end_provisioning(external_channel_id)+ if collaboration_core and external_channel_id:+ collaboration_core.end_provisioning(external_channel_id)# The room row is durably committed above. Everything from here down —- # channel capture, Matrix invites, adding agents/users on the external+ # channel capture, invites, adding agents/users on the external# platform — is best-effort against another system and can still fail# (and, on failure, still propagate out of this call, same as before).# Reported here rather than at the end of the function so a failure in@@ -664,48 +674,49 @@ class RoomService:room.id,)- if bridge_core and external_channel_id:+ if collaboration_core and external_channel_id:await self._ensure_channel_capture(- bridge_core, external_channel_id, channel_type+ collaboration_core, external_channel_id, channel_type)# Invite the bridge client before the agent clients so it is joined (and# thus replicating) before any agent can post — otherwise messages sent# in the gap predate the bridge's join and are dropped by _should_ignore,# never reaching the external channel. Mirrors change_bridge's ordering.- if bridge_core:- await self._matrix_admin.invite_to_room(- matrix_room_id, bridge_core._bridge_client_matrix_user_id+ if collaboration_core:+ await self._provisioning.invite_to_room(+ transport_room_id,+ collaboration_core._workspace_consumer_transport_user_id,)unreachable_users: list[dict[str, Any]] = []if (- bridge_core+ collaboration_coreand external_channel_idand channel_type not in ("direct", "group")):agent_names = await self._resolve_ids_to_names(agent_ids)- await bridge_core.adapter.add_agents_to_channel(+ await collaboration_core.adapter.add_agents_to_channel(external_channel_id, agent_names)if config.user_names:unreachable_users = await self._add_users_to_channel(- bridge_core, external_channel_id, config.user_names+ collaboration_core, external_channel_id, config.user_names)- await bridge_core.ensure_users_in_room(- room.id, matrix_room_id, config.user_names+ await collaboration_core.ensure_users_in_room(+ room.id, transport_room_id, config.user_names)- if bridge_core and external_channel_id and is_dm and config.user_names:- await bridge_core.ensure_users_in_room(- room.id, matrix_room_id, config.user_names+ if collaboration_core and external_channel_id and is_dm and config.user_names:+ await collaboration_core.ensure_users_in_room(+ room.id, transport_room_id, config.user_names)agent_clients = self._resolve_agent_clients(agent_ids)system_clients = self._resolve_system_clients(room.tenant_id)all_clients = {**agent_clients, **system_clients}- await self._invite_clients(matrix_room_id, all_clients)+ await self._invite_clients(transport_room_id, all_clients)async with tenant_session(self._session_factory, room.tenant_id) as session:for client_id in all_clients:@@ -715,7 +726,7 @@ class RoomService:logger.info("Created room %s (%s) with %d agents and %d system clients",config.name,- matrix_room_id,+ transport_room_id,len(agent_clients),len(system_clients),)@@ -785,20 +796,20 @@ class RoomService: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._provisioning.kick_user(+ room.transport_room_id, client.transport_user_id)- await self._matrix_admin.delete_room(room.matrix_room_id)+ await self._provisioning.delete_room(room.transport_room_id)async with self._session_factory() as session:await self._room_store.delete(session, room_id)await session.commit()if bridge_id:- bridge_core = self._collab_lifecycle.get(bridge_id)- if bridge_core:- bridge_core.remove_room_mapping(room.id, room.matrix_room_id)+ collaboration_core = self._collab_lifecycle.get(bridge_id)+ if collaboration_core:+ collaboration_core.remove_room_mapping(room.id, room.transport_room_id)logger.info("Deleted room %s", room_id)@@ -889,7 +900,7 @@ class RoomService:)await session.commit()- await self._invite_clients(room.matrix_room_id, agent_clients)+ await self._invite_clients(room.transport_room_id, agent_clients)async with self._session_factory() as session:for client_id in agent_clients:@@ -897,10 +908,10 @@ class RoomService:await session.commit()if room.bridge_id and room.external_channel_id:- bridge_core = self._collab_lifecycle.get(room.bridge_id)- if bridge_core:+ collaboration_core = self._collab_lifecycle.get(room.bridge_id)+ if collaboration_core:agent_names_resolved = await self._resolve_ids_to_names(new_agent_ids)- await bridge_core.adapter.add_agents_to_channel(+ await collaboration_core.adapter.add_agents_to_channel(room.external_channel_id, agent_names_resolved)@@ -940,8 +951,10 @@ class RoomService:await self._room_store.remove_agents(session, room_id, agent_ids)await session.commit()- for matrix_user_id in agent_clients.values():- await self._matrix_admin.kick_user(room.matrix_room_id, matrix_user_id)+ for transport_user_id in agent_clients.values():+ await self._provisioning.kick_user(+ room.transport_room_id, transport_user_id+ )logger.info("Removed %d agents from room %s", len(agent_ids), room_id)@@ -1126,19 +1139,19 @@ class RoomService:raise ValueError(f"Room not found: {room_id}")if not room.bridge_id or not room.external_channel_id:raise ValueError(f"Room {room_id} is not bridged")- bridge_core = self._collab_lifecycle.get(room.bridge_id)- if bridge_core is None:+ collaboration_core = self._collab_lifecycle.get(room.bridge_id)+ if collaboration_core is None:raise ValueError(f"Bridge not running: {room.bridge_id}")- resolved = await bridge_core.resolve_external_user_id_map(user_names)+ resolved = await collaboration_core.resolve_external_user_id_map(user_names)unresolved = [name for name in user_names if name not in resolved]resolved_names = list(resolved.keys())- failed_ids = await bridge_core.adapter.add_users_to_channel(+ failed_ids = await collaboration_core.adapter.add_users_to_channel(room.external_channel_id, resolved_names, list(resolved.values()))by_id = {resolved[name]: name for name in resolved_names}unresolved.extend(by_id.get(fid, fid) for fid in failed_ids)- await bridge_core.ensure_users_in_room(- room.id, room.matrix_room_id, resolved_names+ await collaboration_core.ensure_users_in_room(+ room.id, room.transport_room_id, resolved_names)logger.info("Added %d users to room %s", len(resolved_names), room_id)if unresolved:@@ -1170,11 +1183,11 @@ class RoomService:raise ValueError(f"Room not found: {room_id}")await self._require_tenant_bridge(bridge_id)- bridge_core = self._collab_lifecycle.get(bridge_id)+ collaboration_core = self._collab_lifecycle.get(bridge_id)- if external_channel_id is None and bridge_core is not None:+ if external_channel_id is None and collaboration_core is not None:await self._require_channel_creation(bridge_id)- external_channel_id = await bridge_core.adapter.create_channel(+ external_channel_id = await collaboration_core.adapter.create_channel(room.name, room.description)@@ -1188,12 +1201,12 @@ class RoomService:)await session.commit()- if bridge_core and external_channel_id:- bridge_core.add_room_mapping(- room.id, room.matrix_room_id, external_channel_id, room.tenant_id+ if collaboration_core and external_channel_id:+ collaboration_core.add_room_mapping(+ room.id, room.transport_room_id, external_channel_id, room.tenant_id)await self._ensure_channel_capture(- bridge_core, external_channel_id, channel_type+ collaboration_core, external_channel_id, channel_type)logger.info("Linked bridge %s to room %s", bridge_id, room_id)@@ -1211,9 +1224,9 @@ class RoomService:await session.commit()if bridge_id:- bridge_core = self._collab_lifecycle.get(bridge_id)- if bridge_core:- bridge_core.remove_room_mapping(room.id, room.matrix_room_id)+ collaboration_core = self._collab_lifecycle.get(bridge_id)+ if collaboration_core:+ collaboration_core.remove_room_mapping(room.id, room.transport_room_id)logger.info("Unlinked bridge from room %s", room_id)@@ -1228,7 +1241,7 @@ class RoomService:"""Move a room onto a different collaboration bridge.Provisions a fresh external channel on the target bridge and re-adds- the room's current agents to it, then joins the target bridge's Matrix+ the room's current agents to it, then joins the target bridge'sclient so events route to the new channel.Pass ``external_channel_id`` to bind to an **existing** channel on the@@ -1245,7 +1258,7 @@ class RoomService:re-invited to the new channel manually. A warning is logged saying so.The old bridge is then detached: its in-memory room mapping is removed- (so it stops syncing) and its Matrix client is kicked from the room.+ (so it stops syncing) and its client is kicked from the room.The old external channel itself is **left in place** on its platform —the adapter has no teardown primitive — so it lingers as an orphan thatis no longer synced. A warning is logged disclosing this; archive or@@ -1262,7 +1275,7 @@ class RoomService:old_bridge_id = room.bridge_idold_external_channel_id = room.external_channel_id- matrix_room_id = room.matrix_room_id+ transport_room_id = room.transport_room_idif old_bridge_id == bridge_id:raise ValueError(f"Room {room_id} is already bound to bridge {bridge_id}")@@ -1307,7 +1320,7 @@ class RoomService:await session.commit()new_bridge.add_room_mapping(- room_id, matrix_room_id, external_channel_id, room.tenant_id+ room_id, transport_room_id, external_channel_id, room.tenant_id)finally:new_bridge.end_provisioning(external_channel_id)@@ -1315,8 +1328,8 @@ class RoomService:await self._ensure_channel_capture(new_bridge, external_channel_id, resolved_channel_type)- await self._matrix_admin.invite_to_room(- matrix_room_id, new_bridge._bridge_client_matrix_user_id+ await self._provisioning.invite_to_room(+ transport_room_id, new_bridge._workspace_consumer_transport_user_id)if resolved_channel_type not in ("direct", "group"):@@ -1337,9 +1350,10 @@ class RoomService:if old_bridge_id:old_bridge = self._collab_lifecycle.get(old_bridge_id)if old_bridge is not None:- old_bridge.remove_room_mapping(room_id, matrix_room_id)- await self._matrix_admin.kick_user(- matrix_room_id, old_bridge._bridge_client_matrix_user_id+ old_bridge.remove_room_mapping(room_id, transport_room_id)+ await self._provisioning.kick_user(+ transport_room_id,+ old_bridge._workspace_consumer_transport_user_id,)logger.warning("Room %s moved from bridge %s to %s; old external channel %s "@@ -1361,17 +1375,17 @@ class RoomService:)def _resolve_agent_clients(self, agent_ids: list[str]) -> dict[str, str]:- """Returns {client_id: matrix_user_id} for the given agent IDs."""+ """Returns {client_id: transport_user_id} for the given agent IDs."""result: dict[str, str] = {}for agent_id in agent_ids:client = self._client_lifecycle.get_by_agent_id(agent_id)if client is None:raise ValueError(f"No running client for agent: {agent_id}")- result[client.client_id] = client.matrix_user_id+ result[client.client_id] = client.transport_user_idreturn resultdef _resolve_system_clients(self, tenant_id: str) -> dict[str, str]:- """`{client_id: matrix_user_id}` for `tenant_id`'s system clients.+ """`{client_id: transport_user_id}` for `tenant_id`'s system clients.Per tenant, not per deployment. `clients` is scoped, so there is anadmin client per tenant rather than one for everyone, and the running@@ -1383,18 +1397,20 @@ class RoomService:result: dict[str, str] = {}for client_type in SYSTEM_CLIENT_TYPES:for client in self._client_lifecycle.get_by_type(client_type, tenant_id):- result[client.client_id] = client.matrix_user_id+ result[client.client_id] = client.transport_user_idreturn resultasync def _invite_clients(- self, matrix_room_id: str, client_ids: dict[str, str]+ self, transport_room_id: str, client_ids: dict[str, str]) -> None:- """Invites all clients to the Matrix room; each client auto-accepts."""- for matrix_user_id in client_ids.values():- await self._matrix_admin.invite_to_room(matrix_room_id, matrix_user_id)+ """Invites all clients to the room; each client auto-accepts."""+ for transport_user_id in client_ids.values():+ await self._provisioning.invite_to_room(+ transport_room_id, transport_user_id+ )async def reconcile_room_clients(self) -> None:- """Ensure every room's clients are actually in it, on Matrix.+ """Ensure every room's clients are actually in it.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@@ -1467,7 +1483,7 @@ class RoomService:missing = {cid: uid for cid, uid in expected.items() if cid not in existing}if not missing:return- await self._invite_clients(room.matrix_room_id, missing)+ await self._invite_clients(room.transport_room_id, missing)async with self._session_factory() as session:for client_id in missing:await self._room_store.add_client(session, client_id, room.id)@@ -1486,15 +1502,15 @@ class RoomService:on it then."""await self._require_tenant_bridge(bridge_id)- bridge_core = self._collab_lifecycle.get(bridge_id)- if bridge_core is None:+ collaboration_core = self._collab_lifecycle.get(bridge_id)+ if collaboration_core is None:raise ValueError("the room's messaging app is not running")- return await bridge_core.resolve_external_user_id_map(names)+ return await collaboration_core.resolve_external_user_id_map(names)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 recordits membership. Idempotent — safe to call repeatedly, e.g. on every- bridged message from an external user's puppet."""+ bridged message from an external user's human actor."""room = await self._load_room(room_id)async with tenant_session(self._session_factory, room.tenant_id) as session:already_member = client_id in await self._room_store.get_client_ids(@@ -1510,8 +1526,8 @@ class RoomService:# so it is bound here alongside the membership record below rather# than left to whatever tenant happened to already be ambient.with tenant_scope(room.tenant_id):- await self._matrix_admin.invite_to_room(- room.matrix_room_id, client.matrix_user_id+ await self._provisioning.invite_to_room(+ room.transport_room_id, client.transport_user_id)if not already_member:diff --git a/core/switch_core/room_wide_mention.py b/core/switch_core/room_wide_mention.pyindex 260332e33..3ef3fb211 100644--- a/core/switch_core/room_wide_mention.py+++ b/core/switch_core/room_wide_mention.py@@ -32,7 +32,7 @@ ROOM_WIDE_TARGET = "everyone"RESERVED_MENTION_NAMES = frozenset({ROOM_WIDE_TARGET, "channel", "here", "all"})# Stamped on the content of a message the server sent as a room-wide mention.-# Only `ProtocolService.send_targeted_message` writes it; a bridge reads it to+# Only `AgentCore.send_targeted_message` writes it; a bridge reads it to# decide whether to render the platform's channel-wide mention.ROOM_WIDE_MENTION_MARKER = "com.switch.room_wide_mention"diff --git a/core/switch_core/rooms_yaml.py b/core/switch_core/rooms_yaml.pyindex 899dd32e7..ee938bd31 100644--- a/core/switch_core/rooms_yaml.py+++ b/core/switch_core/rooms_yaml.py@@ -42,7 +42,7 @@ from pydantic import BaseModel, Field, TypeAdapter, ValidationError, model_validfrom switch_core.agent_runs import AgentOrigin, kickoff_fingerprintfrom switch_core.bridges.collaboration.models import ChannelTypefrom switch_core.bridges.resource.registry import validate_reference_value-from switch_core.clients.admin_client import AdminClient+from switch_core.clients.actor import SystemActorfrom switch_core.clients.admin_messages import OnBehalfOffrom switch_core.room_service import RoleSpec, RoomCreateConfig@@ -1305,13 +1305,13 @@ class RoomYamlService:fail("kickoff posting is not configured on this server")returnadmins = self._client_lifecycle.get_by_type("admin", room.tenant_id)- admin = next((c for c in admins if isinstance(c, AdminClient)), None)+ admin = next((c for c in admins if isinstance(c, SystemActor)), None)if admin is None:fail("the platform has no client to post with")returnlate = await self._wait_for_kickoff_audience(- room.matrix_room_id, admin, agent_names+ room.transport_room_id, admin, agent_names)if late:fail("did not join the room in time to see the kickoff: " + ", ".join(late))@@ -1328,13 +1328,13 @@ class RoomYamlService:headline = f"Template kickoff on behalf of {person.label}"try:root_id = await admin.send_platform_message(- room.matrix_room_id, headline, on_behalf_of=person+ room.transport_room_id, headline, on_behalf_of=person)if root_id is None:fail("the platform could not post the kickoff")returnevent_id = await admin.send_platform_message(- room.matrix_room_id,+ room.transport_room_id,text,thread_root_id=root_id,on_behalf_of=person,@@ -1348,8 +1348,8 @@ class RoomYamlService:async def _wait_for_kickoff_audience(self,- matrix_room_id: str,- admin: AdminClient,+ transport_room_id: str,+ admin: SystemActor,agent_names: list[str],) -> list[str]:"""Wait for the sender and the template's agents to be in the room.@@ -1360,7 +1360,7 @@ class RoomYamlService:miss anything."""late: list[str] = []- if not await admin.wait_joined(matrix_room_id, KICKOFF_JOIN_TIMEOUT):+ if not await admin.wait_joined(transport_room_id, KICKOFF_JOIN_TIMEOUT):late.append("the platform")if not agent_names or self._client_lifecycle is None:return late@@ -1371,7 +1371,9 @@ class RoomYamlService:if client is None:continuetry:- joined = await client.wait_joined(matrix_room_id, KICKOFF_JOIN_TIMEOUT)+ joined = await client.wait_joined(+ transport_room_id, KICKOFF_JOIN_TIMEOUT+ )except RuntimeError:# Not connected: it is not receiving anything either way.continuediff --git a/core/switch_core/session_activity/bridge_answers.py b/core/switch_core/session_activity/bridge_answers.pyindex c30b0f2d0..fbcafb8b8 100644--- a/core/switch_core/session_activity/bridge_answers.py+++ b/core/switch_core/session_activity/bridge_answers.py@@ -4,7 +4,7 @@ The inbound half of `bridge_publisher`. A press carries the card's token andthe option; a typed answer names the card by its handle (`A3 yes`, `A3 q1=2q2=use staging`), or is a bare "yes" / "no" as the first reply to an approvalcard. Either resolves to one `approval_request_posts` row, and from there to-the request itself, which `SessionActivityService.answer_approval` checks:+the request itself, which `AgentSessionActivityService.answer_approval` checks:open, unexpired, fits what was asked, and from someone who may address theagent.@@ -46,11 +46,11 @@ from switch_core.db.models import (from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.session_activity_post_store import ApprovalRequestPostStorefrom switch_core.db.stores.session_activity_store import ApprovalRequestStore-from switch_core.session_activity.bridge_publisher import HANDLE_PREFIXfrom switch_core.session_activity.cards import approval_request+from switch_core.session_activity.publisher import HANDLE_PREFIXfrom switch_core.session_activity.service import (+ AgentSessionActivityService,PlatformPerson,- SessionActivityService,)from switch_core.sessions.contract import RequestResultfrom switch_core.sessions.errors import SessionError@@ -72,7 +72,7 @@ class ApprovalAnswers:self,*,bridge_id: str,- service: SessionActivityService,+ service: AgentSessionActivityService,session_factory: async_sessionmaker[AsyncSession],identify: Callable[[InboundActor], Awaitable[str | None]],is_first_reply: Callable[[str, str, str], Awaitable[bool]],diff --git a/core/switch_core/session_activity/bridge_turns.py b/core/switch_core/session_activity/bridge_turns.pyindex 2cd52201b..cff7c097c 100644--- a/core/switch_core/session_activity/bridge_turns.py+++ b/core/switch_core/session_activity/bridge_turns.py@@ -16,7 +16,7 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom datetime import datetime-from switch_core.db.models import SessionActivityItem+from switch_core.db.models import AgentSessionActivityItemfrom switch_core.db.stores.session_activity_store import TURN_ITEM_IDfrom switch_core.sessions.contract import TURN_ENDED, Item, TurnUpsert@@ -30,7 +30,7 @@ class TurnView:turn: TurnUpsertitems: list[Item]# The turn's own row: where it was asked, and when it started and ended.- row: SessionActivityItem+ row: AgentSessionActivityItemstarted_at: datetime@property@@ -54,7 +54,7 @@ class TurnView:return max(0.0, elapsed)-def turn_view(rows: list[SessionActivityItem]) -> TurnView | None:+def turn_view(rows: list[AgentSessionActivityItem]) -> TurnView | None:"""The turn its rows describe, or None until its own row has been reported."""row = next((r for r in rows if r.item_id == TURN_ITEM_ID), None)if row is None:diff --git a/core/switch_core/session_activity/cards.py b/core/switch_core/session_activity/cards.pyindex 1960f87e1..dd453b4a9 100644--- a/core/switch_core/session_activity/cards.py+++ b/core/switch_core/session_activity/cards.py@@ -168,7 +168,7 @@ async def answerer_of().join(Client, Client.id == ExternalUser.client_id).join(CollaborationBridge, CollaborationBridge.id == ExternalUser.bridge_id)- .where(Client.matrix_user_id == answered_by)+ .where(Client.transport_user_id == answered_by).limit(1))).first()diff --git a/core/switch_core/session_activity/listener.py b/core/switch_core/session_activity/listener.pyindex 735f7bfc9..1b0f6f06c 100644--- a/core/switch_core/session_activity/listener.py+++ b/core/switch_core/session_activity/listener.py@@ -107,7 +107,7 @@ class _Subscriber:_RESYNC = object()-class SessionActivityListener:+class AgentSessionActivityListener:def __init__(self, engine_factory: EngineFactory) -> None:self._engine_factory = engine_factoryself._subscribers: dict[str, set[_Subscriber]] = {}@@ -140,7 +140,7 @@ class SessionActivityListener:async def start(self) -> None:if self._running:- raise RuntimeError("SessionActivityListener is already started")+ raise RuntimeError("AgentSessionActivityListener is already started")self._running = Trueself._tasks = [asyncio.create_task(diff --git a/core/switch_core/session_activity/maintenance.py b/core/switch_core/session_activity/maintenance.pyindex 1efef3416..adcab1849 100644--- a/core/switch_core/session_activity/maintenance.py+++ b/core/switch_core/session_activity/maintenance.py@@ -18,7 +18,7 @@ from datetime import timedeltafrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.db.tenant_lookup import all_tenant_ids-from switch_core.session_activity.service import SessionActivityService+from switch_core.session_activity.service import AgentSessionActivityServicefrom switch_core.tenant_context import no_tenant, tenant_scopelogger = logging.getLogger(__name__)@@ -32,7 +32,7 @@ async def maintain_once(session_factory: async_sessionmaker[AsyncSession], *, prune: bool) -> None:"""One pass over every tenant: expire overdue requests, and prune if asked."""- service = SessionActivityService(session_factory)+ service = AgentSessionActivityService(session_factory)for tenant_id in await all_tenant_ids(session_factory):with tenant_scope(tenant_id):try:diff --git a/core/switch_core/session_activity/outcomes.py b/core/switch_core/session_activity/outcomes.pyindex 6711a7c57..16206ecee 100644--- a/core/switch_core/session_activity/outcomes.py+++ b/core/switch_core/session_activity/outcomes.py@@ -1,7 +1,7 @@"""The outcomes an agent is owed on its stream: answers and expiries.Joins the two halves an agent stream needs. Live outcomes come pushed from-`SessionActivityListener`, with the row attached. Undelivered ones come from+`AgentSessionActivityListener`, with the row attached. Undelivered ones come fromthe table: everything answered or expired that the agent has not acknowledged,read when a stream opens and whenever the listener says announcements may havebeen missed.@@ -19,8 +19,8 @@ from datetime import datetimefrom typing import Anyfrom switch_core.db.models import ApprovalRequest-from switch_core.session_activity.listener import Change, SessionActivityListener-from switch_core.session_activity.service import SessionActivityService+from switch_core.session_activity.listener import AgentSessionActivityListener, Change+from switch_core.session_activity.service import AgentSessionActivityServiceOUTCOME_KINDS = frozenset({"approval.answered", "approval.expired"})@@ -53,7 +53,9 @@ def outcome_of(row: ApprovalRequest | dict[str, Any]) -> Outcome:class ApprovalOutcomes:def __init__(- self, listener: SessionActivityListener, service: SessionActivityService+ self,+ listener: AgentSessionActivityListener,+ service: AgentSessionActivityService,) -> None:self._listener = listenerself._service = servicediff --git a/core/switch_core/session_activity/bridge_publisher.py b/core/switch_core/session_activity/publisher.pysimilarity index 97%rename from core/switch_core/session_activity/bridge_publisher.pyrename to core/switch_core/session_activity/publisher.pyindex e419a81fb..0e233f2b7 100644--- a/core/switch_core/session_activity/bridge_publisher.py+++ b/core/switch_core/session_activity/publisher.py@@ -1,6 +1,6 @@"""Puts session activity and requests on one bridge's platform.-Pushed, not scanned: `SessionActivityListener` hands every change for the+Pushed, not scanned: `AgentSessionActivityListener` hands every change for thebridge's tenant to `_on_change`, which only queues a key. A task of thisbridge's own drains the queue and does the platform work, so a slow or ratelimited platform never holds up the listener's other subscribers.@@ -50,7 +50,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.collaboration.adapter import (ActivityMarkRefused,ActivitySnapshot,- CollaborationAdapter,+ PlatformAdapter,RemovalFailed,RichContentFailed,RichContentThrottled,@@ -60,12 +60,12 @@ from switch_core.bridges.collaboration.adapter import ()from switch_core.db.models import (Agent,+ AgentSessionActivityItem,ApprovalRequest,ApprovalRequestPost,BridgeMessageMap,Message,Room,- SessionActivityItem,TurnStatusPost,)from switch_core.db.session_scope import tenant_session@@ -76,8 +76,8 @@ from switch_core.db.stores.session_activity_post_store import ()from switch_core.db.stores.session_activity_store import (TURN_ITEM_ID,+ AgentSessionActivityStore,ApprovalRequestStore,- SessionActivityStore,)from switch_core.deeplinks import deeplink_for_platformfrom switch_core.session_activity.bridge_turns import (@@ -90,7 +90,7 @@ from switch_core.session_activity.cards import (approval_card,approval_request,)-from switch_core.session_activity.listener import Change, SessionActivityListener+from switch_core.session_activity.listener import AgentSessionActivityListener, Changefrom switch_core.sessions.contract import DecidedBy, decidedfrom switch_core.sessions.presentation import (activity_error_summary,@@ -192,15 +192,15 @@ _Key = tuple[str, ...]_RESYNC: _Key = ("resync",)-class SessionActivityBridgePublisher:+class AgentSessionActivityPublisher:def __init__(self,*,- adapter: CollaborationAdapter,+ adapter: PlatformAdapter,bridge_id: str,bridge_type: str,tenant_id: str,- listener: SessionActivityListener,+ listener: AgentSessionActivityListener,session_factory: async_sessionmaker[AsyncSession],agent_online: Callable[[str], bool],gateway_public_url: str | None,@@ -215,7 +215,7 @@ class SessionActivityBridgePublisher:self._gateway_public_url = gateway_public_urlself._approvals = ApprovalRequestStore()self._rooms = RoomStore()- self._activity = SessionActivityStore()+ self._activity = AgentSessionActivityStore()self._card_posts = ApprovalRequestPostStore()self._turn_posts = TurnStatusPostStore()self._queue: asyncio.Queue[_Key] = asyncio.Queue()@@ -236,7 +236,7 @@ class SessionActivityBridgePublisher:def start(self) -> None:if self._tasks:- raise RuntimeError("SessionActivityBridgePublisher is already started")+ raise RuntimeError("AgentSessionActivityPublisher is already started")self._unsubscribe = self._listener.subscribe(self._tenant_id, self._on_change, self._on_resync)@@ -369,37 +369,39 @@ class SessionActivityBridgePublisher:)).all()unended = and_(- SessionActivityItem.item_id == TURN_ITEM_ID,- SessionActivityItem.status.in_(("queued", "running")),+ AgentSessionActivityItem.item_id == TURN_ITEM_ID,+ AgentSessionActivityItem.status.in_(("queued", "running")),)turns = (await db.execute(select(- SessionActivityItem.agent_id,- SessionActivityItem.session_id,- SessionActivityItem.turn_id,- func.max(SessionActivityItem.updated_at),+ AgentSessionActivityItem.agent_id,+ AgentSessionActivityItem.session_id,+ AgentSessionActivityItem.turn_id,+ func.max(AgentSessionActivityItem.updated_at),func.bool_or(unended),TurnStatusPost.updated_at,)- .join(Room, Room.id == SessionActivityItem.room_id)+ .join(Room, Room.id == AgentSessionActivityItem.room_id).outerjoin(TurnStatusPost,and_(TurnStatusPost.bridge_id == self._bridge_id,- TurnStatusPost.agent_id == SessionActivityItem.agent_id,- TurnStatusPost.session_id == SessionActivityItem.session_id,- TurnStatusPost.turn_id == SessionActivityItem.turn_id,+ TurnStatusPost.agent_id+ == AgentSessionActivityItem.agent_id,+ TurnStatusPost.session_id+ == AgentSessionActivityItem.session_id,+ TurnStatusPost.turn_id == AgentSessionActivityItem.turn_id,),).where(Room.bridge_id == self._bridge_id,- or_(SessionActivityItem.updated_at >= since, unended),+ or_(AgentSessionActivityItem.updated_at >= since, unended),).group_by(- SessionActivityItem.agent_id,- SessionActivityItem.session_id,- SessionActivityItem.turn_id,+ AgentSessionActivityItem.agent_id,+ AgentSessionActivityItem.session_id,+ AgentSessionActivityItem.turn_id,TurnStatusPost.updated_at,))@@ -508,7 +510,7 @@ class SessionActivityBridgePublisher:db: AsyncSession,room_id: str,agent: Agent,- turn_row: SessionActivityItem | None,+ turn_row: AgentSessionActivityItem | None,thread_ref: str | None,) -> str | None:"""Who a post asking someone to act names: whoever asked, else the owner."""@@ -531,9 +533,9 @@ class SessionActivityBridgePublisher:async def _turn_row(self, db: AsyncSession, agent_id: str, session_id: str, turn_id: str- ) -> SessionActivityItem | None:+ ) -> AgentSessionActivityItem | None:return await db.get(- SessionActivityItem,+ AgentSessionActivityItem,(self._tenant_id, agent_id, session_id, turn_id, TURN_ITEM_ID),)@@ -1485,7 +1487,7 @@ class SessionActivityBridgePublisher:return view, await self._running_turn(db, post.agent_id, post.session_id)-def _asked_at_root(turn_row: SessionActivityItem | None) -> bool:+def _asked_at_root(turn_row: AgentSessionActivityItem | None) -> bool:"""Whether the turn a request belongs to was asked at the channel root.Only then may its card go to the root when its thread cannot be found. Adiff --git a/core/switch_core/session_activity/service.py b/core/switch_core/session_activity/service.pyindex 6d5362891..992db9a51 100644--- a/core/switch_core/session_activity/service.py+++ b/core/switch_core/session_activity/service.py@@ -24,8 +24,8 @@ from switch_core.db.models import (APPROVAL_REQUEST_KINDS,SESSION_ACTIVITY_KINDS,Agent,+ AgentSessionActivityItem,ApprovalRequest,- SessionActivityItem,UsageMetric,require_tenant_id,)@@ -37,8 +37,8 @@ from switch_core.db.stores.room_role_store import RoomRoleStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.session_activity_store import (TURN_ITEM_ID,+ AgentSessionActivityStore,ApprovalRequestStore,- SessionActivityStore,)from switch_core.db.stores.usage_store import UsageStorefrom switch_core.delivery.addressing import AddressingResolver@@ -148,11 +148,11 @@ class SwitchUser:Answerer = PlatformPerson | SwitchUser-class SessionActivityService:+class AgentSessionActivityService:def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:self._sessions = session_factoryself._approvals = ApprovalRequestStore()- self._activity = SessionActivityStore()+ self._activity = AgentSessionActivityStore()self._usage = UsageStore()self._rooms = RoomStore()self._external_users = ExternalUserStore()@@ -236,7 +236,7 @@ class SessionActivityService:)moved = await self._activity.upsert(db,- SessionActivityItem(+ AgentSessionActivityItem(tenant_id=tenant_id,agent_id=agent_id,session_id=session_id,@@ -329,7 +329,7 @@ class SessionActivityService:async def turn_items(self, agent_id: str, session_id: str, turn_id: str- ) -> list[SessionActivityItem]:+ ) -> list[AgentSessionActivityItem]:async with tenant_session(self._sessions, require_tenant_id()) as db:return await self._activity.turn(db, agent_id, session_id, turn_id)diff --git a/core/switch_core/sessions/presentation.py b/core/switch_core/sessions/presentation.pyindex cedacddab..929c6148b 100644--- a/core/switch_core/sessions/presentation.py+++ b/core/switch_core/sessions/presentation.py@@ -82,7 +82,7 @@ async def notification_recipient(return Noneactor = await db.scalar(members.join(Client, Client.id == ExternalUser.client_id)- .where(Client.matrix_user_id == actor_id)+ .where(Client.transport_user_id == actor_id).order_by(ExternalUser.id).limit(1))diff --git a/core/switch_core/telemetry/catalogue.py b/core/switch_core/telemetry/catalogue.pyindex 579cbfe3a..22ffcabd3 100644--- a/core/switch_core/telemetry/catalogue.py+++ b/core/switch_core/telemetry/catalogue.py@@ -336,6 +336,9 @@ CATALOGUE: Mapping[str, Mapping[str, PropertyType]] = {"failed_attempts_before_success": NUMBER,},"bridge_connected": {+ # Which side of the bridge: always "collaboration" today; "agent" is+ # declared so the agent bridge can report the same events.+ "bridge": one_of("collaboration", "agent"),"bridge_platform": BRIDGE_PLATFORM,"outcome": OUTCOME,# `none` on success, so the property set stays exact either way.@@ -433,6 +436,9 @@ CATALOGUE: Mapping[str, Mapping[str, PropertyType]] = {},"invitation_accepted": {"age_hours": NUMBER},"bridge_disconnected": {+ # Which side of the bridge: always "collaboration" today; "agent" is+ # declared so the agent bridge can report the same events.+ "bridge": one_of("collaboration", "agent"),"bridge_platform": BRIDGE_PLATFORM,# Shutdown reasons plus every failure `bridge_connected` can carry."reason": one_of(diff --git a/core/switch_core/telemetry/snapshot.py b/core/switch_core/telemetry/snapshot.pyindex 158f61919..bbd9f9be2 100644--- a/core/switch_core/telemetry/snapshot.py+++ b/core/switch_core/telemetry/snapshot.py@@ -59,7 +59,7 @@ from switch_core.db.tenant_lookup import all_tenant_idslogger = logging.getLogger(__name__)-# `clients.type` for a human: one puppet per external user per bridge, and the+# `clients.type` for a human: one human actor per external user per bridge, and the# only row in the schema that stands for "a person did something".HUMAN_CLIENT_TYPE = "user"AGENT_CLIENT_TYPE = "agent"diff --git a/core/switch_core/transport/ephemeral.py b/core/switch_core/transport/ephemeral.pyindex 76dfeb494..3c4199381 100644--- a/core/switch_core/transport/ephemeral.py+++ b/core/switch_core/transport/ephemeral.py@@ -20,8 +20,8 @@ value, and a missed one costs a briefly stale indicator rather than data.**It is in-process, the same limitation `InviteBus` documents**, and it shouldbe lifted at the same time and in the same way. A second replica needs a-cross-process signal for both; until switch-core can run more than one, this is-no worse than the Matrix sessions it replaces.+cross-process signal for both, which is why switch-core runs as a single+replica until then."""from __future__ import annotationsdiff --git a/core/switch_core/transport/invites.py b/core/switch_core/transport/invites.pyindex 74f99fc33..5f3ab05f1 100644--- a/core/switch_core/transport/invites.py+++ b/core/switch_core/transport/invites.py@@ -1,7 +1,7 @@"""How a client is told its membership of a room changed.Over Matrix this was an event: the admin invited a user, the user's sync loop-saw the invitation and `ClientBase.on_invite` joined. Nothing else had to know+saw the invitation and `Consumer.on_invite` joined. Nothing else had to knowthe order things happened in, because the invitation was durable and the clientpicked it up whenever it next synced.@@ -19,11 +19,10 @@ leaves it reading a room it is no longer in. A removal must therefore be rungas well as written.**It is in-process, and that is a real limitation.** A client running in-another replica of switch-core would not hear it. That is the same constraint-Matrix sync sessions imposed and the reason switch-core is single-replica-today; lifting it is its own step, and until then this is no worse than what it-replaces. When nobody is listening for a client the caller writes the-membership itself, so the room is still joined the next time that client+another replica of switch-core would not hear it. It is one of the reasons+switch-core is single-replica today (the Helm chart refuses anything else);+lifting it is its own step. When nobody is listening for a client the caller+writes the membership itself, so the room is still joined the next time that clientstarts — the invitation is a wake-up, never the record.**Keyed by client id, which is a primary key.** It used to be keyed bydiff --git a/core/switch_core/transport/postgres.py b/core/switch_core/transport/postgres.pyindex dbef6b843..8bf397741 100644--- a/core/switch_core/transport/postgres.py+++ b/core/switch_core/transport/postgres.py@@ -1,35 +1,31 @@-"""Postgres implementation of `MessageTransport`.--The homeserver's remaining job is to carry an event from the client that sent-it to the clients that should see it, and to remember it in between. A table-does all three, and Switch already writes that table: every send is recorded-into `messages` today, beside the send, so the rows exist and have been-verified against the bus.--This turns that parallel record into the thing itself. **The write is the-send.** There is no second store to agree with, which is why the reconciler-this stack built has no work left once the flip happens — it exists to compare-two records of the same event, and there is only one.+"""Postgres implementation of `MessageTransport`, and Switch's message bus.++A transport carries an event from the client that sent it to the clients that+should see it, and remembers it in between. Here the `messages` table does all+of that. **The write is the send.** A send is an INSERT, numbered per room+under an advisory lock (`MessageStore.create`); the `messages_notify` trigger+announces it on commit (`db/notify_ddl.py`); one `MessageListener` wakes the+transports watching that room (`messages/notify.py`); and each transport reads+the rows after its own cursor, `_DELIVERY_PAGE` at a time. There is no second+store to agree with. Switch used to run on a Matrix homeserver; the+`matrix_*` column names are what is left of it, kept as stable ids.Three consequences worth stating up front:-- **A send now fails when the database does.** The recorder deliberately could- not fail a send, because a row was a nice-to-have next to a delivered- message. Here the row *is* the delivery, so there is nothing left to protect:- a write that fails is a message that was not sent, and the caller must hear- about it.-- **Every durable event gets a row, not only the conversation.** The bus- carried commands and task events too, and they have to reach their handlers.- `recorded_types` therefore stops meaning "what is written" and starts meaning- "what a reader is shown" — a projection applied on the way out. The one+- **A send fails when the database does.** The row *is* the delivery: a write+ that fails is a message that was not sent, and the caller must hear about+ it.+- **Every durable event gets a row, not only the conversation.** Commands and+ task events travel the same way, and they have to reach their handlers.+ `recorded_types` therefore means "what a reader is shown", not "what is+ written": a projection applied on the way out. The onecategory with no row is the genuinely ephemeral: presence-like state whosenext value replaces it, which is announced and never stored.- **Ids are opaque, and these are not `$event` ids.** Nothing in Switch parsesone; the columns holding them are already named `transport_event_id`.History is the one method left unimplemented, and deliberately: the read path-already queries these rows directly, and the only callers left are the walkers-that exist to compare a bus against them.+queries these rows directly."""from __future__ import annotations@@ -160,8 +156,8 @@ def new_event_id() -> str:class PostgresTransport:"""Carries a room's events in the `messages` table.- One instance per client, as with the Matrix transport: it sends as that- client and, once receiving lands, delivers to that client's handlers.+ One instance per client: it sends as that client and, once it is+ receiving, delivers to that client's handlers."""def __init__(@@ -171,6 +167,7 @@ class PostgresTransport:client_id: str,tenant_id: str,display_name: str,+ actor_role: str,session_factory: async_sessionmaker[AsyncSession],room_store: RoomStore,message_store: MessageStore,@@ -182,6 +179,9 @@ class PostgresTransport:) -> None:self.user_id = user_idself.client_id = client_id+ # Who this client is in message metrics: the writer of what it sends+ # and the reader of what it is handed. Bounded, never an id.+ self._actor_role = actor_role# The tenant everything this transport reads and writes is scoped to,# handed in with the client id rather than looked up from it. Neither# this transport's context nor its caller's is the right answer — the@@ -253,10 +253,9 @@ class PostgresTransport:if not rooms:logger.error("Client %s is receiving but is a member of no room: it will "- "hear nothing until something adds it to one. Under Matrix "- "membership lived on the homeserver; here it is the "- "client_rooms table, so a client whose rows were never "- "written is silent rather than broken",+ "hear nothing until something adds it to one. Membership "+ "is the client_rooms table, so a client whose rows were "+ "never written is silent rather than broken",self.user_id,)delivery = asyncio.create_task(self._deliver_forever())@@ -316,7 +315,9 @@ class PostgresTransport:# problem, and this loop is the only delivery this# client has. Counted as well as logged: swallowing# it is what makes a stalled room invisible.- metrics().increment(DELIVERY_FAILURES, {})+ metrics().increment(+ DELIVERY_FAILURES, {"actor": self._actor_role}+ )logger.error("Delivery failed for client %s in room %s",self.user_id,@@ -571,10 +572,14 @@ class PostgresTransport:if handler is None:returnkind = _delivered_kind(event)- metrics().increment(MESSAGES_DELIVERED, {"kind": kind})+ metrics().increment(+ MESSAGES_DELIVERED, {"kind": kind, "actor": self._actor_role}+ )lag_ms = _age_ms(row.sent_at)if lag_ms is not None:- metrics().observe(DELIVERY_LAG, {"kind": kind}, lag_ms)+ metrics().observe(+ DELIVERY_LAG, {"kind": kind, "actor": self._actor_role}, lag_ms+ )await handler(room, event)def _handler_for(self, event: InboundEvent) -> Handler | None:@@ -688,7 +693,9 @@ class PostgresTransport:event_type=event_type,),)- metrics().increment(MESSAGES_SENT, {"kind": kind})+ metrics().increment(+ MESSAGES_SENT, {"kind": kind, "actor": self._actor_role}+ )return resulttry:@@ -724,9 +731,11 @@ class PostgresTransport:# `MESSAGES_SENT` is recorded only after the commit, so without# this a database outage reads as silence — and so does a quiet# room.- metrics().increment(SEND_FAILURES, {"kind": kind})+ metrics().increment(+ SEND_FAILURES, {"kind": kind, "actor": self._actor_role}+ )raise- metrics().increment(MESSAGES_SENT, {"kind": kind})+ metrics().increment(MESSAGES_SENT, {"kind": kind, "actor": self._actor_role})return resultasync def set_typing(self, room_id: str, is_typing: bool) -> None:@@ -882,7 +891,7 @@ class PostgresTransport:"""async with tenant_session(self._session_factory, self.tenant_id) as session:rooms = await self._room_store.get_for_client(session, self.client_id)- return [room.matrix_room_id for room in rooms if room.matrix_room_id]+ return [room.transport_room_id for room in rooms if room.transport_room_id]async def set_display_name(self, display_name: str) -> None:"""Held on the client row, which is where every reader already looks."""@@ -904,7 +913,9 @@ class PostgresTransport:cached = self._room_ids.get(transport_room_id)if cached is not None:return cached- room = await self._room_store.get_by_matrix_room_id(session, transport_room_id)+ room = await self._room_store.get_by_transport_room_id(+ session, transport_room_id+ )if room is None:raise TransportError(f"{transport_room_id} is not a Switch room")self._room_ids[transport_room_id] = room.id@@ -937,9 +948,8 @@ def to_inbound() -> InboundEvent:"""One stored row as the event a handler expects.- Which of the four inbound shapes a row becomes is read off the row itself,- the same way the Matrix transport reads it off the event class: an- arrival, a file, a `com.switch.*` payload, or a message. The row keeps the+ Which of the four inbound shapes a row becomes is read off the row itself:+ an arrival, a file, a `com.switch.*` payload, or a message. The row keeps thewhole content dict, so nothing is reconstructed here that was not sent."""content = dict(row.content)diff --git a/core/tests/benchmarks/client.py b/core/tests/benchmarks/client.pyindex 1d2c7eb96..a0593b9c3 100644--- a/core/tests/benchmarks/client.py+++ b/core/tests/benchmarks/client.py@@ -20,7 +20,9 @@ from typing import Anyimport httpx-from switch_core.bridges.agent.protocol.connections import HEARTBEAT_INTERVAL_SECONDS+from switch_core.bridges.agent.protocol.agent_connections import (+ HEARTBEAT_INTERVAL_SECONDS,+)@dataclass(frozen=True, slots=True)diff --git a/core/tests/benchmarks/server.py b/core/tests/benchmarks/server.pyindex b061cf337..3fcfa14ab 100644--- a/core/tests/benchmarks/server.py+++ b/core/tests/benchmarks/server.py@@ -33,24 +33,24 @@ from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.agent.app import create_agent_bridge_app-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.event_buffer import EventBuffer-from switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.agent.protocol.types import (IntegrationProfile,TaskProtocolConfig,)from switch_core.bridges.resource.service import ResourceService-from switch_core.clients.agent_client import AgentClient-from switch_core.clients.client_base import ClientBase+from switch_core.clients.actor import Actor, AgentActor, HumanActor+from switch_core.clients.agent_consumer import AgentConsumerfrom switch_core.clients.client_factory import ClientFactoryfrom switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.db.engine import create_unpooled_enginefrom switch_core.db.models import (TENANT_ZERO_ID,+ AgentSessionActivityItem,ApprovalRequest,Message,- SessionActivityItem,User,)from switch_core.db.session_scope import tenant_session@@ -65,9 +65,9 @@ from switch_core.observability.runtime import EventLoopLagfrom switch_core.provisioning import Provisioningfrom switch_core.provisioning.postgres import PostgresProvisioningfrom switch_core.room_service import RoomCreateConfig, RoomService-from switch_core.session_activity.listener import SessionActivityListener+from switch_core.session_activity.listener import AgentSessionActivityListenerfrom switch_core.session_activity.outcomes import ApprovalOutcomes-from switch_core.session_activity.service import SessionActivityService, SwitchUser+from switch_core.session_activity.service import AgentSessionActivityService, SwitchUserfrom switch_core.sessions.contract import ApprovalResultfrom switch_core.tenant_context import bind_tenant_id, tenant_scopefrom switch_core.transport.ephemeral import EphemeralBus@@ -125,17 +125,17 @@ class BenchServer:*,base_url: str,port: int,- protocol: ProtocolService,+ protocol: AgentCore,room_service: RoomService,client_lifecycle: ClientLifecycleService,event_buffer: EventBuffer,- connections: ConnectionRegistry,+ connections: AgentConnectionRegistry,collector: TraceCollector,requests: RequestCounter,statements: Counter[str],owner_id: str,session_factory: async_sessionmaker[AsyncSession],- activity: SessionActivityService,+ activity: AgentSessionActivityService,agents: tuple[BenchAgent, ...],) -> None:self.base_url = base_url@@ -192,14 +192,14 @@ class BenchServer:found.setdefault(correlation, []).append(room_id)return found- async def activity_rows(self, agent_id: str) -> list[SessionActivityItem]:+ async def activity_rows(self, agent_id: str) -> list[AgentSessionActivityItem]:"""The turn-step rows this agent's session hosts reported."""async with tenant_session(self._session_factory, TENANT_ZERO_ID) as db:return list((await db.execute(- select(SessionActivityItem).where(- SessionActivityItem.agent_id == agent_id+ select(AgentSessionActivityItem).where(+ AgentSessionActivityItem.agent_id == agent_id)))@@ -260,7 +260,7 @@ class BenchServer:client = await self._await_client(agent.agent_id, deadline)await client.wait_ready()- async def _await_client(self, agent_id: str, deadline: float) -> AgentClient:+ async def _await_client(self, agent_id: str, deadline: float) -> AgentConsumer:while asyncio.get_event_loop().time() < deadline:client = self.client_lifecycle.get_by_agent_id(agent_id)if client is not None:@@ -443,14 +443,16 @@ async def _serve(# raises instead of unbinding.bind_tenant_id(TENANT_ZERO_ID)event_buffer = EventBuffer()- connections = ConnectionRegistry()+ connections = AgentConnectionRegistry()collab_lifecycle = _NoBridges()message_listener = MessageListener(lambda: create_unpooled_engine(config))await message_listener.start()- activity_listener = SessionActivityListener(lambda: create_unpooled_engine(config))+ activity_listener = AgentSessionActivityListener(+ lambda: create_unpooled_engine(config)+ )await activity_listener.start()- activity = SessionActivityService(session_factory)+ activity = AgentSessionActivityService(session_factory)invites = InviteBus()ephemeral = EphemeralBus()@@ -484,7 +486,8 @@ async def _serve()client_factory.register("agent",- AgentClient,+ AgentActor,+ AgentConsumer,event_buffer=event_buffer,agent_store=session_env.agent_store,room_store=session_env.room_store,@@ -497,11 +500,11 @@ async def _serve(connections=connections,frontend_base_url=config.frontend_base_url,)- client_factory.register("user", ClientBase)- client_factory.register("bridge", ClientBase)+ client_factory.register("user", HumanActor)+ client_factory.register("bridge", Actor)client_lifecycle = ClientLifecycleService(- matrix_admin=provisioning,+ provisioning=provisioning,client_store=session_env.client_store,tenant_store=TenantStore(),client_factory=client_factory,@@ -510,7 +513,7 @@ async def _serve()room_service = RoomService(- matrix_admin=provisioning,+ provisioning=provisioning,room_store=session_env.room_store,agent_store=session_env.agent_store,client_lifecycle=client_lifecycle,diff --git a/core/tests/integration/conftest.py b/core/tests/integration/conftest.pyindex cc95737b2..316811e74 100644--- a/core/tests/integration/conftest.py+++ b/core/tests/integration/conftest.py@@ -4,7 +4,7 @@ Unlike the unit suite (which fakes the transport), these fixtures boot a realdatabase and wire up the subset of `switch_core.main:run()` the feature undertest needs, in-process. Messaging, membership and provisioning all run againstthat database, so a test drives the genuine path RoomService → provisioning →-AgentClient receive loop → EventBuffer.+AgentConsumer receive loop → EventBuffer.The container mirrors the `postgres` service in`deploy/local/docker-compose.yml` (see constants below — keep in sync). It gets@@ -26,6 +26,7 @@ import subprocessimport uuidfrom collections.abc import AsyncIterator, Iteratorfrom dataclasses import dataclass+from unittest.mock import MagicMockimport asyncpgimport pytest@@ -37,17 +38,17 @@ from testcontainers.postgres import PostgresContainer# Importing models registers every table on Base.metadata for create_all.import switch_core.db.models # noqa: F401from switch_core.bridges.agent.api_key_cache import ApiKeyCache-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.event_buffer import EventBuffer-from switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.agent.protocol.types import (IntegrationProfile,RegistrationResult,TaskProtocolConfig,)from switch_core.bridges.resource.service import ResourceService-from switch_core.clients.agent_client import AgentClient-from switch_core.clients.client_base import ClientBase+from switch_core.clients.actor import Actor, AgentActor, HumanActor+from switch_core.clients.agent_consumer import AgentConsumerfrom switch_core.clients.client_factory import ClientFactoryfrom switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.config import SwitchConfig@@ -218,7 +219,7 @@ def _build_config(db_user=user or pg.username,db_password=password or pg.password,db_name=db_name,- matrix_server_name=SERVER_NAME,+ id_server_name=SERVER_NAME,agent_registration_token=REGISTRATION_TOKEN,jwt_secret_key=JWT_SECRET,gateway_admin_email=GATEWAY_ADMIN_EMAIL,@@ -248,7 +249,7 @@ class Harness:def __init__(self,*,- protocol: ProtocolService,+ protocol: AgentCore,room_service: RoomService,client_lifecycle: ClientLifecycleService,room_store: RoomStore,@@ -311,7 +312,7 @@ class Harness:client = await self._await_client(agent_id, timeout)await client.wait_ready()- async def _await_client(self, agent_id: str, timeout: float) -> AgentClient:+ async def _await_client(self, agent_id: str, timeout: float) -> AgentConsumer:deadline = asyncio.get_event_loop().time() + timeoutwhile asyncio.get_event_loop().time() < deadline:client = self.client_lifecycle.get_by_agent_id(agent_id)@@ -320,17 +321,17 @@ class Harness:await asyncio.sleep(0.1)raise AssertionError(f"No running client for agent {agent_id} after {timeout}s")- def client_for(self, agent_id: str) -> AgentClient:+ def client_for(self, agent_id: str) -> AgentConsumer:client = self.client_lifecycle.get_by_agent_id(agent_id)if client is None:raise AssertionError(f"No running client for agent {agent_id}")return client # type: ignore[return-value]- async def matrix_room_id(self, room_id: str) -> str:+ async def transport_room_id(self, room_id: str) -> str:async with self.session_factory() as session: # type: ignore[operator]room = await self.room_store.get(session, room_id)assert room is not None- return room.matrix_room_id+ return room.transport_room_idasync def _admin_dsn(stack: StackInfo) -> str:@@ -525,7 +526,7 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:# Per-test in-memory wiring: a fresh EventBuffer / client registry so queued# events and client registrations never leak across tests.event_buffer = EventBuffer()- connections = ConnectionRegistry()+ connections = AgentConnectionRegistry()collab_lifecycle = _NoBridges()# The transport's wake-up path: rows are announced over LISTEN/NOTIFY, so@@ -566,7 +567,8 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:)client_factory.register("agent",- AgentClient,+ AgentActor,+ AgentConsumer,event_buffer=event_buffer,agent_store=session_env.agent_store,room_store=session_env.room_store,@@ -579,11 +581,11 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:connections=connections,frontend_base_url=config.frontend_base_url,)- client_factory.register("user", ClientBase)- client_factory.register("bridge", ClientBase)+ client_factory.register("user", HumanActor)+ client_factory.register("bridge", Actor)client_lifecycle = ClientLifecycleService(- matrix_admin=provisioning,+ provisioning=provisioning,client_store=session_env.client_store,tenant_store=TenantStore(),client_factory=client_factory,@@ -592,7 +594,7 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:)room_service = RoomService(- matrix_admin=provisioning,+ provisioning=provisioning,room_store=session_env.room_store,agent_store=session_env.agent_store,client_lifecycle=client_lifecycle,@@ -602,7 +604,7 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:session_factory=session_factory,)- protocol = ProtocolService(+ protocol = AgentCore(agent_store=session_env.agent_store,agent_session_store=session_env.agent_session_store,room_store=session_env.room_store,@@ -621,6 +623,8 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:bridge_store=session_env.bridge_store,session_factory=session_factory,config=config,+ # Required since #543; no integration test answers an approval.+ approval_outcomes=MagicMock(),connections=connections,)diff --git a/core/tests/integration/test_agent_greeting_e2e.py b/core/tests/integration/test_agent_greeting_e2e.pyindex 8e6d35a46..cc03d99fa 100644--- a/core/tests/integration/test_agent_greeting_e2e.py+++ b/core/tests/integration/test_agent_greeting_e2e.py@@ -1,7 +1,7 @@"""End-to-end test for the agent self-join greeting over the real transport.Drives the genuine path: RoomService creates a room and invites the agent →-the agent's AgentClient sees the invite → auto-joins → on_self_join posts the+the agent's AgentConsumer sees the invite → auto-joins → on_self_join posts thegreeting. The assertion reads the room timeline back out of the messages table,so nothing is inferred from in-process state."""@@ -20,14 +20,14 @@ pytestmark = [pytest.mark.integration, pytest.mark.asyncio(loop_scope="session")async def _wait_joined(- client: object, matrix_room_id: str, timeout: float = 30+ client: object, transport_room_id: str, timeout: float = 30) -> None:deadline = asyncio.get_event_loop().time() + timeoutwhile asyncio.get_event_loop().time() < deadline:- if matrix_room_id in client.room_join_times: # type: ignore[attr-defined]+ if transport_room_id in client.room_join_times: # type: ignore[attr-defined]returnawait asyncio.sleep(0.25)- raise AssertionError(f"client never joined {matrix_room_id} within {timeout}s")+ raise AssertionError(f"client never joined {transport_room_id} within {timeout}s")async def _timeline_messages(@@ -72,14 +72,14 @@ async def test_agent_posts_greeting_on_join(agent_ids=[agent.agent_id],))- matrix_room_id = result.room.matrix_room_id- await _wait_joined(client, matrix_room_id)+ transport_room_id = result.room.transport_room_id+ await _wait_joined(client, transport_room_id)greeting = await _wait_for_message_from(harness,session_env,result.room.id,- client.matrix_user_id.split(":")[0].lstrip("@"),+ client.transport_user_id.split(":")[0].lstrip("@"),)assert greeting is not None, (@@ -104,8 +104,8 @@ async def test_no_greeting_when_the_bridge_has_them_disabled(agent_ids=[host.agent_id],))- matrix_room_id = result.room.matrix_room_id- await _wait_joined(harness.client_for(host.agent_id), matrix_room_id)+ transport_room_id = result.room.transport_room_id+ await _wait_joined(harness.client_for(host.agent_id), transport_room_id)# Point the room at a connection with greetings turned off. Done after# creation because the harness runs no collaboration bridge — the join path@@ -129,13 +129,13 @@ async def test_no_greeting_when_the_bridge_has_them_disabled(await harness.room_service.add_agents_to_room(result.room.id, agent_ids=[joiner.agent_id])- await _wait_joined(joiner_client, matrix_room_id)+ await _wait_joined(joiner_client, transport_room_id)greeting = await _wait_for_message_from(harness,session_env,result.room.id,- joiner_client.matrix_user_id.split(":")[0].lstrip("@"),+ joiner_client.transport_user_id.split(":")[0].lstrip("@"),timeout=8,)diff --git a/core/tests/integration/test_harness_smoke.py b/core/tests/integration/test_harness_smoke.pyindex 6fa094313..3e6b17966 100644--- a/core/tests/integration/test_harness_smoke.py+++ b/core/tests/integration/test_harness_smoke.py@@ -22,15 +22,15 @@ pytestmark = [pytest.mark.integration, pytest.mark.asyncio(loop_scope="session")async def _wait_joined(- client: object, matrix_room_id: str, timeout: float = 30+ client: object, transport_room_id: str, timeout: float = 30) -> None:"""Block until the agent's own client has joined the room."""deadline = asyncio.get_event_loop().time() + timeoutwhile asyncio.get_event_loop().time() < deadline:- if matrix_room_id in client.room_join_times: # type: ignore[attr-defined]+ if transport_room_id in client.room_join_times: # type: ignore[attr-defined]returnawait asyncio.sleep(0.25)- raise AssertionError(f"client never joined {matrix_room_id} within {timeout}s")+ raise AssertionError(f"client never joined {transport_room_id} within {timeout}s")async def test_harness_boots_and_agents_join_room(harness: Harness) -> None:@@ -50,10 +50,10 @@ async def test_harness_boots_and_agents_join_room(harness: Harness) -> None:agent_ids=[alice.agent_id, bob.agent_id],))- matrix_room_id = result.room.matrix_room_id+ transport_room_id = result.room.transport_room_id- await _wait_joined(alice_client, matrix_room_id)- await _wait_joined(bob_client, matrix_room_id)+ await _wait_joined(alice_client, transport_room_id)+ await _wait_joined(bob_client, transport_room_id)- assert matrix_room_id in alice_client.room_join_times- assert matrix_room_id in bob_client.room_join_times+ assert transport_room_id in alice_client.room_join_times+ assert transport_room_id in bob_client.room_join_timesdiff --git a/core/tests/integration/test_registration_bootstrap_scope.py b/core/tests/integration/test_registration_bootstrap_scope.pyindex 28e584749..77a602303 100644--- a/core/tests/integration/test_registration_bootstrap_scope.py+++ b/core/tests/integration/test_registration_bootstrap_scope.py@@ -2,7 +2,7 @@Before this fix, any holder of that one shared secret registered agents ownedby the seeded admin user. Since room/resource authorization treats "owned by-an admin" as "acts with admin authority" (`ProtocolService._resolve_acting_identity`),+an admin" as "acts with admin authority" (`AgentCore._resolve_acting_identity`),that made the token a privilege-escalation vector: a colleague given thedeployment secret to bring up their own agent got an agent that could bypass`read_visibility`/`write_visibility` on every room and resource in thediff --git a/core/tests/integration/test_removal_stops_delivery_e2e.py b/core/tests/integration/test_removal_stops_delivery_e2e.pyindex 14180b706..73287d2dc 100644--- a/core/tests/integration/test_removal_stops_delivery_e2e.py+++ b/core/tests/integration/test_removal_stops_delivery_e2e.py@@ -7,7 +7,7 @@ over the invite bus → the transport drops the subscription and tells its clienit.The unit tests cover each of those links. What only this can show is that they-are joined: severing the one line in `ClientBase.setup` that wires the removal+are joined: severing the one line in `Actor.setup` that wires the removalhandler to the transport left the whole unit suite green while a kick reachednothing.@@ -31,14 +31,14 @@ pytestmark = [pytest.mark.integration, pytest.mark.asyncio(loop_scope="session")async def _wait_joined(- client: object, matrix_room_id: str, timeout: float = 30+ client: object, transport_room_id: str, timeout: float = 30) -> None:deadline = asyncio.get_event_loop().time() + timeoutwhile asyncio.get_event_loop().time() < deadline:- if matrix_room_id in client.room_join_times: # type: ignore[attr-defined]+ if transport_room_id in client.room_join_times: # type: ignore[attr-defined]returnawait asyncio.sleep(0.25)- raise AssertionError(f"client never joined {matrix_room_id} within {timeout}s")+ raise AssertionError(f"client never joined {transport_room_id} within {timeout}s")async def _wait_buffered(@@ -87,14 +87,14 @@ async def test_removal_stops_every_reader_serving_the_room(harness: Harness) ->))rooms[label] = result.room- await _wait_joined(watcher_client, result.room.matrix_room_id)+ await _wait_joined(watcher_client, result.room.transport_room_id)talker_client = harness.client_for(talker.agent_id)bodies = {}for label, room in rooms.items():bodies[label] = f"@e2e-removed-watcher please look at the {label} room"await talker_client.send_message(- room.matrix_room_id, bodies[label], metered=True+ room.transport_room_id, bodies[label], metered=True)await _wait_buffered(harness, watcher.agent_id, room.id, bodies[label])@@ -160,12 +160,12 @@ async def test_a_room_the_agent_is_still_in_is_untouched(harness: Harness) -> Noagent_ids=[watcher.agent_id, talker.agent_id],))- await _wait_joined(watcher_client, kept.room.matrix_room_id)- await _wait_joined(watcher_client, left.room.matrix_room_id)+ await _wait_joined(watcher_client, kept.room.transport_room_id)+ await _wait_joined(watcher_client, left.room.transport_room_id)body = "@e2e-still-in-watcher this one still applies"await harness.client_for(talker.agent_id).send_message(- kept.room.matrix_room_id,+ kept.room.transport_room_id,body,metered=True,)diff --git a/core/tests/integration/test_room_join_e2e.py b/core/tests/integration/test_room_join_e2e.pyindex ba03b487d..a645b85fe 100644--- a/core/tests/integration/test_room_join_e2e.py+++ b/core/tests/integration/test_room_join_e2e.py@@ -1,7 +1,7 @@"""End-to-end test for the room_join event over the real transport.Drives the genuine path: RoomService adds an agent to a room → the invite reaches-the joiner → the watcher's AgentClient receive loop sees the arrival →+the joiner → the watcher's AgentConsumer receive loop sees the arrival →on_member_event enqueues a `room_join` AgentEvent → it is read off the eventbuffer. No mocks, no HTTP layer."""@@ -22,15 +22,15 @@ pytestmark = [pytest.mark.integration, pytest.mark.asyncio(loop_scope="session")async def _wait_joined(- client: object, matrix_room_id: str, timeout: float = 30+ client: object, transport_room_id: str, timeout: float = 30) -> None:"""Block until the agent's own client has joined the room."""deadline = asyncio.get_event_loop().time() + timeoutwhile asyncio.get_event_loop().time() < deadline:- if matrix_room_id in client.room_join_times: # type: ignore[attr-defined]+ if transport_room_id in client.room_join_times: # type: ignore[attr-defined]returnawait asyncio.sleep(0.25)- raise AssertionError(f"client never joined {matrix_room_id} within {timeout}s")+ raise AssertionError(f"client never joined {transport_room_id} within {timeout}s")async def _drain_room_join(@@ -59,7 +59,7 @@ async def test_join_emits_room_join_event(harness: Harness) -> None:await harness.client_for(joiner.agent_id).wait_ready()# Room with only the watcher, so the joiner's join is strictly later than the- # watcher's own join-time (the AgentClient filters out events predating it).+ # watcher's own join-time (the AgentConsumer filters out events predating it).result = await harness.room_service.create_room(RoomCreateConfig(name="e2e-room-join",@@ -70,9 +70,9 @@ async def test_join_emits_room_join_event(harness: Harness) -> None:))room_id = result.room.id- matrix_room_id = result.room.matrix_room_id+ transport_room_id = result.room.transport_room_id- await _wait_joined(watcher_client, matrix_room_id)+ await _wait_joined(watcher_client, transport_room_id)# Trigger the observed join.await harness.room_service.add_agents_to_room(room_id, agent_ids=[joiner.agent_id])@@ -100,7 +100,7 @@ async def test_self_join_does_not_emit_room_join(harness: Harness) -> None:agent_ids=[watcher.agent_id],))- await _wait_joined(watcher_client, result.room.matrix_room_id)+ await _wait_joined(watcher_client, result.room.transport_room_id)# Give the receive loop time to deliver any (erroneous) self-join event.event = await _drain_room_join(harness, watcher.agent_id, result.room.id, timeout=8)diff --git a/core/tests/switch_core/bridges/agent/api/test_beat_cursor_clamp.py b/core/tests/switch_core/bridges/agent/api/test_beat_cursor_clamp.pyindex 4c77df44a..6d9abba79 100644--- a/core/tests/switch_core/bridges/agent/api/test_beat_cursor_clamp.py+++ b/core/tests/switch_core/bridges/agent/api/test_beat_cursor_clamp.py@@ -18,10 +18,10 @@ from typing import Anyfrom switch_core.bridges.agent.api.handlers import connection_beatfrom switch_core.bridges.agent.api.schemas import ConnectionBeatRequest-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (PROTOCOL_VERSION,+ AgentConnectionRegistry,ClientDeclaration,- ConnectionRegistry,)from switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.bridges.agent.protocol.types import AgentEvent, MessagePayload@@ -34,7 +34,7 @@ ROOM_ID = "room-1"class _Protocol:def __init__(self) -> None:self.event_buffer = EventBuffer()- self.connections = ConnectionRegistry()+ self.connections = AgentConnectionRegistry()def _message() -> AgentEvent:diff --git a/core/tests/switch_core/bridges/agent/api/test_beat_refusal_codes.py b/core/tests/switch_core/bridges/agent/api/test_beat_refusal_codes.pyindex 6530d5855..b97196a17 100644--- a/core/tests/switch_core/bridges/agent/api/test_beat_refusal_codes.py+++ b/core/tests/switch_core/bridges/agent/api/test_beat_refusal_codes.py@@ -19,10 +19,10 @@ from fastapi import HTTPExceptionfrom switch_core.bridges.agent.api.handlers import connection_beatfrom switch_core.bridges.agent.api.schemas import ConnectionBeatRequest-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (PROTOCOL_VERSION,+ AgentConnectionRegistry,ClientDeclaration,- ConnectionRegistry,)from switch_core.bridges.agent.protocol.event_buffer import EventBuffer@@ -33,7 +33,7 @@ CONN_ID = "conn-1"class _Protocol:def __init__(self) -> None:self.event_buffer = EventBuffer()- self.connections = ConnectionRegistry()+ self.connections = AgentConnectionRegistry()def _open(protocol: _Protocol, *, speaks: int | None = PROTOCOL_VERSION) -> Any:diff --git a/core/tests/switch_core/bridges/agent/api/test_connection_placements.py b/core/tests/switch_core/bridges/agent/api/test_connection_placements.pyindex 409c4fb35..f2cb9d0ed 100644--- a/core/tests/switch_core/bridges/agent/api/test_connection_placements.py+++ b/core/tests/switch_core/bridges/agent/api/test_connection_placements.py@@ -9,11 +9,11 @@ from fastapi import HTTPExceptionfrom switch_core.bridges.agent.api.handlers import connection_placementsfrom switch_core.bridges.agent.api.schemas import ConnectionPlacementsRequest-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (ROOM_RELEASED_PROTOCOL_REVISION,+ AgentConnection,+ AgentConnectionRegistry,ClientDeclaration,- Connection,- ConnectionRegistry,)from switch_core.bridges.agent.protocol.event_buffer import EventBuffer@@ -26,7 +26,7 @@ FOREIGN_ROOM = "room-foreign"class _Protocol:def __init__(self) -> None:- self.connections = ConnectionRegistry()+ self.connections = AgentConnectionRegistry()self.event_buffer = EventBuffer()async def require_room_member(self, agent_id: str, room_id: str) -> None:@@ -41,7 +41,7 @@ class _Agent:def _open(protocol: _Protocol, connection_id: str, agent_id: str = AGENT_ID-) -> Connection:+) -> AgentConnection:return protocol.connections.open(agent_id=agent_id,connection_id=connection_id,@@ -56,7 +56,7 @@ def _open(async def _place(protocol: _Protocol,- conn: Connection,+ conn: AgentConnection,placements: dict[str, str],*,path_agent: str = AGENT_ID,diff --git a/core/tests/switch_core/bridges/agent/api/test_connection_subscribe_rooms.py b/core/tests/switch_core/bridges/agent/api/test_connection_subscribe_rooms.pyindex 6b784efbd..ecc2e3e6e 100644--- a/core/tests/switch_core/bridges/agent/api/test_connection_subscribe_rooms.py+++ b/core/tests/switch_core/bridges/agent/api/test_connection_subscribe_rooms.py@@ -20,10 +20,10 @@ import pytestfrom switch_core.bridges.agent.api.handlers import connection_subscribefrom switch_core.bridges.agent.api.schemas import ConnectionSubscribeRequest-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (PROTOCOL_VERSION,+ AgentConnectionRegistry,ClientDeclaration,- ConnectionRegistry,)from switch_core.bridges.agent.protocol.event_buffer import EventBuffer, Readerfrom switch_core.bridges.agent.protocol.types import AgentEvent, MessagePayload@@ -36,7 +36,7 @@ ROOM_B = "!room-b"class _Protocol:def __init__(self) -> None:- self.connections = ConnectionRegistry()+ self.connections = AgentConnectionRegistry()self.event_buffer = EventBuffer()async def require_room_member(self, agent_id: str, room_id: str) -> None:diff --git a/core/tests/switch_core/bridges/agent/api/test_events_endpoint_dispatch.py b/core/tests/switch_core/bridges/agent/api/test_events_endpoint_dispatch.pyindex 8f05096cd..301d93b44 100644--- a/core/tests/switch_core/bridges/agent/api/test_events_endpoint_dispatch.py+++ b/core/tests/switch_core/bridges/agent/api/test_events_endpoint_dispatch.py@@ -18,12 +18,12 @@ from starlette.responses import StreamingResponsefrom switch_core.bridges.agent.api import session_reporterfrom switch_core.bridges.agent.api.handlers import _resolve_start_cursor, poll_eventsfrom switch_core.bridges.agent.api.session_reporter import SessionReporter-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (HEARTBEAT_LAPSED,PROTOCOL_ACCEPTS,PROTOCOL_VERSION,+ AgentConnectionRegistry,ClientDeclaration,- ConnectionRegistry,)from switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.telemetry.service import TelemetryService@@ -35,7 +35,7 @@ AGENT_ID = "agent-1"class _Protocol:def __init__(self) -> None:self.event_buffer = EventBuffer()- self.connections = ConnectionRegistry()+ self.connections = AgentConnectionRegistry()# No approval outcomes: these tests are about opening the stream.self.approval_outcomes = None# Opening and closing a stream reports a session; a reporter with no@@ -113,6 +113,7 @@ async def test_with_the_sse_accept_header_it_opens_a_connection() -> None:assert resp.media_type == "text/event-stream"# Buffering proxies would defeat the point of a push channel.assert resp.headers["x-accel-buffering"] == "no"+ assert resp.headers["connection"] == "keep-alive"assert not protocol.polledconn = protocol.connections.get("c1")diff --git a/core/tests/switch_core/bridges/agent/api/test_reattach_refusal.py b/core/tests/switch_core/bridges/agent/api/test_reattach_refusal.pyindex f377e9daa..4b149ed03 100644--- a/core/tests/switch_core/bridges/agent/api/test_reattach_refusal.py+++ b/core/tests/switch_core/bridges/agent/api/test_reattach_refusal.py@@ -19,10 +19,10 @@ from fastapi import HTTPExceptionfrom switch_core.bridges.agent.api.handlers import poll_eventsfrom switch_core.bridges.agent.api.session_reporter import SessionReporter-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (PROTOCOL_VERSION,+ AgentConnectionRegistry,ClientDeclaration,- ConnectionRegistry,)from switch_core.bridges.agent.protocol.event_buffer import EventBuffer@@ -33,7 +33,7 @@ CONN_ID = "conn-1"class _Protocol:def __init__(self) -> None:self.event_buffer = EventBuffer()- self.connections = ConnectionRegistry()+ self.connections = AgentConnectionRegistry()# No approval outcomes: these tests are about opening the stream.self.approval_outcomes = None# Every stream a client is handed goes past the session reporter; onediff --git a/core/tests/switch_core/bridges/agent/api/test_room_control_fence.py b/core/tests/switch_core/bridges/agent/api/test_room_control_fence.pyindex e5d7e9969..0c2dd4e91 100644--- a/core/tests/switch_core/bridges/agent/api/test_room_control_fence.py+++ b/core/tests/switch_core/bridges/agent/api/test_room_control_fence.py@@ -24,10 +24,10 @@ from switch_core.bridges.agent.api.handlers import (connection_unsubscribe,)from switch_core.bridges.agent.api.schemas import ConnectionSubscribeRequest-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (PROTOCOL_VERSION,+ AgentConnectionRegistry,ClientDeclaration,- ConnectionRegistry,)from switch_core.bridges.agent.protocol.event_buffer import EventBuffer@@ -38,10 +38,10 @@ ROOM_B = "!room-b"class _Protocol:- """Enough of ProtocolService for the two room-control handlers."""+ """Enough of AgentCore for the two room-control handlers."""def __init__(self) -> None:- self.connections = ConnectionRegistry()+ self.connections = AgentConnectionRegistry()self.event_buffer = EventBuffer()self.membership_checks: list[str] = []diff --git a/core/tests/switch_core/bridges/agent/api/test_session_selector.py b/core/tests/switch_core/bridges/agent/api/test_session_selector.pyindex c733cf7fa..1c46647ae 100644--- a/core/tests/switch_core/bridges/agent/api/test_session_selector.py+++ b/core/tests/switch_core/bridges/agent/api/test_session_selector.py@@ -7,14 +7,16 @@ memory, which room each session last connected to.from __future__ import annotations+import typing+import pytestfrom fastapi import HTTPException-from switch_core.bridges.agent.api.operations import resolve_caller-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.api.operations import post_operation, resolve_caller+from switch_core.bridges.agent.protocol.agent_connections import (HEARTBEAT_LAPSED,+ AgentConnectionRegistry,ClientDeclaration,- ConnectionRegistry,)AGENT = "agent-demo"@@ -22,12 +24,12 @@ CONNECTION = "connection-demo"class _Protocol:- def __init__(self, connections: ConnectionRegistry) -> None:+ def __init__(self, connections: AgentConnectionRegistry) -> None:self.connections = connectionsdef _protocol() -> _Protocol:- connections = ConnectionRegistry()+ connections = AgentConnectionRegistry()connections.open(agent_id=AGENT,connection_id=CONNECTION,@@ -89,6 +91,12 @@ async def test_a_session_selector_needs_its_connection() -> None:with pytest.raises(HTTPException) as refused:await _resolve(_protocol(), session_id="first")assert refused.value.status_code == 400+ # The refusal tells the caller what to send, so it has to name the header+ # the endpoint actually reads.+ read = typing.get_type_hints(post_operation, include_extras=True)+ alias = typing.get_args(read["connection_id"])[1].alias+ assert alias.lower() == "x-switch-connection-id"+ assert alias.lower() in refused.value.detail.lower()@pytest.mark.asyncio@@ -105,7 +113,7 @@ async def test_a_dead_or_foreign_connection_is_refused() -> None:def test_one_session_per_room_and_one_room_per_session() -> None:- connections = ConnectionRegistry()+ connections = AgentConnectionRegistry()assert connections.place_session(AGENT, "first", "room-a", CONNECTION) == (set(),None,diff --git a/core/tests/switch_core/bridges/agent/operations/conftest.py b/core/tests/switch_core/bridges/agent/operations/conftest.pyindex 140d62cea..956c663ba 100644--- a/core/tests/switch_core/bridges/agent/operations/conftest.py+++ b/core/tests/switch_core/bridges/agent/operations/conftest.py@@ -15,9 +15,9 @@ from sqlalchemy import insertfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.agent.operations import context as op_context-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.resource.service import ResourceService-from switch_core.clients.admin_client import AdminClient+from switch_core.clients.actor import SystemActorfrom switch_core.db.models import (Agent,ApiKey,@@ -65,7 +65,7 @@ class FakeRoomService:agent_ids = [name_to_id[n] for n in config.agent_names]room = Room(- matrix_room_id=f"!{uuid.uuid4().hex}:test.local",+ transport_room_id=f"!{uuid.uuid4().hex}:test.local",name=config.name,description=config.description,channel_type=config.channel_type or "channel_public",@@ -103,7 +103,7 @@ async def _make_agent(type="agent",)client = Client(- matrix_user_id=f"@{name}:test.local",+ transport_user_id=f"@{name}:test.local",display_name=name,type="agent",)@@ -124,7 +124,7 @@ async def _make_agent(return agent-class RecordingAdminClient(AdminClient):+class RecordingSystemActor(SystemActor):"""Records the platform messages a kickoff sends; has no transport."""def __init__(self) -> None: # noqa: D107 - test double, no super().__init__@@ -151,7 +151,7 @@ class RecordingAdminClient(AdminClient):class FakeLifecycle:- def __init__(self, admin: AdminClient) -> None:+ def __init__(self, admin: SystemActor) -> None:self.admin = admindef get_by_type(self, client_type: str, tenant_id: str) -> list[Any]:@@ -173,7 +173,7 @@ async def env(session_factory: async_sessionmaker[AsyncSession]):room_link_store=RoomLinkStore(),session_factory=session_factory,)- admin = RecordingAdminClient()+ admin = RecordingSystemActor()fake_protocol = SimpleNamespace(client_lifecycle=FakeLifecycle(admin),session_factory=session_factory,@@ -189,8 +189,8 @@ async def env(session_factory: async_sessionmaker[AsyncSession]):connections={},)# Runs are the real service's; only its collaborators are fakes.- fake_protocol.run_service = partial(ProtocolService.run_service, fake_protocol)- # The same wiring `ProtocolService.room_yaml_service` does, over the fakes.+ fake_protocol.run_service = partial(AgentCore.run_service, fake_protocol)+ # The same wiring `AgentCore.room_yaml_service` does, over the fakes.fake_protocol.room_yaml_service = lambda: RoomYamlService(room_service=fake_protocol.room_service,resource_service=fake_protocol.resource_service,diff --git a/core/tests/switch_core/bridges/agent/operations/test_binding_row_is_legacy_only.py b/core/tests/switch_core/bridges/agent/operations/test_binding_row_is_legacy_only.pyindex c6d6732ef..7316ff4da 100644--- a/core/tests/switch_core/bridges/agent/operations/test_binding_row_is_legacy_only.py+++ b/core/tests/switch_core/bridges/agent/operations/test_binding_row_is_legacy_only.py@@ -20,11 +20,11 @@ from typing import Anyfrom switch_core.bridges.agent.operations.definitions import (bind_room_for_connectionless_caller,)-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (PROTOCOL_VERSION,+ AgentConnectionRegistry,ClientDeclaration,Closure,- ConnectionRegistry,)AGENT = "agent-1"@@ -42,7 +42,7 @@ class _RecordingSessionStore:self.writes.append(kwargs)-def _open(registry: ConnectionRegistry, connection_id: str) -> Any:+def _open(registry: AgentConnectionRegistry, connection_id: str) -> Any:return registry.open(agent_id=AGENT,connection_id=connection_id,@@ -65,7 +65,7 @@ async def _write_binding_row_if_needed(protocol: Any, key: str) -> bool:)-def _protocol(registry: ConnectionRegistry, store: _RecordingSessionStore) -> Any:+def _protocol(registry: AgentConnectionRegistry, store: _RecordingSessionStore) -> Any:class _Db:async def __aenter__(self) -> Any:return self@@ -84,7 +84,7 @@ def _protocol(registry: ConnectionRegistry, store: _RecordingSessionStore) -> Anasync def test_no_row_is_written_for_a_connection_backed_caller() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()_open(registry, CONN)store = _RecordingSessionStore()@@ -96,7 +96,7 @@ async def test_no_row_is_written_for_a_connection_backed_caller() -> None:async def test_the_row_is_still_written_for_an_mcp_transport_session() -> None:# No connection was ever opened for this key, so the row is the only thing# that can resolve the caller's room.- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()store = _RecordingSessionStore()await _write_binding_row_if_needed(_protocol(registry, store), "mcp-session-1")@@ -109,7 +109,7 @@ async def test_the_row_is_still_written_for_an_mcp_transport_session() -> None:async def test_a_closed_connection_falls_back_to_writing_the_row() -> None:# A runtime reusing a key whose connection has expired is indistinguishable# from an MCP transport session, and resolves the same way.- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()_open(registry, CONN)registry.close(CONN, Closure(code="closed", message="gone", room_id=None))store = _RecordingSessionStore()diff --git a/core/tests/switch_core/bridges/agent/operations/test_connect_claims_room.py b/core/tests/switch_core/bridges/agent/operations/test_connect_claims_room.pyindex a9b92c07f..9a1557210 100644--- a/core/tests/switch_core/bridges/agent/operations/test_connect_claims_room.py+++ b/core/tests/switch_core/bridges/agent/operations/test_connect_claims_room.py@@ -26,10 +26,10 @@ from typing import Anyfrom switch_core.bridges.agent.operations.definitions import (claim_room_on_caller_connection,)-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (PROTOCOL_VERSION,+ AgentConnectionRegistry,ClientDeclaration,- ConnectionRegistry,NoStreamAttachedError,)@@ -38,11 +38,11 @@ ROOM = "room-1"CONN = "conn-1"-def _protocol(registry: ConnectionRegistry) -> Any:+def _protocol(registry: AgentConnectionRegistry) -> Any:return SimpleNamespace(connections=registry)-def _open(registry: ConnectionRegistry, connection_id: str, agent_id: str = AGENT):+def _open(registry: AgentConnectionRegistry, connection_id: str, agent_id: str = AGENT):return registry.open(agent_id=agent_id,connection_id=connection_id,@@ -56,7 +56,7 @@ def _open(registry: ConnectionRegistry, connection_id: str, agent_id: str = AGENdef test_the_calling_connection_ends_up_holding_the_room() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()_open(registry, CONN)claim_room_on_caller_connection(_protocol(registry), AGENT, CONN, ROOM)@@ -72,7 +72,7 @@ def test_the_claim_wakes_the_stream_so_its_holder_is_told() -> None:Without it the supervisor stays blocked on its read and learns nothinguntil the next event happens along."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, CONN)conn.wake.clear()@@ -90,7 +90,7 @@ def test_a_dead_sibling_does_not_lock_the_agent_out() -> None:"""import time as _time- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()dead = _open(registry, "previous-life")registry.claim_room(dead, ROOM)dead.last_beat = _time.monotonic() - 3600@@ -115,7 +115,7 @@ def test_a_live_sibling_is_evicted_and_the_eviction_is_reported() -> None:indistinguishable from the duplicate-session bug it resolves: a sessionstops receiving a room and nothing says why."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()incumbent = _open(registry, "first-session")registry.claim_room(incumbent, ROOM)_open(registry, CONN)@@ -135,7 +135,7 @@ def test_the_evicted_session_is_woken_so_it_learns_it_lost_the_room() -> None:Without the wake it stays blocked on its read, still believing it holds theroom, and Switch Console keeps showing it under that room."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()incumbent = _open(registry, "first-session")registry.claim_room(incumbent, ROOM)incumbent.wake.clear()@@ -148,7 +148,7 @@ def test_the_evicted_session_is_woken_so_it_learns_it_lost_the_room() -> None:def test_taking_an_unheld_room_reports_no_eviction() -> None:"""The warning must not fire on the ordinary case of an empty room."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()_open(registry, CONN)evicted = claim_room_on_caller_connection(_protocol(registry), AGENT, CONN, ROOM)@@ -164,7 +164,7 @@ def test_a_dead_predecessor_is_not_reported_as_an_eviction() -> None:"""import time as _time- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()dead = _open(registry, "previous-life")registry.claim_room(dead, ROOM)dead.last_beat = _time.monotonic() - 3600@@ -181,7 +181,7 @@ def test_the_same_connection_reconnecting_is_not_a_duplicate() -> None:A session keeps its connection id across reconnects, so it meets its ownclaim. That must stay idempotent or every restart would lock itself out."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, CONN)registry.claim_room(conn, ROOM)@@ -195,7 +195,7 @@ def test_the_same_connection_reconnecting_is_not_a_duplicate() -> None:def test_another_agent_holding_the_room_is_not_a_conflict() -> None:"""The rule is one session per agent per room, not one agent per room."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()theirs = _open(registry, "their-session", agent_id="agent-2")registry.claim_room(theirs, ROOM)_open(registry, CONN)@@ -210,7 +210,7 @@ def test_another_agent_holding_the_room_is_not_a_conflict() -> None:def test_an_unknown_connection_is_not_an_error() -> None:"""An MCP transport session has no connection; the binding row covers it."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()claim_room_on_caller_connection(_protocol(registry), AGENT, "no-such", ROOM)@@ -219,7 +219,7 @@ def test_an_unknown_connection_is_not_an_error() -> None:def test_another_agents_connection_is_never_claimed_on() -> None:"""The key comes off the caller's own header, but never trust it blindly."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()_open(registry, CONN, agent_id="someone-else")claim_room_on_caller_connection(_protocol(registry), AGENT, CONN, ROOM)@@ -237,7 +237,7 @@ def test_a_fault_that_is_not_occupancy_is_logged_and_not_raised(caller may do. Any other connection fault leaves the room the caller's tohave, so failing the whole connect over it would be the harsher answer."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, CONN)def _explode(*_a: Any, **_kw: Any) -> None:diff --git a/core/tests/switch_core/bridges/agent/operations/test_connect_to_room_eviction.py b/core/tests/switch_core/bridges/agent/operations/test_connect_to_room_eviction.pyindex b2af7b183..6227d421d 100644--- a/core/tests/switch_core/bridges/agent/operations/test_connect_to_room_eviction.py+++ b/core/tests/switch_core/bridges/agent/operations/test_connect_to_room_eviction.py@@ -26,10 +26,10 @@ from switch_core.bridges.agent.operations.callctx import (set_call_context,)from switch_core.bridges.agent.operations.context import init_operations_protocol-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (PROTOCOL_VERSION,+ AgentConnectionRegistry,ClientDeclaration,- ConnectionRegistry,)from switch_core.bridges.agent.protocol.event_buffer import EventBuffer@@ -63,7 +63,7 @@ class _RecordingSessionStore:self.bindings.append((agent_id, room_id, transport_session_id))-def _protocol(registry: ConnectionRegistry, store: _RecordingSessionStore) -> Any:+def _protocol(registry: AgentConnectionRegistry, store: _RecordingSessionStore) -> Any:room = SimpleNamespace(id=ROOM, name="Room One", description="A room")agent = SimpleNamespace(id=AGENT, name="agent-one", integration_profile=_PROFILE)room_model = SimpleNamespace(id=ROOM, name="Room One", bridge_id=None)@@ -117,7 +117,7 @@ def _returning(value: Any):return _get-def _open(registry: ConnectionRegistry, connection_id: str):+def _open(registry: AgentConnectionRegistry, connection_id: str):return registry.open(agent_id=AGENT,connection_id=connection_id,@@ -132,7 +132,7 @@ def _open(registry: ConnectionRegistry, connection_id: str):@pytest.fixturedef harness(monkeypatch: pytest.MonkeyPatch):- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()store = _RecordingSessionStore()protocol = _protocol(registry, store)init_operations_protocol(protocol)diff --git a/core/tests/switch_core/bridges/agent/operations/test_read_context_room_argument.py b/core/tests/switch_core/bridges/agent/operations/test_read_context_room_argument.pyindex f83a5072e..b5c354846 100644--- a/core/tests/switch_core/bridges/agent/operations/test_read_context_room_argument.py+++ b/core/tests/switch_core/bridges/agent/operations/test_read_context_room_argument.py@@ -26,10 +26,10 @@ from switch_core.bridges.agent.operations.callctx import (set_call_context,)from switch_core.bridges.agent.operations.definitions import read_context-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (PROTOCOL_VERSION,+ AgentConnectionRegistry,ClientDeclaration,- ConnectionRegistry,)from switch_core.bridges.agent.protocol.event_buffer import (RESTARTED,@@ -47,7 +47,7 @@ OTHER_ROOM = "room-elsewhere"class _Protocol:"""Just enough protocol to answer a read: a registry and a recorder."""- def __init__(self, registry: ConnectionRegistry) -> None:+ def __init__(self, registry: AgentConnectionRegistry) -> None:self.connections = registryself.event_buffer = EventBuffer()self.calls: list[tuple[str, str]] = []@@ -67,7 +67,7 @@ class _Protocol:@pytest.fixturedef protocol(monkeypatch: pytest.MonkeyPatch) -> _Protocol:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()service = _Protocol(registry)monkeypatch.setattr(op_context, "_protocol", service)return servicediff --git a/core/tests/switch_core/bridges/agent/operations/test_role_holder_identity.py b/core/tests/switch_core/bridges/agent/operations/test_role_holder_identity.pyindex d3e35d3ff..b3b7456b7 100644--- a/core/tests/switch_core/bridges/agent/operations/test_role_holder_identity.py+++ b/core/tests/switch_core/bridges/agent/operations/test_role_holder_identity.py@@ -24,10 +24,10 @@ from switch_core.bridges.agent.operations.callctx import ()from switch_core.bridges.agent.operations.context import init_operations_protocolfrom switch_core.bridges.agent.operations.definitions import assume_role-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (PROTOCOL_VERSION,+ AgentConnectionRegistry,ClientDeclaration,- ConnectionRegistry,)AGENT = "agent-1"@@ -44,7 +44,7 @@ def holders():async def session_factory():yield SimpleNamespace()- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()connection = registry.open(agent_id=AGENT,connection_id=CONNECTION,diff --git a/core/tests/switch_core/bridges/agent/operations/test_session_room_resolution.py b/core/tests/switch_core/bridges/agent/operations/test_session_room_resolution.pyindex a610070ba..ae0f7f3d1 100644--- a/core/tests/switch_core/bridges/agent/operations/test_session_room_resolution.py+++ b/core/tests/switch_core/bridges/agent/operations/test_session_room_resolution.py@@ -31,10 +31,10 @@ from switch_core.bridges.agent.operations.context import (init_operations_protocol,require_connected_room,)-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (PROTOCOL_VERSION,+ AgentConnectionRegistry,ClientDeclaration,- ConnectionRegistry,)from switch_core.bridges.agent.protocol.event_buffer import EventBuffer, Readerfrom switch_core.bridges.agent.protocol.types import AgentEvent, MessagePayload@@ -75,7 +75,7 @@ def registry():async def session_factory():yield SimpleNamespace()- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()init_operations_protocol(SimpleNamespace(connections=registry,@@ -87,7 +87,7 @@ def registry():init_operations_protocol(None) # type: ignore[arg-type]-def _open(registry: ConnectionRegistry) -> Any:+def _open(registry: AgentConnectionRegistry) -> Any:return registry.open(agent_id=AGENT,connection_id=CONNECTION,@@ -376,7 +376,7 @@ async def test_evicting_another_connection_still_names_the_connection(assert "connection connection-old" in result["warning"]-def _protocol_for(registry: ConnectionRegistry, room_id: str) -> Any:+def _protocol_for(registry: AgentConnectionRegistry, room_id: str) -> Any:room = SimpleNamespace(id=room_id, name="Room C", description="A room")profile = {"connection_model": "session_addressable",diff --git a/core/tests/switch_core/bridges/agent/protocol/registration_harness.py b/core/tests/switch_core/bridges/agent/protocol/registration_harness.pyindex 77e1cbe77..3f87374bf 100644--- a/core/tests/switch_core/bridges/agent/protocol/registration_harness.py+++ b/core/tests/switch_core/bridges/agent/protocol/registration_harness.py@@ -1,4 +1,4 @@-"""A ProtocolService wired up far enough to run `register_agent`.+"""An AgentCore wired up far enough to run `register_agent`.Registration touches a Matrix client lifecycle and the collaboration bridges;tests about what registration *records* need neither, so the service is built@@ -12,7 +12,7 @@ from types import SimpleNamespacefrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.agent.api_key_cache import ApiKeyCache-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.types import (IntegrationProfile,TaskProtocolConfig,@@ -46,7 +46,7 @@ class FakeClientLifecycle:self.requested_display_names.append(display_name)async with self._session_factory() as session:client = Client(- matrix_user_id=f"@{display_name}:test",+ transport_user_id=f"@{display_name}:test",display_name=display_name,type=client_type,)@@ -65,8 +65,8 @@ class NoBridges:def make_service(session_factory: async_sessionmaker[AsyncSession],-) -> ProtocolService:- svc = object.__new__(ProtocolService)+) -> AgentCore:+ svc = object.__new__(AgentCore)svc.session_factory = session_factory # type: ignore[attr-defined]svc.agent_store = AgentStore() # type: ignore[attr-defined]svc.api_key_store = ApiKeyStore() # type: ignore[attr-defined]@@ -86,9 +86,7 @@ async def make_owner(session_factory: async_sessionmaker[AsyncSession]) -> str:return user.id-async def register(- svc: ProtocolService, name: str, owner_id: str, **kwargs: object-) -> str:+async def register(svc: AgentCore, name: str, owner_id: str, **kwargs: object) -> str:result = await svc.register_agent(name=name,description=f"{name} desc",diff --git a/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py b/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.pyindex 8ba2285d8..05835da81 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py@@ -3,9 +3,9 @@ from __future__ import annotationsimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.agent_detail import AgentOptionsNotEditable-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry-from switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.db.models import Agent, ApiKey, Client, Userfrom switch_core.db.stores.agent_session_store import AgentSessionStorefrom switch_core.db.stores.agent_store import AgentStore@@ -15,11 +15,11 @@ from switch_core.db.stores.user_store import UserStorefrom switch_core.gateway.known_agents import KNOWN_AGENTS-def _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolService:- svc = object.__new__(ProtocolService)+def _service(session_factory: async_sessionmaker[AsyncSession]) -> AgentCore:+ svc = object.__new__(AgentCore)# Presence unions the heartbeat rows with the live connections# (CHOO-1857); an empty registry means "rows only".- svc.connections = ConnectionRegistry()+ svc.connections = AgentConnectionRegistry()svc.session_factory = session_factory # type: ignore[attr-defined]svc.agent_store = AgentStore() # type: ignore[attr-defined]svc.room_store = RoomStore() # type: ignore[attr-defined]@@ -52,7 +52,7 @@ async def _make_agent(type="agent",)client = Client(- matrix_user_id=f"@{name}:test",+ transport_user_id=f"@{name}:test",display_name=name,type="agent",)diff --git a/core/tests/switch_core/bridges/agent/protocol/test_agent_name_validation.py b/core/tests/switch_core/bridges/agent/protocol/test_agent_name_validation.pyindex 48d559bda..bc44cbe1b 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_agent_name_validation.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_agent_name_validation.py@@ -11,7 +11,7 @@ from __future__ import annotationsimport pytest-from switch_core.bridges.agent.protocol.service import _VALID_NAME_RE+from switch_core.bridges.agent.protocol.agent_core import _VALID_NAME_RE@pytest.mark.parametrize(diff --git a/core/tests/switch_core/bridges/agent/protocol/test_agent_tenant_scoped_admin.py b/core/tests/switch_core/bridges/agent/protocol/test_agent_tenant_scoped_admin.pyindex 87b40b674..b1bfab1f3 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_agent_tenant_scoped_admin.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_agent_tenant_scoped_admin.py@@ -27,7 +27,7 @@ from types import SimpleNamespaceimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.types import (IntegrationProfile,TaskProtocolConfig,@@ -65,7 +65,7 @@ class _FakeClientLifecycle:async def create_client(self, *, client_type: str, display_name: str) -> Client:async with self._session_factory() as session:client = Client(- matrix_user_id=f"@{display_name}:test",+ transport_user_id=f"@{display_name}:test",display_name=display_name,type=client_type,)@@ -82,8 +82,8 @@ class _NoBridges:return []-def _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolService:- svc = object.__new__(ProtocolService)+def _service(session_factory: async_sessionmaker[AsyncSession]) -> AgentCore:+ svc = object.__new__(AgentCore)svc.session_factory = session_factory # type: ignore[attr-defined]svc.agent_store = AgentStore() # type: ignore[attr-defined]svc.api_key_store = ApiKeyStore() # type: ignore[attr-defined]@@ -124,7 +124,7 @@ async def _membership(await session.commit()-async def _register(svc: ProtocolService, name: str, owner_id: str) -> str:+async def _register(svc: AgentCore, name: str, owner_id: str) -> str:result = await svc.register_agent(name=name,description=f"{name} desc",@@ -141,7 +141,7 @@ async def _private_room(async with session_factory() as session:room = Room(tenant_id=tenant_id,- matrix_room_id=f"!{tenant_id}-private:test",+ transport_room_id=f"!{tenant_id}-private:test",name="private",description="",owner_id=owner_id,diff --git a/core/tests/switch_core/bridges/agent/protocol/test_bridge_identity_tenant_scope.py b/core/tests/switch_core/bridges/agent/protocol/test_bridge_identity_tenant_scope.pyindex 88ca945cf..ea596c54d 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_bridge_identity_tenant_scope.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_bridge_identity_tenant_scope.py@@ -132,7 +132,7 @@ class _StoppableClientLifecycle:async def create_client(self, *, client_type: str, display_name: str) -> Client:async with self._session_factory() as session:client = Client(- matrix_user_id=f"@{display_name}:test",+ transport_user_id=f"@{display_name}:test",display_name=display_name,type=client_type,)diff --git a/core/tests/switch_core/bridges/agent/protocol/test_connections.py b/core/tests/switch_core/bridges/agent/protocol/test_connections.pyindex 557fe0295..64f7da6c4 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_connections.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_connections.py@@ -1,4 +1,4 @@-"""Connection lifecycle, room slots and liveness (CHOO-1857)."""+"""AgentConnection lifecycle, room slots and liveness (CHOO-1857)."""from __future__ import annotations@@ -6,16 +6,16 @@ import timeimport pytest-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (FENCED_PROTOCOL_REVISION,HEARTBEAT_LAPSED,HEARTBEAT_TTL_SECONDS,MAX_CONNECTIONS_PER_AGENT,PROTOCOL_ACCEPTS,PROTOCOL_VERSION,+ AgentConnectionRegistry,ClientDeclaration,Closure,- ConnectionRegistry,NoStreamAttachedError,ProtocolVersionError,RoomOccupiedError,@@ -33,7 +33,7 @@ ROOM_B = "room-b"def _open(- registry: ConnectionRegistry,+ registry: AgentConnectionRegistry,connection_id: str,*,agent_id: str = AGENT,@@ -57,7 +57,7 @@ def _open(def test_open_is_idempotent_for_the_same_id() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()first = _open(registry, "c1")second = _open(registry, "c1")@@ -66,7 +66,7 @@ def test_open_is_idempotent_for_the_same_id() -> None:def test_reopening_bumps_the_generation_so_the_old_stream_can_stand_down() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "c1")generation = conn.stream_generation@@ -75,7 +75,7 @@ def test_reopening_bumps_the_generation_so_the_old_stream_can_stand_down() -> Nodef test_another_agent_cannot_attach_to_a_connection_id() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()_open(registry, "c1")with pytest.raises(UnknownConnectionError):@@ -83,7 +83,7 @@ def test_another_agent_cannot_attach_to_a_connection_id() -> None:def test_incompatible_protocol_is_refused() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()with pytest.raises(ProtocolVersionError):registry.open(agent_id=AGENT,@@ -98,7 +98,10 @@ def test_incompatible_protocol_is_refused() -> None:def _open_declaring(- registry: ConnectionRegistry, declaration: ClientDeclaration, *, cid: str = "c1"+ registry: AgentConnectionRegistry,+ declaration: ClientDeclaration,+ *,+ cid: str = "c1",):return registry.open(agent_id=AGENT,@@ -118,7 +121,7 @@ def test_a_client_that_declares_nothing_is_admitted_as_unknown() -> None:Refusing on silence would lock out every client built before there wasanything to say, and Part 1 of CHOO-1865 refuses nobody."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open_declaring(registry, ClientDeclaration())assert conn.declaration.declares_protocol is False@@ -133,7 +136,7 @@ def test_a_client_declaring_only_speaks_is_read_as_a_single_revision() -> None:def test_overlapping_ranges_are_admitted() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open_declaring(registry,ClientDeclaration(speaks=PROTOCOL_VERSION + 3, accepts=PROTOCOL_ACCEPTS),@@ -143,7 +146,7 @@ def test_overlapping_ranges_are_admitted() -> None:def test_a_client_whose_ceiling_is_below_the_server_floor_is_refused() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()with pytest.raises(ProtocolVersionError) as excinfo:_open_declaring(registry,@@ -157,7 +160,7 @@ def test_a_client_whose_ceiling_is_below_the_server_floor_is_refused() -> None:def test_a_client_whose_floor_is_above_the_server_ceiling_is_refused() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()with pytest.raises(ProtocolVersionError) as excinfo:_open_declaring(registry,@@ -176,7 +179,7 @@ def test_a_reattach_replaces_the_declaration() -> None:A client can be upgraded and reattach to the same connection id."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()_open_declaring(registry, ClientDeclaration(speaks=PROTOCOL_VERSION, version="1.0.0"))@@ -188,7 +191,7 @@ def test_a_reattach_replaces_the_declaration() -> None:def test_connection_cap_is_enforced_loudly() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()for i in range(MAX_CONNECTIONS_PER_AGENT):_open(registry, f"c{i}")@@ -200,7 +203,7 @@ def test_connection_cap_is_enforced_loudly() -> None:def test_losing_the_stream_does_not_kill_the_connection() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "c1")registry.claim_room(conn, ROOM_A)@@ -212,7 +215,7 @@ def test_losing_the_stream_does_not_kill_the_connection() -> None:def test_a_beat_without_a_stream_is_rejected() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "c1")registry.detach_stream(conn, conn.stream_generation)@@ -223,7 +226,7 @@ def test_a_beat_without_a_stream_is_rejected() -> None:def test_a_stale_heartbeat_kills_the_connection_even_with_a_stream() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "c1")assert conn.stream_attached@@ -235,7 +238,7 @@ def test_a_stale_heartbeat_kills_the_connection_even_with_a_stream() -> None:def test_a_superseded_stream_cannot_clear_the_flag_of_its_replacement() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "c1")stale_generation = conn.stream_generation@@ -246,7 +249,7 @@ def test_a_superseded_stream_cannot_clear_the_flag_of_its_replacement() -> None:def test_beat_advances_the_cursor_but_never_rewinds_it() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "c1")current = conn.stream_generation@@ -255,7 +258,7 @@ def test_beat_advances_the_cursor_but_never_rewinds_it() -> None:def test_a_beat_for_a_superseded_incarnation_is_refused() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "c1")displaced = conn.stream_generation@@ -269,7 +272,7 @@ def test_a_beat_for_a_superseded_incarnation_is_refused() -> None:def test_a_refused_beat_leaves_the_winners_cursor_where_it_was() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "c1")displaced = conn.stream_generationwinner = _open(registry, "c1")@@ -288,7 +291,7 @@ def test_a_refused_beat_leaves_the_winners_cursor_where_it_was() -> None:def test_a_refused_beat_does_not_keep_the_connection_alive() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "c1")displaced = conn.stream_generationwinner = _open(registry, "c1")@@ -304,7 +307,7 @@ def test_a_refused_beat_does_not_keep_the_connection_alive() -> None:def test_a_beat_from_a_client_that_cannot_be_fenced_is_accepted() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()_open(registry, "c1", speaks=None)_open(registry, "c1", speaks=None)@@ -314,7 +317,7 @@ def test_a_beat_from_a_client_that_cannot_be_fenced_is_accepted() -> None:def test_a_client_declaring_the_revision_before_the_fence_ticks_unfenced() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()_open(registry, "c1", speaks=FENCED_PROTOCOL_REVISION - 1)# The server still accepts revision 1, and that revision has no incarnation@@ -324,7 +327,7 @@ def test_a_client_declaring_the_revision_before_the_fence_ticks_unfenced() -> Nodef test_a_holder_that_carries_an_incarnation_may_not_tick_without_one() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "c1")conn.cursor = 4@@ -340,7 +343,7 @@ def test_a_holder_that_carries_an_incarnation_may_not_tick_without_one() -> Nonedef test_what_a_connection_cannot_be_fenced_by_follows_its_current_holder() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()_open(registry, "c1", speaks=None)# A reattach replaces the declaration, so an id first opened by a client@@ -364,7 +367,7 @@ def test_a_connection_accumulates_the_rooms_claimed_on_it() -> None:it: clearing here would mean a second session connecting silentlyunsubscribed the first."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "c1", scope="single")registry.claim_room(conn, ROOM_A)@@ -376,7 +379,7 @@ def test_a_connection_accumulates_the_rooms_claimed_on_it() -> None:def test_a_second_connection_cannot_take_a_claimed_room() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()first = _open(registry, "c1")registry.claim_room(first, ROOM_A)@@ -386,7 +389,7 @@ def test_a_second_connection_cannot_take_a_claimed_room() -> None:def test_takeover_evicts_the_incumbent() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()first = _open(registry, "c1")registry.claim_room(first, ROOM_A)second = _open(registry, "c2")@@ -399,7 +402,7 @@ def test_takeover_evicts_the_incumbent() -> None:def test_all_scope_covers_rooms_no_session_has_claimed() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()daemon = _open(registry, "daemon", scope="all", delivery_filter="addressed")assert registry.covers(daemon, ROOM_A)@@ -407,7 +410,7 @@ def test_all_scope_covers_rooms_no_session_has_claimed() -> None:def test_all_scope_goes_fully_dark_on_a_claimed_room() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()daemon = _open(registry, "daemon", scope="all", delivery_filter="addressed")session = _open(registry, "session", scope="single")registry.claim_room(session, ROOM_A)@@ -419,7 +422,7 @@ def test_all_scope_goes_fully_dark_on_a_claimed_room() -> None:def test_coverage_returns_to_the_daemon_when_the_session_goes() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()daemon = _open(registry, "daemon", scope="all")session = _open(registry, "session", scope="single")registry.claim_room(session, ROOM_A)@@ -440,7 +443,7 @@ def test_a_removal_takes_the_room_off_every_connection_of_that_agent() -> None:session that claimed a room the agent has since been removed from keepscovering it for the life of its stream."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()session = _open(registry, "session", scope="single")other = _open(registry, "other", scope="single")registry.claim_room(session, ROOM_A)@@ -454,7 +457,7 @@ def test_a_removal_takes_the_room_off_every_connection_of_that_agent() -> None:def test_a_removal_does_not_touch_another_agents_claim() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()mine = _open(registry, "c1")theirs = _open(registry, "c2", agent_id=OTHER_AGENT)registry.claim_room(mine, ROOM_A)@@ -468,7 +471,7 @@ def test_a_removal_does_not_touch_another_agents_claim() -> None:def test_a_removal_reaches_a_connection_whose_heartbeat_has_lapsed() -> None:"""A lapsed connection still holds its claim, and can be reconnected to."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "c1")registry.claim_room(conn, ROOM_A)conn.last_beat = time.monotonic() - HEARTBEAT_TTL_SECONDS - 1@@ -480,7 +483,7 @@ def test_a_removal_reaches_a_connection_whose_heartbeat_has_lapsed() -> None:def test_rooms_of_one_agent_do_not_block_another() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()mine = _open(registry, "c1")registry.claim_room(mine, ROOM_A)@@ -503,7 +506,7 @@ class TestAReattachCanBeFenced:"""def test_the_holder_reattaches_and_the_incarnation_moves_on(self) -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "c1")before = conn.stream_generation@@ -512,7 +515,7 @@ class TestAReattachCanBeFenced:assert conn.stream_generation != beforedef test_a_claim_on_a_superseded_incarnation_is_refused(self) -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "c1")displaced = conn.stream_generation_open(registry, "c1")@@ -530,7 +533,7 @@ class TestAReattachCanBeFenced:the declaration would hand the loser a way to disrupt the winnerwithout ever taking the connection from it."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "c1")displaced = conn.stream_generation_open(registry, "c1", speaks=PROTOCOL_VERSION)@@ -552,7 +555,7 @@ class TestAReattachCanBeFenced:It is how a supervisor adopts a session's connection, and how everyclient built before the check attaches. Both are unconditional."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "c1")_open(registry, "c1")@@ -567,7 +570,7 @@ class TestAReattachCanBeFenced:Refusing here would strand every client that outlived the process:there is no holder to protect, so there is nothing to take away."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "c1", expected_generation=4)@@ -585,7 +588,7 @@ class TestAReattachCanBeFenced:evict the client that legitimately opened it — the takeover the fenceexists to refuse, let through by arithmetic."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()stale = _open(registry, "c1").stream_generationregistry.close("c1", HEARTBEAT_LAPSED)@@ -609,14 +612,14 @@ class TestLiveConnectionIds:"""def test_reports_connection_ids_not_agent_ids(self) -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()_open(registry, "c1")_open(registry, "c2")assert registry.live_connection_ids() == {"c1", "c2"}def test_a_dead_connection_is_not_reported(self) -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "c1")_open(registry, "c2")diff --git a/core/tests/switch_core/bridges/agent/protocol/test_create_room_group.py b/core/tests/switch_core/bridges/agent/protocol/test_create_room_group.pyindex af76b03c1..5db2fdef1 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_create_room_group.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_create_room_group.py@@ -3,17 +3,17 @@ from __future__ import annotationsimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.db.models import Roomfrom switch_core.db.stores.room_group_store import RoomGroupStorefrom switch_core.db.stores.room_store import RoomStore-def _bare_service() -> ProtocolService:+def _bare_service() -> AgentCore:# These methods only touch the passed-in session / session_factory, so we# can exercise them on an un-__init__'d instance (matching the fake-based# protocol tests).- return object.__new__(ProtocolService)+ return object.__new__(AgentCore)class TestResolveGroupName:@@ -86,7 +86,7 @@ class TestListRoomGroups:)room = await rooms.create(session,- Room(matrix_room_id="!r:test", name="r", description="d"),+ Room(transport_room_id="!r:test", name="r", description="d"),)await rooms.set_group(session, room.id, child.id)await session.commit()diff --git a/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.py b/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.pyindex 422b4c44b..a7d2fb633 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.py@@ -3,8 +3,8 @@ from __future__ import annotationsimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.types import AgentStatusfrom switch_core.budgets import BudgetExceeded, BudgetGuardfrom switch_core.db.models import (@@ -24,11 +24,11 @@ from switch_core.db.stores.task_store import TaskStorefrom switch_core.db.stores.usage_store import UsageStore-def _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolService:- svc = object.__new__(ProtocolService)+def _service(session_factory: async_sessionmaker[AsyncSession]) -> AgentCore:+ svc = object.__new__(AgentCore)# Presence unions the heartbeat rows with the live connections# (CHOO-1857); an empty registry means "rows only".- svc.connections = ConnectionRegistry()+ svc.connections = AgentConnectionRegistry()svc.session_factory = session_factory # type: ignore[attr-defined]svc.agent_store = AgentStore() # type: ignore[attr-defined]svc.room_store = RoomStore() # type: ignore[attr-defined]@@ -71,7 +71,7 @@ async def _make_agent(type="agent",)client = Client(- matrix_user_id=f"@{name}:test",+ transport_user_id=f"@{name}:test",display_name=name,type="agent",)@@ -96,7 +96,7 @@ async def _make_agent(async def _make_room(session: AsyncSession, room_store: RoomStore, agent_ids: list[str]) -> Room:- room = Room(matrix_room_id="!room:test", name="Room", description="d")+ room = Room(transport_room_id="!room:test", name="Room", description="d")session.add(room)await session.flush()await room_store.add_agents(session, room.id, agent_ids)diff --git a/core/tests/switch_core/bridges/agent/protocol/test_delete_agent.py b/core/tests/switch_core/bridges/agent/protocol/test_delete_agent.pyindex 04d2b823e..6ac83f28d 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_delete_agent.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_delete_agent.py@@ -59,7 +59,7 @@ class TestDeleteAgentInARoom:assert agent is not Noneclient_id = agent.client_idroom = Room(- matrix_room_id=f"!{uuid.uuid4().hex[:8]}:test",+ transport_room_id=f"!{uuid.uuid4().hex[:8]}:test",name="a room",description="somewhere the agent has been",)diff --git a/core/tests/switch_core/bridges/agent/protocol/test_list_all_references.py b/core/tests/switch_core/bridges/agent/protocol/test_list_all_references.pyindex 28a9aca9e..067b92770 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_list_all_references.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_list_all_references.py@@ -1,4 +1,4 @@-"""`ProtocolService.list_all_references` — the agent-facing reference search.+"""`AgentCore.list_all_references` — the agent-facing reference search.The interesting behaviour here is authorization (the agent acts as its owner,and an agent owned by a non-admin must never see a stranger's private@@ -17,8 +17,8 @@ from typing import Anyimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.resource.service import ResourceServicefrom switch_core.db.models import Reference, Room, Userfrom switch_core.db.stores.document_store import DocumentStore@@ -46,9 +46,9 @@ class _FakeAgentStore:def _build_service(session_factory: async_sessionmaker[AsyncSession],owners: dict[str, str | None],-) -> ProtocolService:- svc = object.__new__(ProtocolService)- svc.connections = ConnectionRegistry()+) -> AgentCore:+ svc = object.__new__(AgentCore)+ svc.connections = AgentConnectionRegistry()svc.session_factory = session_factory # type: ignore[assignment]svc.agent_store = _FakeAgentStore(owners) # type: ignore[assignment]svc.user_store = UserStore() # type: ignore[assignment]@@ -255,9 +255,11 @@ class TestAttachedToCurrentRoom:attached = await _make_reference(session, owner=alice, name="attached")loose = await _make_reference(session, owner=alice, name="loose")room = Room(- matrix_room_id="!current:test", name="Current", description="room"+ transport_room_id="!current:test", name="Current", description="room"+ )+ other = Room(+ transport_room_id="!other:test", name="Other", description="room")- other = Room(matrix_room_id="!other:test", name="Other", description="room")session.add_all([room, other])await session.flush()store = ReferenceStore()diff --git a/core/tests/switch_core/bridges/agent/protocol/test_poll_events_membership.py b/core/tests/switch_core/bridges/agent/protocol/test_poll_events_membership.pyindex 0f36feebd..38dff82c2 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_poll_events_membership.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_poll_events_membership.py@@ -41,7 +41,7 @@ async def _room(session_factory: async_sessionmaker[AsyncSession], name: str, agent_id: str) -> str:async with session_factory() as session:- room = Room(matrix_room_id=f"!{name}:test", name=name, description="")+ room = Room(transport_room_id=f"!{name}:test", name=name, description="")session.add(room)await session.flush()await RoomStore().add_agents(session, room.id, [agent_id])diff --git a/core/tests/switch_core/bridges/agent/protocol/test_pool_checkouts.py b/core/tests/switch_core/bridges/agent/protocol/test_pool_checkouts.pyindex 891d8e0cb..5194ef749 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_pool_checkouts.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_pool_checkouts.py@@ -16,8 +16,8 @@ from typing import Anyimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.types import RoomDescriptorfrom switch_core.budgets import BudgetExceeded, BudgetGuardfrom switch_core.db.models import (@@ -68,14 +68,14 @@ class _OneBridge:self.typing.append((room_id, agent_name, is_typing))-def _service(counting: _CountingSessionFactory) -> ProtocolService:- svc = object.__new__(ProtocolService)+def _service(counting: _CountingSessionFactory) -> AgentCore:+ svc = object.__new__(AgentCore)svc.session_factory = counting # type: ignore[attr-defined]svc.agent_store = AgentStore() # type: ignore[attr-defined]svc.room_store = RoomStore() # type: ignore[attr-defined]svc.budget_guard = BudgetGuard(BudgetStore()) # type: ignore[attr-defined]svc.collab_lifecycle = _NoBridges() # type: ignore[attr-defined]- svc.connections = ConnectionRegistry()+ svc.connections = AgentConnectionRegistry()return svc@@ -103,7 +103,7 @@ async def _seed(type="agent",)client = Client(- matrix_user_id=f"@{name}:test",+ transport_user_id=f"@{name}:test",display_name=name,type="agent",)@@ -123,7 +123,7 @@ async def _seed(session.add(agent)await session.flush()ids.append(agent.id)- room = Room(matrix_room_id="!r:test", name="room", description="d")+ room = Room(transport_room_id="!r:test", name="room", description="d")session.add(room)await session.flush()await RoomStore().add_agents(session, room.id, [ids[0]])@@ -316,9 +316,9 @@ class TestSendMessage:class _Client:async def send_message(- self, matrix_room_id: str, content: str, **_kwargs: Any+ self, transport_room_id: str, content: str, **_kwargs: Any) -> str:- sent.append((matrix_room_id, content))+ sent.append((transport_room_id, content))return "$event"svc.client_lifecycle = SimpleNamespace( # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/agent/protocol/test_read_context.py b/core/tests/switch_core/bridges/agent/protocol/test_read_context.pyindex 9fa37a9aa..e1ec27d92 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_read_context.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_read_context.py@@ -21,8 +21,8 @@ from types import SimpleNamespacefrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.attachments import ATTACHMENT_GROUP_KEY-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.clients.admin_messages import PLATFORM_MARKERfrom switch_core.db.models import Client, Message, MessageAttachment, Roomfrom switch_core.db.stores.message_store import MessageStore@@ -42,14 +42,14 @@ async def _make_room(session: AsyncSession) -> tuple[str, str]:"""Insert the Room and Client a recorded row depends on."""suffix = uuid.uuid4().hex[:8]client = Client(- matrix_user_id=f"@agent-{suffix}:test",+ transport_user_id=f"@agent-{suffix}:test",display_name="agent one",type="agent",)session.add(client)await session.flush()room = Room(- matrix_room_id=f"!room-{suffix}:test",+ transport_room_id=f"!room-{suffix}:test",name="a room",description="",)@@ -91,12 +91,12 @@ async def _write(return await MessageStore().create(session, message, attachments or [])-def _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolService:+def _service(session_factory: async_sessionmaker[AsyncSession]) -> AgentCore:async def _require(agent_id: str, room_id: str):return SimpleNamespace(id=room_id)- svc = object.__new__(ProtocolService)- svc.connections = ConnectionRegistry()+ svc = object.__new__(AgentCore)+ svc.connections = AgentConnectionRegistry()svc.session_factory = session_factorysvc.message_store = MessageStore()svc.require_room_member = _require # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/agent/protocol/test_record_client_declaration.py b/core/tests/switch_core/bridges/agent/protocol/test_record_client_declaration.pyindex b5d7d0a23..bbc710f4b 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_record_client_declaration.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_record_client_declaration.py@@ -15,8 +15,8 @@ from typing import Anyimport pytest-from switch_core.bridges.agent.protocol.connections import ClientDeclaration-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_connections import ClientDeclaration+from switch_core.bridges.agent.protocol.agent_core import AgentCoreAGENT_ID = "agent-1"CONNECTION_ID = "conn-1"@@ -48,14 +48,14 @@ class _AgentStore:self.updates.append(kwargs)-def _service(store: _AgentStore) -> ProtocolService:- """A ProtocolService with only the two collaborators this path touches.+def _service(store: _AgentStore) -> AgentCore:+ """An AgentCore with only the two collaborators this path touches.Constructed without __init__ on purpose: the real one wires two dozendependencies, none of which this method uses, and threading them allthrough would test the fixture rather than the behaviour."""- service = ProtocolService.__new__(ProtocolService)+ service = AgentCore.__new__(AgentCore)session = _Session()@asynccontextmanagerdiff --git a/core/tests/switch_core/bridges/agent/protocol/test_reference_type_parity.py b/core/tests/switch_core/bridges/agent/protocol/test_reference_type_parity.pyindex b0656af7e..ae1f3071e 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_reference_type_parity.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_reference_type_parity.py@@ -4,7 +4,7 @@ user). They are separate implementations over the same service, so this filepins them to the same answer for the same principal: a filter added to one andnot the other is a drift bug that no other test would catch.-`ProtocolService.__init__` takes 17 required collaborators, so the service is+`AgentCore.__init__` takes 17 required collaborators, so the service isbuilt with `object.__new__` and the four attributes this method touches, per`test_agent_detail_mcp_tools.py`. `_resolve_acting_identity` loads the ownerwith `session.get(User, ...)` on the live session, then reads@@ -15,7 +15,7 @@ from __future__ import annotationsfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.resource.registry import BUILTIN_REFERENCE_TYPESfrom switch_core.bridges.resource.service import ResourceServicefrom switch_core.db.models import Agent, ApiKey, Client, User@@ -44,11 +44,11 @@ def _resource_service()-def _protocol_service(+def _agent_core(session_factory: async_sessionmaker[AsyncSession],resource_service: ResourceService,-) -> ProtocolService:- svc = object.__new__(ProtocolService)+) -> AgentCore:+ svc = object.__new__(AgentCore)svc.session_factory = session_factory # type: ignore[attr-defined]svc.agent_store = AgentStore() # type: ignore[attr-defined]svc.resource_service = resource_service # type: ignore[attr-defined]@@ -76,7 +76,7 @@ async def _make_agent(type="agent",)client = Client(- matrix_user_id=f"@{name}:example.invalid",+ transport_user_id=f"@{name}:example.invalid",display_name=name,type="agent",)@@ -151,7 +151,7 @@ class TestAgentAndGatewayAgree:self, session_factory: async_sessionmaker[AsyncSession]) -> None:service = _resource_service(session_factory)- svc = _protocol_service(session_factory, service)+ svc = _agent_core(session_factory, service)async with session_factory() as session:alice, _bob, agent = await _seed(session, service)await session.commit()@@ -172,7 +172,7 @@ class TestAgentAndGatewayAgree:self, session_factory: async_sessionmaker[AsyncSession]) -> None:service = _resource_service(session_factory)- svc = _protocol_service(session_factory, service)+ svc = _agent_core(session_factory, service)async with session_factory() as session:_alice, _bob, _agent = await _seed(session, service)root = await _make_user(session, "root", role="admin")@@ -201,7 +201,7 @@ class TestOwnerlessAgent:self, session_factory: async_sessionmaker[AsyncSession]) -> None:service = _resource_service(session_factory)- svc = _protocol_service(session_factory, service)+ svc = _agent_core(session_factory, service)async with session_factory() as session:_alice, bob, _agent = await _seed(session, service)agent = await _make_agent(@@ -219,7 +219,7 @@ class TestEntryShape:self, session_factory: async_sessionmaker[AsyncSession]) -> None:service = _resource_service(session_factory)- svc = _protocol_service(session_factory, service)+ svc = _agent_core(session_factory, service)async with session_factory() as session:_alice, _bob, agent = await _seed(session, service)await session.commit()diff --git a/core/tests/switch_core/bridges/agent/protocol/test_register_addressing_policy.py b/core/tests/switch_core/bridges/agent/protocol/test_register_addressing_policy.pyindex a39684a04..17aa70781 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_register_addressing_policy.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_register_addressing_policy.py@@ -8,7 +8,7 @@ from types import SimpleNamespacefrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.addressing import parse_policy-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.db.models import TENANT_ZERO_ID, ApiKeyfrom tests.switch_core.bridges.agent.protocol.registration_harness import (PROFILE,@@ -44,7 +44,7 @@ async def _seed_registration_key(async def _policy_of(- svc: ProtocolService,+ svc: AgentCore,session_factory: async_sessionmaker[AsyncSession],agent_id: str,) -> dict | None:diff --git a/core/tests/switch_core/bridges/agent/protocol/test_register_display_name.py b/core/tests/switch_core/bridges/agent/protocol/test_register_display_name.pyindex ee7170dc9..4344f4410 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_register_display_name.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_register_display_name.py@@ -15,7 +15,7 @@ import pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.agent_display_name import InvalidDisplayName-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.db.models import Agent, Clientfrom tests.switch_core.bridges.agent.protocol.registration_harness import (FakeClientLifecycle,@@ -28,7 +28,7 @@ _ICON = "https://cdn.example.com/9.x/bottts/png?seed=switchdev"async def _agent(- svc: ProtocolService,+ svc: AgentCore,session_factory: async_sessionmaker[AsyncSession],agent_id: str,) -> Agent:@@ -38,8 +38,8 @@ async def _agent(return agent-class TestMatrixIdentityStaysTheIdentifier:- async def test_a_display_name_does_not_reach_the_matrix_client(+class TestTransportIdentityStaysTheIdentifier:+ async def test_a_display_name_does_not_reach_the_transport(self, session_factory: async_sessionmaker[AsyncSession]) -> None:svc = make_service(session_factory)diff --git a/core/tests/switch_core/bridges/agent/protocol/test_register_overwrite_owner_guard.py b/core/tests/switch_core/bridges/agent/protocol/test_register_overwrite_owner_guard.pyindex 391181058..c11aab461 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_register_overwrite_owner_guard.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_register_overwrite_owner_guard.py@@ -16,9 +16,9 @@ from types import SimpleNamespaceimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.agent.protocol.service import (+from switch_core.bridges.agent.protocol.agent_core import (+ AgentCore,AgentExistsError,- ProtocolService,)from switch_core.bridges.agent.protocol.types import (IntegrationProfile,@@ -45,7 +45,7 @@ class _FakeClientLifecycle:async def create_client(self, *, client_type: str, display_name: str) -> Client:async with self._session_factory() as session:client = Client(- matrix_user_id=f"@{display_name}:test",+ transport_user_id=f"@{display_name}:test",display_name=display_name,type=client_type,)@@ -62,15 +62,15 @@ class _NoBridges:return []-def _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolService:- svc = object.__new__(ProtocolService)+def _service(session_factory: async_sessionmaker[AsyncSession]) -> AgentCore:+ svc = object.__new__(AgentCore)svc.session_factory = session_factory # type: ignore[attr-defined]svc.agent_store = AgentStore() # type: ignore[attr-defined]svc.api_key_store = ApiKeyStore() # type: ignore[attr-defined]svc.client_lifecycle = _FakeClientLifecycle(session_factory) # type: ignore[attr-defined]svc.collab_lifecycle = _NoBridges() # type: ignore[attr-defined]svc.config = SimpleNamespace(jwt_secret_key="test-secret") # type: ignore[attr-defined]- # Duck-typed: the attribute exists on ProtocolService after the api-key+ # Duck-typed: the attribute exists on AgentCore after the api-key# cache landed on main; a no-op stand-in keeps this test valid on both# sides of that merge.svc.api_key_cache = SimpleNamespace(invalidate_agent=lambda *a, **k: None) # type: ignore[attr-defined]@@ -87,7 +87,7 @@ async def _make_user(return user.id-async def _register(svc: ProtocolService, name: str, owner_id: str, **kw: object):+async def _register(svc: AgentCore, name: str, owner_id: str, **kw: object):return await svc.register_agent(name=name,description=f"{name} desc",diff --git a/core/tests/switch_core/bridges/agent/protocol/test_role_change_notices.py b/core/tests/switch_core/bridges/agent/protocol/test_role_change_notices.pyindex 0817e56aa..9866f9c15 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_role_change_notices.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_role_change_notices.py@@ -3,8 +3,8 @@ from __future__ import annotationsfrom types import SimpleNamespacefrom typing import Any-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCoreclass _FakeSession:@@ -106,7 +106,7 @@ _ROOM = SimpleNamespace(id="room-1",name="This Room",description="desc",- matrix_room_id="!mx:switch.local",+ transport_room_id="!mx:switch.local",archived_at=None,bridge_id=None,)@@ -115,11 +115,11 @@ _ROLE = SimpleNamespace(id="role-m", name="manager", instructions="coordinate")def _build_service(*, role_store: _FakeRoomRoleStore, client: Any, members: list[str]-) -> ProtocolService:- svc = object.__new__(ProtocolService)+) -> AgentCore:+ svc = object.__new__(AgentCore)# Presence unions the heartbeat rows with the live connections# (CHOO-1857); an empty registry means "rows only".- svc.connections = ConnectionRegistry()+ svc.connections = AgentConnectionRegistry()svc.session_factory = _session_factory # type: ignore[assignment]svc.room_role_store = role_store # type: ignore[assignment]svc.room_store = _FakeRoomStore(_ROOM, members) # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/agent/protocol/test_role_detail.py b/core/tests/switch_core/bridges/agent/protocol/test_role_detail.pyindex 731a0fbfd..a21b3a7cb 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_role_detail.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_role_detail.py@@ -5,8 +5,8 @@ from typing import Anyimport pytest-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCoreclass _FakeSession:@@ -117,7 +117,7 @@ def _room(room_id: str, name: str) -> SimpleNamespace:id=room_id,name=name,description="d",- matrix_room_id="!m:x",+ transport_room_id="!m:x",archived_at=None,bridge_id=None,)@@ -132,11 +132,11 @@ def _build_service(rooms: dict[str, Any],members: dict[str, list[str]],my_lease: Any | None = None,-) -> ProtocolService:- svc = object.__new__(ProtocolService)+) -> AgentCore:+ svc = object.__new__(AgentCore)# Presence unions the heartbeat rows with the live connections# (CHOO-1857); an empty registry means "rows only".- svc.connections = ConnectionRegistry()+ svc.connections = AgentConnectionRegistry()svc.session_factory = _session_factory # type: ignore[assignment]svc.room_role_store = _FakeRoomRoleStore(roles, leases, my_lease) # type: ignore[assignment]svc.agent_store = _FakeAgentStore(agents) # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/agent/protocol/test_role_listing.py b/core/tests/switch_core/bridges/agent/protocol/test_role_listing.pyindex eceee7d48..0bcd27911 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_role_listing.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_role_listing.py@@ -3,8 +3,8 @@ from __future__ import annotationsfrom types import SimpleNamespacefrom typing import Any-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCoreclass _FakeSession:@@ -106,11 +106,11 @@ def _build_service(sdk_rooms: dict[str, str],rooms: dict[str, Any],my_lease: Any | None = None,-) -> ProtocolService:- svc = object.__new__(ProtocolService)+) -> AgentCore:+ svc = object.__new__(AgentCore)# Presence unions the heartbeat rows with the live connections# (CHOO-1857); an empty registry means "rows only".- svc.connections = ConnectionRegistry()+ svc.connections = AgentConnectionRegistry()# Where each holding session connected, as `connect_to_room` placed it.for session_id, room_id in sdk_rooms.items():holder = next(diff --git a/core/tests/switch_core/bridges/agent/protocol/test_room_aliases.py b/core/tests/switch_core/bridges/agent/protocol/test_room_aliases.pyindex 508f06313..4c58b4d53 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_room_aliases.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_room_aliases.py@@ -6,8 +6,8 @@ from typing import Anyimport pytestfrom switch_core.aliases import AliasError-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.types import AgentStatus@@ -101,7 +101,7 @@ def _room(**overrides: Any) -> SimpleNamespace:"id": "room-1","name": "Feature room","description": "desc",- "matrix_room_id": "!abc:switch.local",+ "transport_room_id": "!abc:switch.local","channel_type": "channel_private","admin_mode": False,"instructions": "",@@ -124,12 +124,12 @@ def _build_service(agents: dict[str, Any],aliases: dict[str, str] | None = None,role_names: list[str] | None = None,-) -> ProtocolService:+) -> AgentCore:room = _room()- svc = object.__new__(ProtocolService)+ svc = object.__new__(AgentCore)# Presence unions the heartbeat rows with the live connections# (CHOO-1857); an empty registry means "rows only".- svc.connections = ConnectionRegistry()+ svc.connections = AgentConnectionRegistry()svc.session_factory = _session_factory # type: ignore[assignment]svc.room_store = _FakeRoomStore({room.id: room}, agent_ids, aliases or {}) # type: ignore[assignment]svc.agent_store = _FakeAgentStore(agents) # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/agent/protocol/test_room_detail.py b/core/tests/switch_core/bridges/agent/protocol/test_room_detail.pyindex 9f26e4d24..c89d5ee8f 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_room_detail.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_room_detail.py@@ -5,8 +5,8 @@ from typing import Anyimport pytest-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.types import AgentStatus@@ -123,7 +123,7 @@ def _room(**overrides: Any) -> SimpleNamespace:"id": "room-1","name": "Feature room","description": "Work on the feature",- "matrix_room_id": "!abc:switch.local",+ "transport_room_id": "!abc:switch.local","channel_type": "channel_private","admin_mode": False,"instructions": "Be excellent",@@ -150,11 +150,11 @@ def _build_service(ext_users: dict[str, list[Any]] | None = None,statuses: dict[str, AgentStatus] | None = None,roles: list[dict[str, Any]] | None = None,-) -> ProtocolService:- svc = object.__new__(ProtocolService)+) -> AgentCore:+ svc = object.__new__(AgentCore)# Presence unions the heartbeat rows with the live connections# (CHOO-1857); an empty registry means "rows only".- svc.connections = ConnectionRegistry()+ svc.connections = AgentConnectionRegistry()svc.session_factory = _session_factory # type: ignore[assignment]svc.room_store = _FakeRoomStore({room.id: room}, agent_ids, client_ids or []) # type: ignore[assignment]svc.agent_store = _FakeAgentStore(agents or {}) # type: ignore[assignment]@@ -211,7 +211,7 @@ class TestGetRoomDetail:assert detail.channel_type == "channel_private"assert detail.admin_mode is Falseassert detail.instructions == "Be excellent"- assert detail.matrix_room_id == "!abc:switch.local"+ assert detail.transport_room_id == "!abc:switch.local"assert detail.created_at == "2026-05-29T00:00:00+00:00"assert detail.bridge_id is Noneassert detail.bridge_display_name is Nonediff --git a/core/tests/switch_core/bridges/agent/protocol/test_room_group_mcp_tools.py b/core/tests/switch_core/bridges/agent/protocol/test_room_group_mcp_tools.pyindex c3c43f267..b2b837ec8 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_room_group_mcp_tools.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_room_group_mcp_tools.py@@ -3,21 +3,21 @@ from __future__ import annotationsimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.db.models import Roomfrom switch_core.db.stores.room_group_store import RoomGroupStorefrom switch_core.db.stores.room_store import RoomStore-def _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolService:+def _service(session_factory: async_sessionmaker[AsyncSession]) -> AgentCore:# These methods only touch session_factory + room_group_store, so we can# exercise them on an un-__init__'d instance (matching the other protocol# tests) with just those attributes set.- svc = object.__new__(ProtocolService)+ svc = object.__new__(AgentCore)# Presence unions the heartbeat rows with the live connections# (CHOO-1857); an empty registry means "rows only".- svc.connections = ConnectionRegistry()+ svc.connections = AgentConnectionRegistry()svc.session_factory = session_factory # type: ignore[attr-defined]svc.room_group_store = RoomGroupStore() # type: ignore[attr-defined]return svc@@ -72,7 +72,7 @@ class TestGetRoomGroupDetail:async with session_factory() as session:room = await rooms.create(- session, Room(matrix_room_id="!r:test", name="r1", description="d")+ session, Room(transport_room_id="!r:test", name="r1", description="d"))await rooms.set_group(session, room.id, parent["id"])await session.commit()diff --git a/core/tests/switch_core/bridges/agent/protocol/test_room_links.py b/core/tests/switch_core/bridges/agent/protocol/test_room_links.pyindex 0b33add74..50de2b66f 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_room_links.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_room_links.py@@ -5,8 +5,8 @@ from typing import Anyimport pytest-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCoreclass _FakeSession:@@ -65,14 +65,14 @@ class _FakeRoomStore:def _build_service(*, exists: bool-) -> tuple[ProtocolService, _FakeSession, _FakeResourceService]:+) -> tuple[AgentCore, _FakeSession, _FakeResourceService]:session = _FakeSession()resource_service = _FakeResourceService(exists=exists)- svc = object.__new__(ProtocolService)+ svc = object.__new__(AgentCore)# Presence unions the heartbeat rows with the live connections# (CHOO-1857); an empty registry means "rows only".- svc.connections = ConnectionRegistry()+ svc.connections = AgentConnectionRegistry()svc.session_factory = lambda: session # type: ignore[assignment]svc.resource_service = resource_service # type: ignore[assignment]svc.agent_store = _FakeAgentStore() # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/agent/protocol/test_room_released.py b/core/tests/switch_core/bridges/agent/protocol/test_room_released.pyindex ca8389fac..ea134e656 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_room_released.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_room_released.py@@ -8,11 +8,11 @@ from typing import Anyimport pytest-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (ROOM_RELEASED_PROTOCOL_REVISION,+ AgentConnection,+ AgentConnectionRegistry,ClientDeclaration,- Connection,- ConnectionRegistry,Released,)from switch_core.bridges.agent.protocol.event_buffer import EventBuffer@@ -25,8 +25,12 @@ ROOM_C = "room-c"def _open(- registry: ConnectionRegistry, connection_id: str, *, speaks: int | None, scope: str-) -> Connection:+ registry: AgentConnectionRegistry,+ connection_id: str,+ *,+ speaks: int | None,+ scope: str,+) -> AgentConnection:return registry.open(agent_id=AGENT,connection_id=connection_id,@@ -64,7 +68,7 @@ async def _frames_until_quiet(def test_a_claim_taken_over_is_released_to_its_holder_with_its_session() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()loser = _open(registry, "loser", speaks=ROOM_RELEASED_PROTOCOL_REVISION, scope="all")@@ -82,7 +86,7 @@ def test_a_claim_taken_over_is_released_to_its_holder_with_its_session() -> Nonedef test_connect_to_room_placement_releases_the_other_connections_session() -> None:"""`connect_to_room` places before it claims; the frame names the session once."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()loser = _open(registry, "loser", speaks=ROOM_RELEASED_PROTOCOL_REVISION, scope="all")@@ -99,7 +103,7 @@ def test_connect_to_room_placement_releases_the_other_connections_session() -> Ndef test_displacing_a_sibling_on_the_same_connection_releases_nothing() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "watcher", speaks=ROOM_RELEASED_PROTOCOL_REVISION, scope="all")@@ -112,7 +116,7 @@ def test_displacing_a_sibling_on_the_same_connection_releases_nothing() -> None:@pytest.mark.parametrize("speaks", [ROOM_RELEASED_PROTOCOL_REVISION - 1, None])def test_a_client_that_cannot_take_the_frame_is_not_sent_it(speaks: int | None) -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()loser = _open(registry, "loser", speaks=speaks, scope="single")winner = _open(registry, "winner", speaks=ROOM_RELEASED_PROTOCOL_REVISION, scope="all"@@ -126,7 +130,7 @@ def test_a_client_that_cannot_take_the_frame_is_not_sent_it(speaks: int | None)def test_taking_the_room_back_withdraws_the_unsent_release() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()first = _open(registry, "first", speaks=ROOM_RELEASED_PROTOCOL_REVISION, scope="all")@@ -143,7 +147,7 @@ def test_taking_the_room_back_withdraws_the_unsent_release() -> None:def test_replacing_placements_is_a_full_replacement() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "watcher", speaks=ROOM_RELEASED_PROTOCOL_REVISION, scope="all")@@ -158,7 +162,7 @@ def test_replacing_placements_is_a_full_replacement() -> None:def test_replacing_placements_leaves_other_connections_alone() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()mine = _open(registry, "mine", speaks=ROOM_RELEASED_PROTOCOL_REVISION, scope="all")theirs = _open(registry, "theirs", speaks=ROOM_RELEASED_PROTOCOL_REVISION, scope="all"@@ -175,7 +179,7 @@ def test_replacing_placements_leaves_other_connections_alone() -> None:def test_replacing_placements_takes_a_room_over_and_releases_it() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()mine = _open(registry, "mine", speaks=ROOM_RELEASED_PROTOCOL_REVISION, scope="all")theirs = _open(registry, "theirs", speaks=ROOM_RELEASED_PROTOCOL_REVISION, scope="all"@@ -194,7 +198,7 @@ def test_replacing_placements_takes_a_room_over_and_releases_it() -> None:def test_a_room_claimed_without_a_placement_is_released_with_no_session() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()mine = _open(registry, "mine", speaks=ROOM_RELEASED_PROTOCOL_REVISION, scope="all")theirs = _open(registry, "theirs", speaks=ROOM_RELEASED_PROTOCOL_REVISION, scope="single"@@ -210,7 +214,7 @@ def test_a_room_claimed_without_a_placement_is_released_with_no_session() -> Nondef test_two_sessions_in_one_room_are_refused_without_change() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _open(registry, "watcher", speaks=ROOM_RELEASED_PROTOCOL_REVISION, scope="all")@@ -224,7 +228,7 @@ def test_two_sessions_in_one_room_are_refused_without_change() -> None:async def test_the_displaced_stream_is_sent_room_released() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()loser = _open(registry, "loser", speaks=ROOM_RELEASED_PROTOCOL_REVISION, scope="all"@@ -248,7 +252,7 @@ async def test_the_displaced_stream_is_sent_room_released() -> None:async def test_an_older_client_stream_is_not_sent_room_released() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()loser = _open(registry, "loser", speaks=ROOM_RELEASED_PROTOCOL_REVISION - 1, scope="all"diff --git a/core/tests/switch_core/bridges/agent/protocol/test_room_roster_authz.py b/core/tests/switch_core/bridges/agent/protocol/test_room_roster_authz.pyindex 3ef918b1f..51ee5e4b7 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_room_roster_authz.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_room_roster_authz.py@@ -15,7 +15,7 @@ from types import SimpleNamespaceimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.types import (IntegrationProfile,TaskProtocolConfig,@@ -43,7 +43,7 @@ class _FakeClientLifecycle:async def create_client(self, *, client_type: str, display_name: str) -> Client:async with self._session_factory() as session:client = Client(- matrix_user_id=f"@{display_name}:test",+ transport_user_id=f"@{display_name}:test",display_name=display_name,type=client_type,)@@ -60,8 +60,8 @@ class _NoBridges:return []-def _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolService:- svc = object.__new__(ProtocolService)+def _service(session_factory: async_sessionmaker[AsyncSession]) -> AgentCore:+ svc = object.__new__(AgentCore)svc.session_factory = session_factory # type: ignore[attr-defined]svc.agent_store = AgentStore() # type: ignore[attr-defined]svc.api_key_store = ApiKeyStore() # type: ignore[attr-defined]@@ -86,7 +86,7 @@ async def _make_user(return user.id-async def _register(svc: ProtocolService, name: str, owner_id: str) -> str:+async def _register(svc: AgentCore, name: str, owner_id: str) -> str:result = await svc.register_agent(name=name,description=f"{name} desc",@@ -105,7 +105,7 @@ async def _make_public_room() -> str:async with session_factory() as session:room = Room(- matrix_room_id="!secret:test",+ transport_room_id="!secret:test",name="secret",description="",owner_id=owner_id,diff --git a/core/tests/switch_core/bridges/agent/protocol/test_runtime_state_sweep.py b/core/tests/switch_core/bridges/agent/protocol/test_runtime_state_sweep.pyindex 533895034..fb89251a1 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_runtime_state_sweep.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_runtime_state_sweep.py@@ -23,12 +23,12 @@ from typing import Anyfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (PROTOCOL_VERSION,+ AgentConnectionRegistry,ClientDeclaration,- ConnectionRegistry,)-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.db.models import TENANT_ZERO_IDAGENT = "agent-1"@@ -60,10 +60,10 @@ class _SessionStore:def _service(session_factory: async_sessionmaker[AsyncSession],- registry: ConnectionRegistry,+ registry: AgentConnectionRegistry,store: _RuntimeStateStore,-) -> ProtocolService:- svc = object.__new__(ProtocolService)+) -> AgentCore:+ svc = object.__new__(AgentCore)svc.connections = registrysvc.agent_runtime_state_store = store # type: ignore[assignment]svc.agent_session_store = _SessionStore() # type: ignore[assignment]@@ -86,15 +86,15 @@ async def _an_agent(*_a: Any, **_kw: Any) -> Any:async def _a_room(*_a: Any, **_kw: Any) -> Any:- return SimpleNamespace(id=ROOM, matrix_room_id="!m:server", bridge_id=None)+ return SimpleNamespace(id=ROOM, transport_room_id="!m:server", bridge_id=None)async def _noop(*_a: Any, **_kw: Any) -> None:return None-def _connected(room: str | None) -> ConnectionRegistry:- registry = ConnectionRegistry()+def _connected(room: str | None) -> AgentConnectionRegistry:+ registry = AgentConnectionRegistry()conn = registry.open(agent_id=AGENT,connection_id="c1",@@ -149,6 +149,8 @@ async def test_with_nothing_live_the_sweep_still_clears("""The sweep's whole purpose: a crashed session must not stay 'working'."""store = _RuntimeStateStore([_row()])- await _service(session_factory, ConnectionRegistry(), store).sweep_runtime_states()+ await _service(+ session_factory, AgentConnectionRegistry(), store+ ).sweep_runtime_states()assert store.cleared == [(AGENT, ROOM)]diff --git a/core/tests/switch_core/bridges/agent/protocol/test_send_media.py b/core/tests/switch_core/bridges/agent/protocol/test_send_media.pyindex 1eff08346..93e2cdbe2 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_send_media.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_send_media.py@@ -5,8 +5,8 @@ from typing import Anyimport pytest-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCoreclass _FakeClient:@@ -49,17 +49,19 @@ class _FakeClient:return f"$media-event-{len(self.sends)}"-def _build_service(client: _FakeClient, *, max_bytes: int = 100) -> ProtocolService:+def _build_service(client: _FakeClient, *, max_bytes: int = 100) -> AgentCore:async def _require(agent_id: str, room_id: str):- return SimpleNamespace(id=room_id, matrix_room_id="!room", bridge_id=None)+ return SimpleNamespace(id=room_id, transport_room_id="!room", bridge_id=None)- async def _resolve_thread_root(client_: Any, matrix_room_id: str, thread_id: str):+ async def _resolve_thread_root(+ client_: Any, transport_room_id: str, thread_id: str+ ):return f"root-of-{thread_id}"- svc = object.__new__(ProtocolService)+ svc = object.__new__(AgentCore)# Presence unions the heartbeat rows with the live connections# (CHOO-1857); an empty registry means "rows only".- svc.connections = ConnectionRegistry()+ svc.connections = AgentConnectionRegistry()svc.require_room_poster = _require # type: ignore[assignment]svc.client_lifecycle = SimpleNamespace( # type: ignore[assignment]get_by_agent_id=lambda agent_id: clientdiff --git a/core/tests/switch_core/bridges/agent/protocol/test_send_targeted_roles.py b/core/tests/switch_core/bridges/agent/protocol/test_send_targeted_roles.pyindex 8342afa0a..38f0086f0 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_send_targeted_roles.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_send_targeted_roles.py@@ -5,8 +5,8 @@ from typing import Anyimport pytest-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.types import (AgentStatus,RoomWideMentionStatus,@@ -83,13 +83,13 @@ def _build_service(holders: dict[str, list[str]],agents: dict[str, Any],group_id: str | None = None,-) -> tuple[ProtocolService, list[str]]:+) -> tuple[AgentCore, list[str]]:sent_bodies: list[str] = []- svc = object.__new__(ProtocolService)+ svc = object.__new__(AgentCore)# Presence unions the heartbeat rows with the live connections# (CHOO-1857); an empty registry means "rows only".- svc.connections = ConnectionRegistry()+ svc.connections = AgentConnectionRegistry()svc.session_factory = _session_factory # type: ignore[assignment]svc.room_role_store = _FakeRoomRoleStore(roles, holders) # type: ignore[assignment]svc.agent_store = _FakeAgentStore(agents) # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/agent/protocol/test_statuses.py b/core/tests/switch_core/bridges/agent/protocol/test_statuses.pyindex e26dd9090..e495022d7 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_statuses.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_statuses.py@@ -7,10 +7,10 @@ from typing import Anyimport pytest_asynciofrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (PROTOCOL_VERSION,+ AgentConnectionRegistry,ClientDeclaration,- ConnectionRegistry,)from switch_core.bridges.agent.protocol.statuses import compute_agent_statusesfrom switch_core.bridges.agent.protocol.types import AgentStatus@@ -50,9 +50,9 @@ def _registry(scope: str = "single",room: str | None = None,spawn_capable: bool = False,-) -> ConnectionRegistry:+) -> AgentConnectionRegistry:"""A registry holding at most one live connection."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()if agent_id is not None:conn = registry.open(agent_id=agent_id,diff --git a/core/tests/switch_core/bridges/agent/protocol/test_stream.py b/core/tests/switch_core/bridges/agent/protocol/test_stream.pyindex a99196eb5..012528a02 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_stream.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_stream.py@@ -10,18 +10,19 @@ import pytestfrom switch_core import version as version_modulefrom switch_core.bridges.agent.protocol import stream as stream_module-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (HEARTBEAT_LAPSED,HEARTBEAT_TTL_SECONDS,PROTOCOL_ACCEPTS,PROTOCOL_VERSION,+ AgentConnectionRegistry,ClientDeclaration,Closure,- ConnectionRegistry,)from switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.bridges.agent.protocol.stream import event_streamfrom switch_core.bridges.agent.protocol.types import AgentEvent, MessagePayload+from switch_core.observability.metrics import MetricsRegistry, install, uninstallAGENT = "agent-1"ROOM_A = "room-a"@@ -72,7 +73,7 @@ async def _take(stream, count: int, timeout: float = 2.0) -> list[tuple[str, dicreturn out-def _open(registry: ConnectionRegistry, **kw: Any):+def _open(registry: AgentConnectionRegistry, **kw: Any):params: dict[str, Any] = {"agent_id": AGENT,"connection_id": kw.pop("connection_id", "c1"),@@ -88,7 +89,7 @@ def _open(registry: ConnectionRegistry, **kw: Any):async def test_first_frame_is_the_connection_state() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry)registry.claim_room(conn, ROOM_A)@@ -113,7 +114,7 @@ async def test_the_first_frame_declares_the_server(monkeypatch) -> None:version is reachable without authenticating (CHOO-1865)."""monkeypatch.setattr(version_module, "switch_core_version", lambda: "9.9.9")- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry)@@ -136,7 +137,7 @@ async def test_an_unreadable_server_version_is_null_not_a_placeholder() -> None:"""Null means unknown. A placeholder would read as a version we chose."""monkeypatch.setattr(version_module, "switch_core_version", lambda: None)- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry)@@ -152,7 +153,7 @@ async def test_the_first_frame_echoes_what_the_client_declared() -> None:Both sides otherwise believe it landed, which is worse than never havingsent it."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry,@@ -176,7 +177,7 @@ async def test_the_first_frame_echoes_what_the_client_declared() -> None:async def test_an_undeclared_client_is_echoed_as_all_null() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry, declaration=ClientDeclaration())@@ -192,7 +193,7 @@ async def test_an_undeclared_client_is_echoed_as_all_null() -> None:async def test_catch_up_then_live_delivery() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry)registry.claim_room(conn, ROOM_A)@@ -218,7 +219,7 @@ async def test_catch_up_then_live_delivery() -> None:async def test_sequence_number_is_carried_for_resume() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry)registry.claim_room(conn, ROOM_A)@@ -232,7 +233,7 @@ async def test_sequence_number_is_carried_for_resume() -> None:async def test_resuming_from_a_cursor_skips_what_was_already_seen() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()first = buffer.enqueue(AGENT, ROOM_A, _message("seen"))buffer.enqueue(AGENT, ROOM_A, _message("missed"))@@ -247,7 +248,7 @@ async def test_resuming_from_a_cursor_skips_what_was_already_seen() -> None:async def test_expired_cursor_produces_a_gap_event_rather_than_silence() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer(max_events_per_agent=1)buffer.enqueue(AGENT, ROOM_A, _message("dropped"))buffer.enqueue(AGENT, ROOM_A, _message("kept"))@@ -263,7 +264,7 @@ async def test_expired_cursor_produces_a_gap_event_rather_than_silence() -> Noneasync def test_events_for_rooms_the_connection_does_not_cover_are_skipped() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry)registry.claim_room(conn, ROOM_A)@@ -278,7 +279,7 @@ async def test_events_for_rooms_the_connection_does_not_cover_are_skipped() -> Nasync def test_addressed_filter_drops_ambient_chatter() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry, scope="all", delivery_filter="addressed")@@ -292,7 +293,7 @@ async def test_addressed_filter_drops_ambient_chatter() -> None:async def test_a_superseded_stream_is_told_it_was_evicted() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry)registry.claim_room(conn, ROOM_A)@@ -312,7 +313,7 @@ async def test_a_superseded_stream_is_told_it_was_evicted() -> None:async def test_closing_the_connection_ends_the_stream_with_a_reason() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry)registry.claim_room(conn, ROOM_A)@@ -331,7 +332,7 @@ async def test_closing_the_connection_ends_the_stream_with_a_reason() -> None:async def test_a_close_about_a_room_names_the_room_it_was_about() -> None:"""A client that loses a connection over a room it declared must be told which."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry)registry.claim_room(conn, ROOM_A)@@ -351,7 +352,7 @@ async def test_a_close_about_a_room_names_the_room_it_was_about() -> None:async def test_subscription_change_is_announced() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry)registry.claim_room(conn, ROOM_A)@@ -373,7 +374,7 @@ async def test_subscription_change_is_announced() -> None:async def test_stream_detaches_on_exit_without_killing_the_connection() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry)@@ -388,7 +389,7 @@ async def test_stream_detaches_on_exit_without_killing_the_connection() -> None:@pytest.mark.parametrize("scope", ["single", "all"])async def test_two_connections_receive_the_same_event(scope: str) -> None:"""Non-destructive reads: one reader must not steal from another."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()session = registry.open(@@ -433,7 +434,7 @@ async def test_resume_replays_buffered_events_for_a_room_claimed_at_open() -> Nofirst, skip those events as "not covered", and advance the cursor pastthem — losing exactly what resume is meant to recover."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()seen = buffer.enqueue(AGENT, ROOM_A, _message("before the drop"))@@ -452,7 +453,7 @@ async def test_resume_replays_buffered_events_for_a_room_claimed_at_open() -> Noasync def test_events_for_uncovered_rooms_do_not_block_the_cursor() -> None:"""Skipping is deliberate for rooms this connection does not cover."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry)registry.claim_room(conn, ROOM_A)@@ -474,7 +475,7 @@ async def test_a_cursor_from_before_a_restart_is_reported_not_ignored() -> None:otherwise sit quietly at a position that no longer means anything, lookingcaught up while its history has a hole in it."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()buffer.enqueue(AGENT, ROOM_A, _message("after the restart"))@@ -503,7 +504,7 @@ class TestALapsedHeartbeatStopsDelivery:async def test_the_stream_evicts_when_the_heartbeat_lapses(self) -> None:import time as _time- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry)registry.claim_room(conn, ROOM_A)@@ -527,7 +528,7 @@ class TestALapsedHeartbeatStopsDelivery:"""Otherwise the room slot stays claimed by a connection that is gone."""import time as _time- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry)registry.claim_room(conn, ROOM_A)@@ -560,7 +561,7 @@ class TestFilteredEventsDoNotSpinTheLoop:async def test_the_cursor_advances_past_events_the_filter_excludes(self, monkeypatch: pytest.MonkeyPatch) -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry, delivery_filter="addressed")registry.claim_room(conn, ROOM_A)@@ -586,7 +587,7 @@ class TestFilteredEventsDoNotSpinTheLoop:self,) -> None:"""Advancing past the excluded events must not skip what follows."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry, delivery_filter="addressed")registry.claim_room(conn, ROOM_A)@@ -622,7 +623,7 @@ class TestAConnectionWithNoRoomDoesNotConsume:self, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(stream_module, "KEEPALIVE_INTERVAL_SECONDS", 0.05)- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()# Opened at 0, like a session handed its trigger's position.conn = _open(registry, cursor=0)@@ -643,7 +644,7 @@ class TestAConnectionWithNoRoomDoesNotConsume:self, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(stream_module, "KEEPALIVE_INTERVAL_SECONDS", 0.05)- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry, cursor=0)@@ -666,7 +667,7 @@ class TestAConnectionWithNoRoomDoesNotConsume:async def test_an_all_scope_connection_is_not_parked(self) -> None:"""A watcher holds no room by design and must keep receiving."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry, scope="all", connection_id="watcher")@@ -682,7 +683,7 @@ class TestAConnectionWithNoRoomDoesNotConsume:async def test_replaced_stream_cannot_capture_its_successors_generation() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry)old = event_stream(conn=conn, registry=registry, buffer=buffer, approvals=None)@@ -692,7 +693,7 @@ async def test_replaced_stream_cannot_capture_its_successors_generation() -> Nonasync def test_closed_stream_cannot_detach_a_recreated_connection() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry)old = event_stream(conn=conn, registry=registry, buffer=buffer, approvals=None)@@ -722,13 +723,13 @@ async def test_a_resumed_stream_does_not_replay_a_room_the_agent_was_removed_fronothing left for any reader to be handed. This asserts the property at thereader that has no other defence."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()buffer.enqueue(AGENT, ROOM_A, _message("said before the removal"))buffer.enqueue(AGENT, ROOM_B, _message("still a member here", room=ROOM_B))- # What a kick does, through the two calls `AgentClient.on_removed` makes.+ # What a kick does, through the two calls `AgentConsumer.on_removed` makes.buffer.drop_room(AGENT, ROOM_A)registry.release_room_everywhere(AGENT, ROOM_A)@@ -751,7 +752,7 @@ async def test_a_last_event_id_reconnect_does_not_replay_a_removed_room() -> Nonbeing asked — so it is worth pinning separately from an explicitlyrequested `start_from`."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()seen = buffer.enqueue(AGENT, ROOM_A, _message("before the drop"))@@ -782,7 +783,7 @@ class TestWhatADeliveredEventSaysAboutItsRoom:async def test_a_delivered_event_carries_the_chatter_of_its_own_room(self,) -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry, delivery_filter="addressed")registry.claim_room(conn, ROOM_A)@@ -809,7 +810,7 @@ class TestWhatADeliveredEventSaysAboutItsRoom:Skipping unnotifiable events is what keeps the generator from spinning;it must not double as a claim that the agent has seen them."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry, delivery_filter="addressed")registry.claim_room(conn, ROOM_A)@@ -833,7 +834,7 @@ class TestWhatADeliveredEventSaysAboutItsRoom:async def test_a_room_claimed_after_the_connection_opened_counts_from_there(self,) -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry, delivery_filter="addressed")registry.claim_room(conn, ROOM_A)@@ -855,7 +856,7 @@ class TestWhatADeliveredEventSaysAboutItsRoom:assert frames[1][1]["missed"] == {"count": 1, "reason": None}async def test_a_count_is_absent_rather_than_zero_after_a_restart(self) -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry, cursor=4812) # from a previous liferegistry.claim_room(conn, ROOM_A)@@ -877,7 +878,7 @@ class TestAGapNamesTheRoomsThatLostEvents:""" "Something was dropped" is unactionable across a dozen rooms."""async def test_an_expired_cursor_names_them(self) -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer(max_events_per_agent=2)buffer.enqueue(AGENT, ROOM_A, _message("dropped"))buffer.enqueue(AGENT, ROOM_B, _message("dropped", room=ROOM_B))@@ -898,7 +899,7 @@ class TestAGapNamesTheRoomsThatLostEvents:assert sorted(frames[1][1]["rooms"]) == [ROOM_A, ROOM_B]async def test_a_restart_names_the_rooms_the_connection_covers(self) -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()buffer.enqueue(AGENT, ROOM_A, _message("after the restart"))@@ -922,7 +923,7 @@ class TestAGapNamesTheRoomsThatLostEvents:its sessions go on to claim answering with a fresh zero, which is therestart made invisible in exactly the rooms the agent works in."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()buffer.enqueue(AGENT, ROOM_A, _message("after the restart"))conn = _open(registry, scope="all", cursor=4812)@@ -946,7 +947,7 @@ class TestAGapNamesTheRoomsThatLostEvents:assert "restarted" in delivered[-1][1]["missed"]["reason"]async def test_a_dropped_event_gap_is_confined_to_the_rooms_it_names(self) -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer(max_events_per_agent=1)buffer.enqueue(AGENT, ROOM_A, _message("dropped"))buffer.enqueue(AGENT, ROOM_A, _message("kept"))@@ -966,7 +967,7 @@ class TestAGapNamesTheRoomsThatLostEvents:async def test_a_delivered_event_names_no_session() -> None:"""Routing a room's events to a session is the watcher's, from its own placements."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()buffer = EventBuffer()conn = _open(registry, scope="all")registry.place_session(AGENT, "session-1", ROOM_A, conn.id)@@ -977,3 +978,33 @@ async def test_a_delivered_event_names_no_session() -> None:assert name == "message"assert "session_id" not in data+++async def test_each_delivered_event_counts_as_an_agent_bridge_event_out() -> None:+ registry_metrics = MetricsRegistry()+ install(registry_metrics)+ try:+ registry = AgentConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(registry)+ registry.claim_room(conn, ROOM_A)+ registry.claim_room(conn, ROOM_B)+ buffer.enqueue(AGENT, ROOM_A, _message("one"))+ buffer.enqueue(AGENT, ROOM_B, _message("two", room=ROOM_B))++ stream = event_stream(+ conn=conn, registry=registry, buffer=buffer, approvals=None+ )+ await _take(stream, 3)++ points = {+ payload.name: {+ tuple(sorted(p.attributes.items())): p.value for p in payload.numbers+ }+ for payload in registry_metrics.collect()+ }+ assert points["switch.bridge.events_out"] == {+ (("bridge", "agent"), ("kind", "message"), ("platform", "switch")): 2.0+ }+ finally:+ uninstall()diff --git a/core/tests/switch_core/bridges/agent/protocol/test_sweep_runtime_states_tenant_binding.py b/core/tests/switch_core/bridges/agent/protocol/test_sweep_runtime_states_tenant_binding.pyindex 8b69406de..2778dc76b 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_sweep_runtime_states_tenant_binding.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_sweep_runtime_states_tenant_binding.py@@ -1,4 +1,4 @@-"""`ProtocolService.sweep_runtime_states` (CHOO-2623) spans every tenant by+"""`AgentCore.sweep_runtime_states` (CHOO-2623) spans every tenant bynature: one pass resets every stale runtime-state row anywhere, so the readthat finds them is unscoped. Each row is itself tenant-scoped, so the rest ofthe work for that row — the liveness check and the reset — binds that row's@@ -20,8 +20,8 @@ import uuidimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.db.models import (Agent,AgentRuntimeState,@@ -38,12 +38,12 @@ from switch_core.db.stores.room_store import RoomStorefrom switch_core.tenant_context import current_tenant_id-def _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolService:- svc = object.__new__(ProtocolService)+def _service(session_factory: async_sessionmaker[AsyncSession]) -> AgentCore:+ svc = object.__new__(AgentCore)svc.session_factory = session_factory # type: ignore[attr-defined]# Nothing is registered, so every agent/room pair reads as not live —# the sweep's job is exactly to reset those.- svc.connections = ConnectionRegistry() # type: ignore[attr-defined]+ svc.connections = AgentConnectionRegistry() # type: ignore[attr-defined]svc.agent_session_store = AgentSessionStore() # type: ignore[attr-defined]svc.agent_store = AgentStore() # type: ignore[attr-defined]svc.room_store = RoomStore() # type: ignore[attr-defined]@@ -85,7 +85,7 @@ async def _make_stale_runtime_state()client = Client(tenant_id=tenant_id,- matrix_user_id=f"@agent-{suffix}:test",+ transport_user_id=f"@agent-{suffix}:test",display_name="agent",type="agent",)@@ -104,7 +104,7 @@ async def _make_stale_runtime_state(session.add(agent)room = Room(tenant_id=tenant_id,- matrix_room_id=f"!room-{suffix}:test",+ transport_room_id=f"!room-{suffix}:test",name="room",description="d",)diff --git a/core/tests/switch_core/bridges/agent/protocol/test_threads.py b/core/tests/switch_core/bridges/agent/protocol/test_threads.pyindex 1d5641098..4f036a114 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_threads.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_threads.py@@ -4,8 +4,8 @@ from types import SimpleNamespaceimport pytest-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.transport import HistoryPage, InboundMessagefrom tests.switch_core.transport.fake import FakeTransport@@ -30,15 +30,15 @@ def _ev()-def _service_with_transport(transport: FakeTransport) -> ProtocolService:+def _service_with_transport(transport: FakeTransport) -> AgentCore:client = SimpleNamespace(transport=transport)- svc = object.__new__(ProtocolService)+ svc = object.__new__(AgentCore)# Presence unions the heartbeat rows with the live connections# (CHOO-1857); an empty registry means "rows only".- svc.connections = ConnectionRegistry()+ svc.connections = AgentConnectionRegistry()async def _require_room_member(agent_id: str, room_id: str) -> SimpleNamespace:- return SimpleNamespace(matrix_room_id="!matrix:server")+ return SimpleNamespace(transport_room_id="!matrix:server")svc.require_room_member = _require_room_member # type: ignore[assignment]svc.client_lifecycle = SimpleNamespace( # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/agent/protocol/test_update_room_bridge.py b/core/tests/switch_core/bridges/agent/protocol/test_update_room_bridge.pyindex af0a4115a..8b2788dc6 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_update_room_bridge.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_update_room_bridge.py@@ -5,8 +5,8 @@ from typing import Anyimport pytest-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCoreclass _FakeSession:@@ -55,14 +55,12 @@ class _FakeRoomService:)-def _build_service(- *, bridge_found: bool = True-) -> tuple[ProtocolService, _FakeRoomService]:+def _build_service(*, bridge_found: bool = True) -> tuple[AgentCore, _FakeRoomService]:room_service = _FakeRoomService()- svc = object.__new__(ProtocolService)+ svc = object.__new__(AgentCore)# Presence unions the heartbeat rows with the live connections# (CHOO-1857); an empty registry means "rows only".- svc.connections = ConnectionRegistry()+ svc.connections = AgentConnectionRegistry()svc.session_factory = lambda: _FakeSession() # type: ignore[assignment]svc.room_store = _FakeRoomStore() # type: ignore[assignment]svc.bridge_store = _FakeBridgeStore(bridge_found) # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/agent/server_connectors/test_connector_tenant_binding.py b/core/tests/switch_core/bridges/agent/server_connectors/test_connector_tenant_binding.pyindex 605a47610..8d9a4de00 100644--- a/core/tests/switch_core/bridges/agent/server_connectors/test_connector_tenant_binding.py+++ b/core/tests/switch_core/bridges/agent/server_connectors/test_connector_tenant_binding.py@@ -1,6 +1,6 @@"""A server-side connector acts as its own row's tenant (CHOO-2623).-A connector runs in-process and calls `ProtocolService` directly, so unlike an+A connector runs in-process and calls `AgentCore` directly, so unlike anexternal agent there is no bearer token in front of it to resolve a tenantfrom. Its own row is the answer, and `ServerSideConnectorLifecycleService.start`reads it unscoped — from boot with nothing bound, and from an HTTP requestdiff --git a/core/tests/switch_core/bridges/agent/test_agent_bridge_metrics.py b/core/tests/switch_core/bridges/agent/test_agent_bridge_metrics.pynew file mode 100644index 000000000..94ab2e2c1--- /dev/null+++ b/core/tests/switch_core/bridges/agent/test_agent_bridge_metrics.py@@ -0,0 +1,113 @@+"""The agent bridge reports the same `switch.bridge.*` metrics as a collaboration+bridge, tagged `bridge=agent`, and tags its log lines the same way.++Every agent operation goes through `call_operation`, so that is where an event+in is counted and a call is timed, and where a failure is counted before it is+raised again.+"""++from __future__ import annotations++from collections.abc import Iterator+from types import SimpleNamespace+from typing import Any++import pytest++from switch_core.bridges.agent import app as agent_app+from switch_core.bridges.agent.api import operations+from switch_core.logging_context import current_log_context+from switch_core.observability.metrics import MetricsRegistry, install, uninstall+++def registry() -> Iterator[MetricsRegistry]:+ registry = MetricsRegistry()+ install(registry)+ yield registry+ uninstall()+++def _collect(registry: MetricsRegistry) -> dict[str, list[dict[str, Any]]]:+ """Every point this interval, by metric name. One call: collecting resets."""+ return {+ payload.name: [+ dict(point.attributes) for point in [*payload.numbers, *payload.histograms]+ ]+ for payload in registry.collect()+ }+++def _operation(fn: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ operations, "get_operation", lambda name: SimpleNamespace(fn=fn)+ )+++async def _call(name: str) -> Any:+ return await operations.call_operation(+ operation=name,+ arguments={},+ agent_id="agent-1",+ connection_id=None,+ session=None,+ )+++async def test_an_operation_is_an_event_in_and_a_timed_call(+ registry: MetricsRegistry, monkeypatch: pytest.MonkeyPatch+) -> None:+ async def ok() -> str:+ return "done"++ _operation(ok, monkeypatch)++ assert await _call("post_message") == "done"++ points = _collect(registry)+ assert points["switch.bridge.events_in"] == [+ {"bridge": "agent", "platform": "switch", "event": "post_message"}+ ]+ assert "switch.bridge.call.duration" in points+ assert "switch.bridge.errors" not in points+++async def test_a_failing_operation_is_counted_and_still_raises(+ registry: MetricsRegistry, monkeypatch: pytest.MonkeyPatch+) -> None:+ async def boom() -> None:+ raise ValueError("no such room")++ _operation(boom, monkeypatch)++ with pytest.raises(ValueError, match="no such room"):+ await _call("post_message")++ points = _collect(registry)+ assert points["switch.bridge.errors"] == [+ {"bridge": "agent", "platform": "switch", "direction": "inbound"}+ ]+++ ("path", "bridge"),+ [+ ("/agents/agent-1/events", "agent"),+ ("/mcp/", "agent"),+ ("/gateway/rooms", None),+ ("/health", None),+ ],+)+async def test_only_agent_paths_are_tagged_as_the_agent_bridge(+ path: str, bridge: str | None+) -> None:+ seen: list[str | None] = []++ async def inner(scope: Any, receive: Any, send: Any) -> None:+ seen.append(current_log_context().bridge)++ middleware = agent_app.AgentBridgeLogContextMiddleware(inner)+ await middleware({"type": "http", "path": path}, None, None) # type: ignore[arg-type]++ assert seen == [bridge]+ assert current_log_context().bridge is Nonediff --git a/core/tests/switch_core/bridges/agent/test_api_key_cache.py b/core/tests/switch_core/bridges/agent/test_api_key_cache.pyindex b2bece810..4cf9d29e1 100644--- a/core/tests/switch_core/bridges/agent/test_api_key_cache.py+++ b/core/tests/switch_core/bridges/agent/test_api_key_cache.py@@ -17,8 +17,8 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.agent.api_key_cache import ApiKeyCachefrom switch_core.bridges.agent.auth import BearerAuthMiddleware-from switch_core.bridges.agent.protocol.connections import HEARTBEAT_TTL_SECONDS-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_connections import HEARTBEAT_TTL_SECONDS+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.types import (IntegrationProfile,TaskProtocolConfig,@@ -61,7 +61,7 @@ class _FakeClientLifecycle:async def create_client(self, *, client_type: str, display_name: str) -> Client:async with self._session_factory() as session:client = Client(- matrix_user_id=f"@{display_name}:test",+ transport_user_id=f"@{display_name}:test",display_name=display_name,type=client_type,)@@ -125,7 +125,7 @@ async def _seed_agent(agent_id = ""if with_agent:client = Client(- matrix_user_id=f"@{name}:test",+ transport_user_id=f"@{name}:test",display_name=name,type="agent",)@@ -362,7 +362,7 @@ class TestInvalidation:await mw._resolve_api_key("tok")assert cache.get(_hash("tok")) is not None- svc = _protocol_service(session_factory, cache)+ svc = _agent_core(session_factory, cache)await svc.delete_agent(agent_id=agent_id)assert cache.get(_hash("tok")) is None@@ -380,7 +380,7 @@ class TestInvalidation:# invalidation the retired credential keeps authenticating for the# whole TTL, which is the failure mode this cache must not introduce.cache = ApiKeyCache(ttl_seconds=5, max_entries=8)- svc = _protocol_service(session_factory, cache)+ svc = _agent_core(session_factory, cache)async with session_factory() as session:owner = User(name="o", email="o@test", role="user", password_hash="x")session.add(owner)@@ -414,10 +414,10 @@ class TestInvalidation:assert rotated is not None-def _protocol_service(+def _agent_core(session_factory: async_sessionmaker[AsyncSession], cache: ApiKeyCache-) -> ProtocolService:- svc = object.__new__(ProtocolService)+) -> AgentCore:+ svc = object.__new__(AgentCore)svc.session_factory = session_factory # type: ignore[attr-defined]svc.agent_store = AgentStore() # type: ignore[attr-defined]svc.api_key_store = ApiKeyStore() # type: ignore[attr-defined]@@ -435,7 +435,7 @@ _CONFIG_KWARGS = dict(db_user="postgres",db_password="pw",db_name="switch",- matrix_server_name="switch.local",+ id_server_name="switch.local",agent_registration_token="token",jwt_secret_key="jwt",gateway_admin_email="[email protected]",diff --git a/core/tests/switch_core/bridges/agent/test_bearer_auth_tenant_binding.py b/core/tests/switch_core/bridges/agent/test_bearer_auth_tenant_binding.pyindex 6e2f6a932..4380663ec 100644--- a/core/tests/switch_core/bridges/agent/test_bearer_auth_tenant_binding.py+++ b/core/tests/switch_core/bridges/agent/test_bearer_auth_tenant_binding.py@@ -46,7 +46,7 @@ async def _seed_agent(client = Client(tenant_id=tenant_id,- matrix_user_id="@bearer-agent:test",+ transport_user_id="@bearer-agent:test",display_name="bearer-agent",type="agent",)diff --git a/core/tests/switch_core/bridges/agent/test_command_result_threading.py b/core/tests/switch_core/bridges/agent/test_command_result_threading.pyindex b7af85577..d6c3e6f61 100644--- a/core/tests/switch_core/bridges/agent/test_command_result_threading.py+++ b/core/tests/switch_core/bridges/agent/test_command_result_threading.py@@ -3,7 +3,7 @@ from __future__ import annotationsfrom types import SimpleNamespacefrom switch_core.bridges.agent.commands import _cmd_help, _reply-from switch_core.clients.client_base import ClientBase+from switch_core.clients.consumer import Consumerfrom switch_core.events import CommandEventfrom switch_core.transport import InboundCustomEvent, RoomRef@@ -83,7 +83,7 @@ class TestDispatchPopulatesThreadId:fake_self = SimpleNamespace(_should_ignore=lambda _room, _event: False,- _EVENT_DISPATCH=ClientBase._EVENT_DISPATCH,+ _EVENT_DISPATCH=Consumer._EVENT_DISPATCH,on_command=_on_command,)custom = InboundCustomEvent(@@ -95,7 +95,7 @@ class TestDispatchPopulatesThreadId:event_type="com.switch.command",thread_root_id=thread_root_id,)- await ClientBase._handle_custom_event(fake_self, RoomRef("!m"), custom)+ await Consumer._handle_custom_event(fake_self, RoomRef("!m"), custom)assert len(captured) == 1return captured[0]diff --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 a7a1cfb00..8727edcef 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@@ -192,7 +192,7 @@ def _event(args: str) -> CommandEvent:def _fake_client(*, role_exists: bool) -> SimpleNamespace:sent: list[str] = []- async def _resolve_room_meta(_matrix_room_id: str): # type: ignore[no-untyped-def]+ async def _resolve_room_meta(_transport_room_id: str): # type: ignore[no-untyped-def]return SimpleNamespace(room_id="room-1", name="Feature Room", bridge_id=None)async def _agent_get(_session, _agent_id): # type: ignore[no-untyped-def]diff --git a/core/tests/switch_core/bridges/agent/test_control_commands.py b/core/tests/switch_core/bridges/agent/test_control_commands.pyindex 077b52d13..2b6b06ef9 100644--- a/core/tests/switch_core/bridges/agent/test_control_commands.py+++ b/core/tests/switch_core/bridges/agent/test_control_commands.py@@ -41,7 +41,7 @@ def _client(placed: str | None = None,relayed: list[Any] | None = None,) -> SimpleNamespace:- """Minimal AgentClient stand-in for _dispatch_control_command."""+ """Minimal AgentConsumer stand-in for _dispatch_control_command."""agent = SimpleNamespace(id="agent-1",@@ -52,7 +52,7 @@ def _client(async def _fresh_agent(_session: Any) -> SimpleNamespace:return agent- async def _resolve_room_meta(_matrix_room_id: str) -> SimpleNamespace:+ async def _resolve_room_meta(_transport_room_id: str) -> SimpleNamespace:return SimpleNamespace(room_id="room-1",name="Room",diff --git a/core/tests/switch_core/bridges/agent/test_mediation.py b/core/tests/switch_core/bridges/agent/test_mediation.pyindex f6866bfd9..27b6bedb7 100644--- a/core/tests/switch_core/bridges/agent/test_mediation.py+++ b/core/tests/switch_core/bridges/agent/test_mediation.py@@ -29,7 +29,7 @@ async def _agent(session: AsyncSession) -> Agent:type="agent",)client = Client(- matrix_user_id=f"@{name}:test",+ transport_user_id=f"@{name}:test",display_name=name,type="agent",)diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.pyindex deefef0ff..bce192a92 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py@@ -19,10 +19,10 @@ import pytestfrom switch_core.agent_icon import default_icon_urlfrom switch_core.bridges.collaboration.adapter import (AgentPresentation,- CollaborationAdapter,+ PlatformAdapter,TurnActivity,)-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.discord.adapter import (DiscordAdapter,DiscordConnectionConfig,@@ -96,17 +96,17 @@ def _agent(return SimpleNamespace(name=name, display_name=display_name, icon_url=icon_url)-def _bridge(*agents: SimpleNamespace) -> BridgeCore:- """A BridgeCore with only the two collaborators the resolver and the echo+def _bridge(*agents: SimpleNamespace) -> CollaborationCore:+ """A CollaborationCore with only the two collaborators the resolver and the echocheck touch — the rest of `__init__` needs a live Matrix stack."""- bridge = BridgeCore.__new__(BridgeCore)+ bridge = CollaborationCore.__new__(CollaborationCore)bridge._bridge_tenant_id = "tenant-1"bridge._agent_store = _AgentStore({a.name: a for a in agents}) # type: ignore[assignment]bridge._session_factory = _Session # type: ignore[assignment]return bridge-class _BareAdapter(CollaborationAdapter):+class _BareAdapter(PlatformAdapter):"""Concrete only so it can be instantiated: the label plumbing under testlives on the base class and no platform method is called."""@@ -127,7 +127,7 @@ class _BareAdapter(CollaborationAdapter):def _render_outbound(self, *a: Any, **k: Any) -> Any: ...-class TestBridgeCoreResolver:+class TestCollaborationCoreResolver:async def test_returns_the_agents_display_name(self) -> None:bridge = _bridge(_agent("worker", "Worker Bee"))found = await bridge._agent_presentation("worker")@@ -242,7 +242,7 @@ class TestAdapterLabelSelection:that uploads the bytes rather than passing a link on keeps the responseformat it can accept."""adapter = MattermostAdapter.__new__(MattermostAdapter)- CollaborationAdapter.__init__(adapter)+ PlatformAdapter.__init__(adapter)assert await adapter.agent_icon_url("worker") == default_icon_url("worker", image_format="png"@@ -279,12 +279,12 @@ def test_the_resolver_is_installed_before_the_adapter_starts() -> None:return Nonebridge._load_channel_map = _noop # type: ignore[assignment,method-assign]- bridge._load_existing_puppets = _noop # type: ignore[assignment,method-assign]+ bridge._load_existing_human_actors = _noop # type: ignore[assignment,method-assign]bridge._ensure_channel_captures = _noop # type: ignore[assignment,method-assign]bridge._refresh_channel_types = _noop # type: ignore[assignment,method-assign]bridge._create_agent_identities = _noop # type: ignore[assignment,method-assign]- asyncio.run(BridgeCore.start(bridge))+ asyncio.run(CollaborationCore.start(bridge))assert started == ["started"]assert installed == [bridge._agent_presentation]@@ -322,7 +322,9 @@ class _FakeSlackClient:return {"ts": "301.0"}-def _slack_adapter(bridge: BridgeCore | None) -> tuple[SlackAdapter, _FakeSlackClient]:+def _slack_adapter(+ bridge: CollaborationCore | None,+) -> tuple[SlackAdapter, _FakeSlackClient]:adapter = SlackAdapter(config=SlackConnectionConfig(bot_token="xoxb-test", app_token="xapp-test", workspace_id="T123"@@ -639,7 +641,7 @@ def _gateway_message(def _discord_adapter(- bridge: BridgeCore | None,+ bridge: CollaborationCore | None,) -> tuple[DiscordAdapter, _FakeChannel, _FakeChannel]:adapter = DiscordAdapter(config=DiscordConnectionConfig(bot_token="token", guild_id=str(GUILD_ID))@@ -1037,7 +1039,7 @@ class _FakeTeamsConnector:def _teams_adapter(- bridge: BridgeCore | None,+ bridge: CollaborationCore | None,) -> tuple[TeamsAdapter, _FakeTeamsConnector]:adapter = TeamsAdapter(config=TeamsConnectionConfig(@@ -1245,7 +1247,7 @@ class _FakeTelegramBot:def _telegram_adapter(- bridge: BridgeCore | None,+ bridge: CollaborationCore | None,) -> tuple[TelegramAdapter, _FakeTelegramBot]:adapter = TelegramAdapter(config=TelegramConnectionConfig(@@ -1473,7 +1475,7 @@ MATTERMOST_CHANNEL = "mm-channel-1"def _mattermost_adapter(- bridge: BridgeCore | None,+ bridge: CollaborationCore | None,) -> tuple[MattermostAdapter, list[str]]:"""Mattermost carries the label in two places: the inherited operator ping,covered here, and the per-agent bot's own `display_name`, covered by the@@ -1592,7 +1594,7 @@ class _MattermostBot:def _mattermost_identity_adapter(- bridge: BridgeCore, bots: list[dict[str, Any]], name_display: str | None+ bridge: CollaborationCore, bots: list[dict[str, Any]], name_display: str | None) -> tuple[MattermostAdapter, _MattermostAdmin]:"""An adapter wired for `create_agent_identity`: a fake admin driver, andstubs for the icon upload (its own concern, covered elsewhere) and the botdiff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.py b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.pyindex e016aa8c1..7c423d297 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.py@@ -14,9 +14,9 @@ from typing import Anyfrom switch_core.agent_icon import default_icon_urlfrom switch_core.bridges.collaboration.adapter import (AgentPresentation,- CollaborationAdapter,+ PlatformAdapter,)-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCore_CUSTOM = "https://cdn.example.com/9.x/bottts/png?seed=chosen"@@ -37,8 +37,8 @@ class _AgentStore:return self._agents.get(name)-def _bridge(agents: dict[str, SimpleNamespace]) -> BridgeCore:- bridge = BridgeCore.__new__(BridgeCore)+def _bridge(agents: dict[str, SimpleNamespace]) -> CollaborationCore:+ bridge = CollaborationCore.__new__(CollaborationCore)bridge._bridge_tenant_id = "tenant-1"bridge._agent_store = _AgentStore(agents) # type: ignore[assignment]bridge._session_factory = _Session # type: ignore[assignment]@@ -49,7 +49,7 @@ def _agent(icon_url: str | None) -> SimpleNamespace:return SimpleNamespace(name="worker", display_name=None, icon_url=icon_url)-class _Adapter(CollaborationAdapter):+class _Adapter(PlatformAdapter):"""Concrete only so it can be instantiated — the icon plumbing under testlives entirely on the base class, and none of the platform methods arecalled here."""@@ -71,7 +71,7 @@ class _Adapter(CollaborationAdapter):def _render_outbound(self, *a: Any, **k: Any) -> Any: ...-class TestBridgeCoreResolver:+class TestCollaborationCoreResolver:async def test_returns_the_agents_own_icon(self) -> None:bridge = _bridge({"worker": _agent(_CUSTOM)})found = await bridge._agent_presentation("worker")diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_user_discrimination.py b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_user_discrimination.pyindex 6b534e8bc..589c7ec90 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_user_discrimination.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_user_discrimination.py@@ -2,7 +2,7 @@ from __future__ import annotationsfrom types import SimpleNamespace-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.models import (InboundAgentJoin,InboundMessage,@@ -54,9 +54,9 @@ def _fake_bridge(*, agents: set[str]) -> SimpleNamespace:async def _is_registered_agent(name: str) -> bool:return name in agents- async def _ensure_user_in_matrix_room(**kwargs: str): # noqa: ANN202+ async def _ensure_human_in_room(**kwargs: str): # noqa: ANN202ensure_calls.append(kwargs)- return None # short-circuits the message path after the puppet step+ return None # short-circuits the message path after the human actor stepasync def _handle_agent_joined_channel(join: InboundAgentJoin) -> None:agent_joins.append(join)@@ -68,7 +68,7 @@ def _fake_bridge(*, agents: set[str]) -> SimpleNamespace:_handle_text_answer=_no_text_answer,_repair_placeholder_username=_noop_repair,_is_registered_agent=_is_registered_agent,- _ensure_user_in_matrix_room=_ensure_user_in_matrix_room,+ _ensure_human_in_room=_ensure_human_in_room,_handle_agent_joined_channel=_handle_agent_joined_channel,_maybe_guide_self_mention=_maybe_guide_self_mention,_channel_to_room={"chan-1": ("room-uuid", "!matrix:switch.local")},@@ -84,9 +84,9 @@ def _fake_bridge(*, agents: set[str]) -> SimpleNamespace:async def test_inbound_message_from_agent_is_dropped() -> None:bridge = _fake_bridge(agents={"cc-marketing.chad"})- await BridgeCore._handle_inbound_message(bridge, _msg("cc-marketing.chad"))+ await CollaborationCore._handle_inbound_message(bridge, _msg("cc-marketing.chad"))- # Agent's own echo: never re-imported, never puppeted as a user.+ # Agent's own echo: never re-imported, never given a human actor as a user.assert bridge.ensure_calls == []@@ -94,7 +94,7 @@ async def test_inbound_message_from_third_party_bot_is_bridged() -> None:# Not a registered agent (e.g. a GitHub/CI bot or a human) — must flow in.bridge = _fake_bridge(agents={"cc-marketing.chad"})- await BridgeCore._handle_inbound_message(bridge, _msg("github-ci-bot"))+ await CollaborationCore._handle_inbound_message(bridge, _msg("github-ci-bot"))assert len(bridge.ensure_calls) == 1assert bridge.ensure_calls[0]["external_username"] == "github-ci-bot"@@ -106,17 +106,19 @@ async def test_inbound_message_from_third_party_bot_is_bridged() -> None:async def test_user_join_from_agent_routes_to_agent_join() -> None:bridge = _fake_bridge(agents={"github.phil.conway"})- await BridgeCore._handle_user_joined_channel(bridge, _join("github.phil.conway"))+ await CollaborationCore._handle_user_joined_channel(+ bridge, _join("github.phil.conway")+ )- # Routed to the agent-join path; no external-user puppet created.+ # Routed to the agent-join path; no external-user human actor created.assert [j.agent_name for j in bridge.agent_joins] == ["github.phil.conway"]assert bridge.ensure_calls == []-async def test_user_join_from_human_creates_puppet() -> None:+async def test_user_join_from_human_creates_human_actor() -> None:bridge = _fake_bridge(agents={"github.phil.conway"})- await BridgeCore._handle_user_joined_channel(bridge, _join("alice"))+ await CollaborationCore._handle_user_joined_channel(bridge, _join("alice"))assert bridge.agent_joins == []assert len(bridge.ensure_calls) == 1diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_capture.py b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_capture.pyindex a3fcffaa3..bf5ebcb91 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_capture.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_capture.py@@ -3,9 +3,9 @@ from __future__ import annotationsfrom types import SimpleNamespacefrom typing import Any-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCore-# On startup BridgeCore hands the adapter the bridge's channels so channel+# On startup CollaborationCore hands the adapter the bridge's channels so channel# capture can self-heal (Teams recreates Graph subscriptions; other adapters# no-op). Only rows with both an external channel id and a channel type are# forwarded.@@ -52,7 +52,7 @@ async def test_ensure_channel_captures_forwards_valid_channels() -> None:_bridge_tenant_id="tenant-1",)- await BridgeCore._ensure_channel_captures(bridge)+ await CollaborationCore._ensure_channel_captures(bridge)assert passed == [[@@ -83,6 +83,6 @@ async def test_ensure_channel_captures_noop_without_channels() -> None:_bridge_tenant_id="tenant-1",)- await BridgeCore._ensure_channel_captures(bridge)+ await CollaborationCore._ensure_channel_captures(bridge)assert calls == []diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.pyindex 30d7504fa..3a00c889b 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py@@ -13,7 +13,7 @@ import asynciofrom types import SimpleNamespacefrom typing import Any-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCoreOLD_ID = "-4912345678"NEW_ID = "-1009876543210"@@ -57,8 +57,8 @@ class _Session:return None-def _make_bridge(rooms: dict[str, SimpleNamespace]) -> BridgeCore:- bridge = BridgeCore.__new__(BridgeCore)+def _make_bridge(rooms: dict[str, SimpleNamespace]) -> CollaborationCore:+ bridge = CollaborationCore.__new__(CollaborationCore)bridge._bridge_id = "bridge-1"bridge._bridge_tenant_id = "tenant-1"bridge._room_tenants = {}@@ -73,7 +73,7 @@ def _make_bridge(rooms: dict[str, SimpleNamespace]) -> BridgeCore:def _room(room_id: str = "room-uuid") -> SimpleNamespace:return SimpleNamespace(- id=room_id, tenant_id="tenant-1", matrix_room_id=f"!{room_id}:switch.local"+ id=room_id, tenant_id="tenant-1", transport_room_id=f"!{room_id}:switch.local")@@ -107,12 +107,12 @@ def test_the_handler_is_installed_before_the_adapter_starts() -> None:return Nonebridge._load_channel_map = _noop # type: ignore[assignment,method-assign]- bridge._load_existing_puppets = _noop # type: ignore[assignment,method-assign]+ bridge._load_existing_human_actors = _noop # type: ignore[assignment,method-assign]bridge._ensure_channel_captures = _noop # type: ignore[assignment,method-assign]bridge._refresh_channel_types = _noop # type: ignore[assignment,method-assign]bridge._create_agent_identities = _noop # type: ignore[assignment,method-assign]- asyncio.run(BridgeCore.start(bridge))+ asyncio.run(CollaborationCore.start(bridge))assert started == ["started"]assert installed == [bridge._handle_channel_migrated]@@ -121,24 +121,24 @@ def test_the_handler_is_installed_before_the_adapter_starts() -> None:def test_the_room_moves_onto_the_new_channel_id() -> None:room = _room()bridge = _make_bridge({OLD_ID: room})- bridge._channel_to_room[OLD_ID] = (room.id, room.matrix_room_id)- bridge._room_to_channel[(room.id, room.matrix_room_id)] = OLD_ID+ bridge._channel_to_room[OLD_ID] = (room.id, room.transport_room_id)+ bridge._room_to_channel[(room.id, room.transport_room_id)] = OLD_ID- asyncio.run(BridgeCore._handle_channel_migrated(bridge, OLD_ID, NEW_ID))+ asyncio.run(CollaborationCore._handle_channel_migrated(bridge, OLD_ID, NEW_ID))store: Any = bridge._room_storeassert store.repoints == [(room.id, NEW_ID)]# The in-memory routing table is what inbound traffic is matched against,# so a committed row alone would not fix anything until the next restart.- assert bridge._channel_to_room == {NEW_ID: (room.id, room.matrix_room_id)}- assert bridge._room_to_channel == {(room.id, room.matrix_room_id): NEW_ID}+ assert bridge._channel_to_room == {NEW_ID: (room.id, room.transport_room_id)}+ assert bridge._room_to_channel == {(room.id, room.transport_room_id): NEW_ID}def test_the_chat_is_told_its_room_followed_it() -> None:room = _room()bridge = _make_bridge({OLD_ID: room})- asyncio.run(BridgeCore._handle_channel_migrated(bridge, OLD_ID, NEW_ID))+ asyncio.run(CollaborationCore._handle_channel_migrated(bridge, OLD_ID, NEW_ID))adapter: Any = bridge._adapterassert [channel for channel, _ in adapter.notices] == [NEW_ID]@@ -147,7 +147,7 @@ def test_the_chat_is_told_its_room_followed_it() -> None:def test_a_migration_of_an_unbridged_channel_is_a_no_op() -> None:bridge = _make_bridge({})- asyncio.run(BridgeCore._handle_channel_migrated(bridge, OLD_ID, NEW_ID))+ asyncio.run(CollaborationCore._handle_channel_migrated(bridge, OLD_ID, NEW_ID))store: Any = bridge._room_storeadapter: Any = bridge._adapter@@ -163,7 +163,7 @@ def test_a_new_id_another_room_already_holds_is_refused() -> None:occupant = _room("room-new")bridge = _make_bridge({OLD_ID: old_room, NEW_ID: occupant})- asyncio.run(BridgeCore._handle_channel_migrated(bridge, OLD_ID, NEW_ID))+ asyncio.run(CollaborationCore._handle_channel_migrated(bridge, OLD_ID, NEW_ID))store: Any = bridge._room_storeadapter: Any = bridge._adapterdiff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_type_correction.py b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_type_correction.pyindex aea208c07..2168150b9 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_type_correction.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_type_correction.py@@ -10,8 +10,8 @@ from typing import Anyimport pytest-from switch_core.bridges.collaboration.adapter import CollaborationAdapter-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.adapter import PlatformAdapter+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.tenant_context import current_tenant_id, tenant_scope@@ -107,7 +107,7 @@ async def test_a_learned_type_corrects_this_bridges_rooms(bridge = _bridge(store, _Adapter())with caplog.at_level(logging.WARNING):- await BridgeCore._record_channel_type(+ await CollaborationCore._record_channel_type(bridge, # type: ignore[arg-type]"19:[email protected]",channel_type, # type: ignore[arg-type]@@ -152,7 +152,7 @@ async def test_startup_rereads_every_live_channel_room(adapter = _Adapter()store = _RoomStore(rooms, [])- await BridgeCore._refresh_channel_types(_bridge(store, adapter)) # type: ignore[arg-type]+ await CollaborationCore._refresh_channel_types(_bridge(store, adapter)) # type: ignore[arg-type]assert adapter.refreshed == refreshedassert store.tenants == ["tenant-1"]@@ -160,7 +160,7 @@ async def test_startup_rereads_every_live_channel_room(async def test_adapters_have_nothing_to_refresh_by_default() -> None:adapter: Any = SimpleNamespace()- await CollaborationAdapter.refresh_channel_types(adapter, ["C1"])+ await PlatformAdapter.refresh_channel_types(adapter, ["C1"])# ── Wiring in start() and stop() ─────────────────────────────────────────────@@ -187,8 +187,8 @@ class _StartableAdapter:return None-def _startable_core(refresh: Any) -> tuple[BridgeCore, _StartableAdapter]:- core = object.__new__(BridgeCore)+def _startable_core(refresh: Any) -> tuple[CollaborationCore, _StartableAdapter]:+ core = object.__new__(CollaborationCore)adapter = _StartableAdapter()async def _noop() -> None:@@ -200,7 +200,7 @@ def _startable_core(refresh: Any) -> tuple[BridgeCore, _StartableAdapter]:"_identity_task": None,"_channel_type_refresh_task": None,"_load_channel_map": _noop,- "_load_existing_puppets": _noop,+ "_load_existing_human_actors": _noop,"_ensure_channel_captures": _noop,"_create_agent_identities": _noop,"_refresh_channel_types": refresh,diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_duplicate_room_race.py b/core/tests/switch_core/bridges/collaboration/test_bridge_duplicate_room_race.pyindex 5ee8f35e0..85ed4d3dc 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_duplicate_room_race.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_duplicate_room_race.py@@ -5,7 +5,7 @@ from typing import Anyfrom sqlalchemy.exc import IntegrityError-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.models import InboundAppJoin# CHOO-1660: creating a Slack-bridged room provisions a channel; the bot@@ -15,12 +15,12 @@ from switch_core.bridges.collaboration.models import InboundAppJoin# guard, the idempotent DB adoption, and the unique-constraint backstop.-def _make_bridge(**overrides: Any) -> BridgeCore:- """A BridgeCore with only the attributes the auto-room-creation path+def _make_bridge(**overrides: Any) -> CollaborationCore:+ """A CollaborationCore with only the attributes the auto-room-creation pathtouches, so the real methods run without the full dependency graph."""created_configs: list[Any] = []room = SimpleNamespace(- id="room-uuid", tenant_id="tenant-1", matrix_room_id="!m:switch.local"+ id="room-uuid", tenant_id="tenant-1", transport_room_id="!m:switch.local")async def create_room(config: Any) -> SimpleNamespace:@@ -39,7 +39,7 @@ def _make_bridge(**overrides: Any) -> BridgeCore:async def _adopt_existing_room(channel_id: str) -> tuple[str, str] | None:return None- bridge = BridgeCore.__new__(BridgeCore)+ bridge = CollaborationCore.__new__(CollaborationCore)bridge._provisioning_channels = set()bridge._channel_to_room = {}bridge._room_to_channel = {}@@ -74,7 +74,7 @@ async def test_provisioning_channel_is_not_re_created() -> None:# NOT create a second room; it defers to the in-flight create_room.bridge = _make_bridge(_provisioning_channels={"C1"})- result = await BridgeCore._create_room_for_channel(+ result = await CollaborationCore._create_room_for_channel(bridge,channel_id="C1",channel_type="channel_public",@@ -91,7 +91,7 @@ async def test_provisioning_channel_returns_existing_mapping() -> None:_channel_to_room={"C1": ("room-x", "!x:switch.local")},)- result = await BridgeCore._create_room_for_channel(+ result = await CollaborationCore._create_room_for_channel(bridge,channel_id="C1",channel_type="channel_public",@@ -107,7 +107,7 @@ async def test_existing_db_room_is_adopted_not_recreated() -> None:bridge = _make_bridge(_adopt_existing_room=_adopt)- result = await BridgeCore._create_room_for_channel(+ result = await CollaborationCore._create_room_for_channel(bridge,channel_id="C1",channel_type="channel_public",@@ -137,7 +137,7 @@ async def test_integrity_error_falls_back_to_existing_room() -> None:_room_service=SimpleNamespace(create_room=create_room),)- result = await BridgeCore._create_room_for_channel(+ result = await CollaborationCore._create_room_for_channel(bridge,channel_id="C1",channel_type="channel_public",@@ -152,7 +152,7 @@ async def test_app_join_during_provisioning_creates_no_room() -> None:# still provisioning the channel. It must not spawn a duplicate room.bridge = _make_bridge(_provisioning_channels={"C1"})- await BridgeCore._handle_app_joined_channel(+ await CollaborationCore._handle_app_joined_channel(bridge,InboundAppJoin(channel_id="C1",@@ -168,7 +168,7 @@ async def test_adopt_existing_room_registers_mapping() -> None:# The real _adopt_existing_room: a DB hit registers the in-memory mapping# and returns the room, so subsequent lookups short-circuit.room = SimpleNamespace(- id="db-room", tenant_id="tenant-1", matrix_room_id="!db:switch.local"+ id="db-room", tenant_id="tenant-1", transport_room_id="!db:switch.local")class _Session:@@ -184,7 +184,7 @@ async def test_adopt_existing_room_registers_mapping() -> None:) -> Any:return room if channel_id == "C1" else None- bridge = BridgeCore.__new__(BridgeCore)+ bridge = CollaborationCore.__new__(CollaborationCore)bridge._channel_to_room = {}bridge._room_to_channel = {}bridge._room_tenants = {}diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.py b/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.pyindex 5bc526f46..3da8db100 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.py@@ -12,7 +12,7 @@ from typing import Anyimport pytest-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCoreclass _FakeAdapter:@@ -39,9 +39,9 @@ class _FakeAdapter:self.stopped = True-def _core(provision: Any) -> tuple[BridgeCore, _FakeAdapter]:- """A BridgeCore with everything start() touches stubbed but the task logic."""- core = object.__new__(BridgeCore)+def _core(provision: Any) -> tuple[CollaborationCore, _FakeAdapter]:+ """A CollaborationCore with everything start() touches stubbed but the task logic."""+ core = object.__new__(CollaborationCore)adapter = _FakeAdapter()core._bridge_type = "slack" # type: ignore[attr-defined]core._adapter = adapter # type: ignore[attr-defined]@@ -52,7 +52,7 @@ def _core(provision: Any) -> tuple[BridgeCore, _FakeAdapter]:return Nonecore._load_channel_map = _noop # type: ignore[assignment]- core._load_existing_puppets = _noop # type: ignore[assignment]+ core._load_existing_human_actors = _noop # type: ignore[assignment]core._ensure_channel_captures = _noop # type: ignore[assignment]core._refresh_channel_types = _noop # type: ignore[assignment]core._handle_channel_migrated = None # type: ignore[attr-defined]diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.pyindex 4b49d8d47..3a298b613 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py@@ -3,7 +3,7 @@ from __future__ import annotationsfrom types import SimpleNamespacefrom typing import Any-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.models import (Attachment,AttachmentFailure,@@ -11,8 +11,8 @@ from switch_core.bridges.collaboration.models import ()-class _FakePuppet:- matrix_user_id = "@puppet:s"+class _FakeHumanActor:+ transport_user_id = "@human actor:s"def __init__(self) -> None:self.uploads: list[dict[str, Any]] = []@@ -25,7 +25,7 @@ class _FakePuppet:async def send_media(self,- matrix_room_id,+ transport_room_id,mxc,filename,mimetype,@@ -39,7 +39,7 @@ class _FakePuppet:): # noqa: ANN001, ANN201self.media.append({- "matrix_room_id": matrix_room_id,+ "matrix_room_id": transport_room_id,"mxc": mxc,"filename": filename,"mimetype": mimetype,@@ -53,7 +53,7 @@ class _FakePuppet:return f"$evt-{len(self.media) - 1}"async def send_message(- self, matrix_room_id, content, *, metered, format=None, thread_root_id=None+ self, transport_room_id, content, *, metered, format=None, thread_root_id=None): # noqa: ANN001, ANN201, A002self.messages.append({"content": content, "thread_root_id": thread_root_id})return "$evt-text"@@ -70,14 +70,14 @@ async def _no_text_answer(_msg: object) -> None:def _fake_bridge() -> SimpleNamespace:- puppet = _FakePuppet()+ human_actor = _FakeHumanActor()recorded: list[dict[str, str]] = []async def _is_registered_agent(_name: str) -> bool:return False- async def _ensure_user_in_matrix_room(**_kwargs: Any) -> _FakePuppet:- return puppet+ async def _ensure_human_in_room(**_kwargs: Any) -> _FakeHumanActor:+ return human_actorasync def _record_message_map(**kwargs: str) -> None:recorded.append(kwargs)@@ -92,9 +92,9 @@ def _fake_bridge() -> SimpleNamespace:_adapter=_FakeAdapter(),_channel_to_room={"chan-1": ("room-1", "!room:s")},_is_registered_agent=_is_registered_agent,- _ensure_user_in_matrix_room=_ensure_user_in_matrix_room,+ _ensure_human_in_room=_ensure_human_in_room,_record_message_map=_record_message_map,- puppet=puppet,+ human_actor=human_actor,recorded=recorded,)return ns@@ -125,7 +125,7 @@ def _attachment(filename: str, mimetype: str) -> Attachment:async def test_three_attachments_are_stamped_as_one_group() -> None:bridge = _fake_bridge()- await BridgeCore._handle_inbound_message(+ await CollaborationCore._handle_inbound_message(bridge,_msg(content="three files",@@ -137,7 +137,7 @@ async def test_three_attachments_are_stamped_as_one_group() -> None:),)- media = bridge.puppet.media+ media = bridge.human_actor.mediaassert len(media) == 3group_ids = {m["group"]["id"] for m in media}@@ -158,7 +158,7 @@ async def test_three_attachments_are_stamped_as_one_group() -> None:"external_post_id": "post-1",}]- assert bridge.puppet.messages == []+ assert bridge.human_actor.messages == []async def test_single_attachment_carries_no_group_marker() -> None:@@ -166,19 +166,19 @@ async def test_single_attachment_carries_no_group_marker() -> None:# a complete message and never buffers it.bridge = _fake_bridge()- await BridgeCore._handle_inbound_message(+ await CollaborationCore._handle_inbound_message(bridge, _msg(attachments=[_attachment("cat.png", "image/png")]))- assert len(bridge.puppet.media) == 1- assert bridge.puppet.media[0]["group"] is None- assert bridge.puppet.media[0]["caption"] == "here you go"+ assert len(bridge.human_actor.media) == 1+ assert bridge.human_actor.media[0]["group"] is None+ assert bridge.human_actor.media[0]["caption"] == "here you go"async def test_attachment_failures_are_disclosed_alongside_text() -> None:bridge = _fake_bridge()- await BridgeCore._handle_inbound_message(+ await CollaborationCore._handle_inbound_message(bridge,_msg(content="see attached",@@ -188,7 +188,7 @@ async def test_attachment_failures_are_disclosed_alongside_text() -> None:),)- body = bridge.puppet.messages[0]["content"]+ body = bridge.human_actor.messages[0]["content"]assert body.startswith("see attached")assert "huge.zip" in bodyassert "too large" in body@@ -200,7 +200,7 @@ async def test_attachment_failures_are_disclosed_when_text_is_empty() -> None:# in the room — never a silent drop.bridge = _fake_bridge()- await BridgeCore._handle_inbound_message(+ await CollaborationCore._handle_inbound_message(bridge,_msg(content=" ",@@ -211,7 +211,7 @@ async def test_attachment_failures_are_disclosed_when_text_is_empty() -> None:),)- body = bridge.puppet.messages[0]["content"]+ body = bridge.human_actor.messages[0]["content"]assert body.splitlines() == ["_attachment not relayed: huge.zip — too large_","_attachment not relayed: broken.pdf — download failed_",@@ -221,7 +221,7 @@ async def test_attachment_failures_are_disclosed_when_text_is_empty() -> None:async def test_attachment_failures_ride_on_the_caption_of_relayed_media() -> None:bridge = _fake_bridge()- await BridgeCore._handle_inbound_message(+ await CollaborationCore._handle_inbound_message(bridge,_msg(content="two files, one failed",@@ -232,7 +232,7 @@ async def test_attachment_failures_ride_on_the_caption_of_relayed_media() -> Non),)- assert bridge.puppet.messages == []- caption = bridge.puppet.media[0]["caption"]+ assert bridge.human_actor.messages == []+ caption = bridge.human_actor.media[0]["caption"]assert "two files, one failed" in captionassert "huge.zip" in captiondiff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_tenant_binding.py b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_tenant_binding.pyindex 0b8289b4b..07c198ee8 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_tenant_binding.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_tenant_binding.py@@ -31,7 +31,7 @@ from typing import Anyimport pytest-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.tenant_context import current_tenant_id, tenant_scopeBRIDGE_TENANT = "tenant-bridge"@@ -53,8 +53,8 @@ class _ExplodingSessionFactory:)-def _bridge() -> BridgeCore:- bridge = BridgeCore.__new__(BridgeCore)+def _bridge() -> CollaborationCore:+ bridge = CollaborationCore.__new__(CollaborationCore)bridge._bridge_id = "bridge-1"bridge._bridge_tenant_id = BRIDGE_TENANTbridge._bridge_type = "mattermost"@@ -176,8 +176,8 @@ async def test_the_dispatch_style_cannot_change_the_tenant() -> None:assert seen == [ROOM_TENANT, ROOM_TENANT]-class TestAPuppetIsMintedInTheBridgesTenant:- """A puppet is per-bridge and reused for every room the person it stands+class TestAHumanActorIsMintedInTheBridgesTenant:+ """A human actor is per-bridge and reused for every room the person it standsfor ever speaks in, so it cannot be stamped with the tenant of whicheverroom happened to trigger it first. The rooms a bridge carries are all inits tenant (`rooms` keys to `collaboration_bridges` on `tenant_id`), so@@ -185,39 +185,41 @@ class TestAPuppetIsMintedInTheBridgesTenant:"""async def test_the_identity_is_created_under_the_bridges_tenant(self) -> None:- bridge = BridgeCore.__new__(BridgeCore)+ bridge = CollaborationCore.__new__(CollaborationCore)bridge._bridge_id = "bridge-1"bridge._bridge_tenant_id = BRIDGE_TENANTbridge._bridge_type = "mattermost"- bridge._puppet_locks = {}- bridge._user_puppets = {}- bridge._puppet_matrix_ids = set()+ bridge._human_actor_locks = {}+ bridge._human_actors = {}+ bridge._human_user_ids = set()seen: list[str | None] = []async def _locked(external_user_id: str, external_username: str) -> str:seen.append(current_tenant_id())return "client-1"- bridge._create_puppet_locked = _locked # type: ignore[assignment]+ bridge._create_human_actor_locked = _locked # type: ignore[assignment]# Reached from inside an inbound event for a room — the binding the- # puppet must *not* adopt, were the two ever to differ.+ # human actor must *not* adopt, were the two ever to differ.with tenant_scope(ROOM_TENANT):- assert await bridge._create_puppet("U1", "alice") == "client-1"+ assert await bridge._create_human_actor("U1", "alice") == "client-1"assert seen == [BRIDGE_TENANT]- async def test_a_cached_puppet_is_returned_without_reminting(self) -> None:- bridge = BridgeCore.__new__(BridgeCore)+ async def test_a_cached_human_actor_is_returned_without_reminting(self) -> None:+ bridge = CollaborationCore.__new__(CollaborationCore)bridge._bridge_tenant_id = BRIDGE_TENANT- bridge._puppet_locks = {}- bridge._user_puppets = {"U1": "client-1"}+ bridge._human_actor_locks = {}+ bridge._human_actors = {"U1": "client-1"}# The cache check lives inside the locked half, so this proves the# split did not move it out from under the lock.- bridge._create_puppet_locked = BridgeCore._create_puppet_locked.__get__(bridge) # type: ignore[assignment]+ bridge._create_human_actor_locked = (+ CollaborationCore._create_human_actor_locked.__get__(bridge)+ ) # type: ignore[assignment]- assert await bridge._create_puppet("U1", "alice") == "client-1"+ assert await bridge._create_human_actor("U1", "alice") == "client-1"@pytest.mark.parametrize("tenant", [BRIDGE_TENANT, ROOM_TENANT])@@ -234,11 +236,11 @@ async def test_the_mapping_records_whatever_tenant_it_is_given(tenant: str) -> Nclass TestBridgeLevelWorkBindsTheBridgesTenant:"""Everything a bridge does that is not for one room in particular. All of- it is reached with nothing bound — from `BridgeCore.start`, which the+ it is reached with nothing bound — from `CollaborationCore.start`, which thebridge's task calls after unbinding, or from a callback the adapter holdsand invokes on its own task."""- def _bridge_with_store(self, seen: list[str | None]) -> BridgeCore:+ def _bridge_with_store(self, seen: list[str | None]) -> CollaborationCore:class _Session:async def __aenter__(self) -> Any:seen.append(current_tenant_id())@@ -254,7 +256,7 @@ class TestBridgeLevelWorkBindsTheBridgesTenant:async def get_all(self, session: Any) -> list[Any]:return []- bridge = BridgeCore.__new__(BridgeCore)+ bridge = CollaborationCore.__new__(CollaborationCore)bridge._bridge_id = "bridge-1"bridge._bridge_tenant_id = BRIDGE_TENANTbridge._bridge_type = "mattermost"@@ -275,7 +277,7 @@ class TestBridgeLevelWorkBindsTheBridgesTenant:assert seen == [BRIDGE_TENANT]async def test_the_identity_task_unbinds_and_then_binds_it(self) -> None:- """The provisioning task is spawned from `BridgeCore.start`; it must+ """The provisioning task is spawned from `CollaborationCore.start`; it mustnot keep whatever created it, and the read it does must still be thebridge's."""seen: list[str | None] = []diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_lobby_deprecation.py b/core/tests/switch_core/bridges/collaboration/test_bridge_lobby_deprecation.pyindex 358fa2df9..3c185b48c 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_lobby_deprecation.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_lobby_deprecation.py@@ -2,7 +2,7 @@ from __future__ import annotationsfrom types import SimpleNamespace-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.models import InboundMessage@@ -47,7 +47,7 @@ async def test_lobby_message_posts_deprecation_notice() -> None:adapter = _adapter_fake()bridge = SimpleNamespace(_adapter=adapter)- await BridgeCore._handle_lobby_message(bridge, _msg("lobby"))+ await CollaborationCore._handle_lobby_message(bridge, _msg("lobby"))assert len(adapter.notices) == 1channel_id, content, thread_root_id = adapter.notices[0]@@ -71,22 +71,22 @@ async def test_inbound_lobby_message_short_circuits_routing() -> None:async def _handle_lobby_message(msg: InboundMessage) -> None:handled.append(msg)- async def _ensure_user_in_matrix_room(**kwargs: str) -> None:+ async def _ensure_human_in_room(**kwargs: str) -> None:ensure_calls.append(kwargs)return Nonebridge = SimpleNamespace(_is_registered_agent=_is_registered_agent,_handle_lobby_message=_handle_lobby_message,- _ensure_user_in_matrix_room=_ensure_user_in_matrix_room,+ _ensure_human_in_room=_ensure_human_in_room,_handle_text_answer=_no_text_answer,_channel_to_room={},_channel_locks={},)- await BridgeCore._handle_inbound_message(bridge, _msg("lobby"))+ await CollaborationCore._handle_inbound_message(bridge, _msg("lobby"))- # Routed to the deprecation handler; never created a room / puppet.+ # Routed to the deprecation handler; never created a room / human actor.assert len(handled) == 1assert ensure_calls == []@@ -114,7 +114,7 @@ async def test_inbound_non_lobby_message_is_not_short_circuited() -> None:_channel_locks={},)- await BridgeCore._handle_inbound_message(bridge, _msg("channel_public"))+ await CollaborationCore._handle_inbound_message(bridge, _msg("channel_public"))# A normal channel message does not hit the lobby deprecation handler.assert handled == []diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_mention_resolution.py b/core/tests/switch_core/bridges/collaboration/test_bridge_mention_resolution.pyindex 648c0e119..183853614 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_mention_resolution.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_mention_resolution.py@@ -6,7 +6,7 @@ from contextlib import asynccontextmanagerfrom types import SimpleNamespacefrom typing import Any-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.slack.adapter import (SlackAdapter,SlackConnectionConfig,@@ -53,7 +53,7 @@ def _session_factory() -> Any:def _loading_bridge(adapter: SlackAdapter, users: list[SimpleNamespace]) -> Any:- """A BridgeCore stand-in with just what `_load_existing_puppets` touches."""+ """A CollaborationCore stand-in with just what `_load_existing_human_actors` touches."""async def _get_by_bridge(_session: object, bridge_id: str) -> list[SimpleNamespace]:assert bridge_id == BRIDGE_ID@@ -70,8 +70,8 @@ def _loading_bridge(adapter: SlackAdapter, users: list[SimpleNamespace]) -> Any:_external_user_store=SimpleNamespace(get_by_bridge=_get_by_bridge),_client_store=SimpleNamespace(get=_get_client),_client_lifecycle=SimpleNamespace(get=lambda _id: None),- _user_puppets={},- _puppet_matrix_ids=set(),+ _human_actors={},+ _human_user_ids=set(),)@@ -82,7 +82,7 @@ async def test_startup_priming_makes_a_never_seen_user_mentionable() -> None:# Nothing has posted since startup, so the live-resolution path has not run.assert adapter.translate_outbound("@doe.jane ping") == "@doe.jane ping"- await BridgeCore._load_existing_puppets(bridge)+ await CollaborationCore._load_existing_human_actors(bridge)assert adapter.translate_outbound("@doe.jane ping") == "<@U123> ping"@@ -93,7 +93,7 @@ async def test_priming_resolves_a_handle_with_capitals() -> None:adapter, [_external_user("Timo.Meyer", "U456", "client-2")])- await BridgeCore._load_existing_puppets(bridge)+ await CollaborationCore._load_existing_human_actors(bridge)# The mention pattern and the lookup are both case-insensitive: Slack handles# are, and the token a sender types need not match the stored casing.@@ -115,16 +115,16 @@ async def test_app_rows_are_skipped_while_human_rows_are_primed() -> None:],)- await BridgeCore._load_existing_puppets(bridge)+ await CollaborationCore._load_existing_human_actors(bridge)assert adapter.translate_outbound("@datadog alert") == "@datadog alert"assert adapter.translate_outbound("@doe.jane alert") == "<@U123> alert"-async def test_new_puppet_is_mentionable_without_waiting_for_a_restart() -> None:+async def test_new_human_actor_is_mentionable_without_waiting_for_a_restart() -> None:adapter = _adapter()created_client = SimpleNamespace(- client_id="client-9", matrix_user_id="@ext_new:switch.local"+ client_id="client-9", transport_user_id="@ext_new:switch.local")async def _get_by_name(_session: object, _name: str) -> None:@@ -142,18 +142,18 @@ async def test_new_puppet_is_mentionable_without_waiting_for_a_restart() -> None_bridge_type="slack",_bridge_tenant_id="tenant-1",_session_factory=_session_factory(),- _puppet_locks={},- _user_puppets={},- _puppet_matrix_ids=set(),+ _human_actor_locks={},+ _human_actors={},+ _human_user_ids=set(),_agent_store=SimpleNamespace(get_by_name=_get_by_name),_client_lifecycle=SimpleNamespace(create_and_start=_create_and_start),_external_user_store=SimpleNamespace(create=_create),)- bridge._create_puppet_locked = functools.partial(- BridgeCore._create_puppet_locked, bridge+ bridge._create_human_actor_locked = functools.partial(+ CollaborationCore._create_human_actor_locked, bridge)- await BridgeCore._create_puppet(bridge, "U789", "new.person")+ await CollaborationCore._create_human_actor(bridge, "U789", "new.person")assert adapter.translate_outbound("@new.person welcome") == "<@U789> welcome"diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_metrics.py b/core/tests/switch_core/bridges/collaboration/test_bridge_metrics.pyindex f92e15459..f5cab7d3a 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_metrics.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_metrics.py@@ -2,7 +2,7 @@Inbound at `_traced`, the choke point every platform event goes through;outbound at the relay rather than the top of the handler, which returns early-for a puppet's own echo and for a room with no channel mapping.+for a human actor's own echo and for a room with no channel mapping.The failure counters matter more than the volume ones: an inbound failure is amessage a person sent that nobody received.@@ -16,7 +16,7 @@ from typing import Anyimport pytest-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.observability.metrics import MetricsRegistry, install, uninstallBRIDGE_TENANT = "tenant-bridge"@@ -30,8 +30,8 @@ def registry() -> Iterator[MetricsRegistry]:uninstall()-def _bridge() -> BridgeCore:- bridge = BridgeCore.__new__(BridgeCore)+def _bridge() -> CollaborationCore:+ bridge = CollaborationCore.__new__(CollaborationCore)bridge._bridge_id = "bridge-1"bridge._bridge_tenant_id = BRIDGE_TENANTbridge._bridge_type = "slack"@@ -71,8 +71,8 @@ async def test_each_inbound_event_kind_is_counted_separately(registry) -> None:await bridge._traced("command", _handler)(_event())assert _points(registry, "switch.bridge.events_in") == {- (("event", "message"), ("platform", "slack")): 2.0,- (("event", "command"), ("platform", "slack")): 1.0,+ (("bridge", "collaboration"), ("event", "message"), ("platform", "slack")): 2.0,+ (("bridge", "collaboration"), ("event", "command"), ("platform", "slack")): 1.0,}@@ -89,7 +89,11 @@ async def test_a_failing_inbound_handler_is_counted_and_still_raises(# Counted and re-raised unchanged: whoever handled it before still does.assert _points(registry, "switch.bridge.errors") == {- (("direction", "inbound"), ("platform", "slack")): 1.0+ (+ ("bridge", "collaboration"),+ ("direction", "inbound"),+ ("platform", "slack"),+ ): 1.0}@@ -100,7 +104,7 @@ def test_an_outbound_relay_is_counted(registry) -> None:passassert _points(registry, "switch.bridge.events_out") == {- (("kind", "message"), ("platform", "slack")): 1.0+ (("bridge", "collaboration"), ("kind", "message"), ("platform", "slack")): 1.0}@@ -113,12 +117,16 @@ def test_a_failing_outbound_relay_is_counted_and_still_raises(registry) -> None:collected = _collect(registry)assert collected["switch.bridge.errors"] == {- (("direction", "outbound"), ("platform", "slack")): 1.0+ (+ ("bridge", "collaboration"),+ ("direction", "outbound"),+ ("platform", "slack"),+ ): 1.0}# Still counted as attempted: the rate of attempts is what the failure# rate is a fraction of.assert collected["switch.bridge.events_out"] == {- (("kind", "media"), ("platform", "slack")): 1.0+ (("bridge", "collaboration"), ("kind", "media"), ("platform", "slack")): 1.0}diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_no_agents_notice.py b/core/tests/switch_core/bridges/collaboration/test_bridge_no_agents_notice.pyindex d681b37f7..e67c65657 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_no_agents_notice.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_no_agents_notice.py@@ -3,7 +3,7 @@ from __future__ import annotationsfrom types import SimpleNamespacefrom typing import Any-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.discord.adapter import (DiscordAdapter,DiscordConnectionConfig,@@ -24,7 +24,7 @@ from switch_core.bridges.collaboration.telegram.adapter import (def _fake_bridge(*, agent_ids: list[str], slash_hint: str | None = None): # noqa: ANN202notices: list[tuple[str, str, str | None]] = []room = SimpleNamespace(- id="room-uuid", tenant_id="tenant-1", matrix_room_id="!m:switch.local"+ id="room-uuid", tenant_id="tenant-1", transport_room_id="!m:switch.local")class _Adapter:@@ -56,7 +56,7 @@ def _fake_bridge(*, agent_ids: list[str], slash_hint: str | None = None): # noqreturn agent_idsdef add_room_mapping(- room_id: str, matrix_room_id: str, channel_id: str, tenant_id: str+ room_id: str, transport_room_id: str, channel_id: str, tenant_id: str) -> None:pass@@ -81,7 +81,7 @@ def _fake_bridge(*, agent_ids: list[str], slash_hint: str | None = None): # noqasync def test_agentless_auto_create_posts_notice() -> None:bridge = _fake_bridge(agent_ids=[])- result = await BridgeCore._create_room_for_channel(+ result = await CollaborationCore._create_room_for_channel(bridge,channel_id="C0BGC39BFSR",channel_type="channel_public",@@ -107,7 +107,7 @@ async def test_notice_carries_this_bridge_s_own_slash_syntax() -> None:slash_hint="`/invite-agent agent:agent-name` — the Discord slash command",)- await BridgeCore._create_room_for_channel(+ await CollaborationCore._create_room_for_channel(bridge,channel_id="C1",channel_type="channel_public",@@ -125,7 +125,7 @@ async def test_notice_omits_the_slash_form_where_there_is_none() -> None:# would point the user at something that does not exist.bridge = _fake_bridge(agent_ids=[], slash_hint=None)- await BridgeCore._create_room_for_channel(+ await CollaborationCore._create_room_for_channel(bridge,channel_id="C1",channel_type="channel_public",@@ -173,7 +173,7 @@ def test_each_adapter_advertises_a_syntax_it_actually_accepts() -> None:async def test_auto_create_with_agents_posts_no_notice() -> None:bridge = _fake_bridge(agent_ids=["a1"])- result = await BridgeCore._create_room_for_channel(+ result = await CollaborationCore._create_room_for_channel(bridge,channel_id="C0BGC39BFSR",channel_type="channel_public",diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_admin_rendering.py b/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_admin_rendering.pyindex da1f94baa..5a54e7c82 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_admin_rendering.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_admin_rendering.py@@ -1,7 +1,7 @@"""Who renders an admin/system message on its way out of Matrix.`admin_message` takes Switch Markdown and renders it itself, because most of-its callers are notices composed in `bridge_core` with no adapter in reach. The+its callers are notices composed in `collaboration_core` with no adapter in reach. Therelay path here has to respect that and pass the body unrendered.It did not, and the two halves each did the conversion: a `!list-agents` reply@@ -14,7 +14,10 @@ from __future__ import annotationsfrom typing import Any-from switch_core.bridges.collaboration.bridge_core import ADMIN_MARKER, BridgeCore+from switch_core.bridges.collaboration.collaboration_core import (+ ADMIN_MARKER,+ CollaborationCore,+)from switch_core.transport import InboundMessage, RoomRefBODY = "**Agents in this room:**\n- **scout** — Claude Code"@@ -66,12 +69,12 @@ class _RecordingAdapter:return "ref-msg"-def _bridge(adapter: _RecordingAdapter) -> BridgeCore:- core = object.__new__(BridgeCore)+def _bridge(adapter: _RecordingAdapter) -> CollaborationCore:+ core = object.__new__(CollaborationCore)core._bridge_type = "slack" # type: ignore[attr-defined]core._adapter = adapter # type: ignore[assignment]- core._puppet_matrix_ids = set() # type: ignore[assignment]- core._bridge_client_matrix_user_id = "@bridge:switch.local" # type: ignore[assignment]+ core._human_user_ids = set() # type: ignore[assignment]+ core._workspace_consumer_transport_user_id = "@bridge:switch.local" # type: ignore[assignment]core._find_channel = lambda **_kwargs: "C1" # type: ignore[assignment]core._channel_to_room = {"C1": ("room-uuid", "!r:switch.local")} # type: ignore[assignment]core._room_tenant = _tenant # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_media.py b/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_media.pyindex ee7711ce0..5abf75b86 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_media.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_media.py@@ -4,7 +4,7 @@ import asynciofrom types import SimpleNamespacefrom typing import Any-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.transport import (DownloadResult,InboundMedia,@@ -118,14 +118,14 @@ class _FakeAdapter:def _fake_bridge(*,download: DownloadResult | TransportError = DownloadResult(body=b"bytes"),- matrix_to_external: dict[str, str] | None = None,+ room_to_external: dict[str, str] | None = None,max_bytes: int = 1024,) -> SimpleNamespace:adapter = _FakeAdapter()recorded: list[dict[str, str]] = []- lookup = matrix_to_external or {}+ lookup = room_to_external or {}- async def _external_post_for_matrix_event(transport_event_id: str) -> str | None:+ async def _external_post_for_event(transport_event_id: str) -> str | None:return lookup.get(transport_event_id)async def _record_message_map(**kwargs: str) -> None:@@ -137,10 +137,10 @@ def _fake_bridge(ns = SimpleNamespace(_bridge_type="slack",_adapter=adapter,- _puppet_matrix_ids={"@puppet:s"},- _bridge_client_matrix_user_id="@bridge:s",+ _human_user_ids={"@human actor:s"},+ _workspace_consumer_transport_user_id="@bridge:s",_max_attachment_bytes=max_bytes,- _external_post_for_matrix_event=_external_post_for_matrix_event,+ _external_post_for_event=_external_post_for_event,_record_message_map=_record_message_map,recorded=recorded,_outbound_groups={},@@ -148,22 +148,24 @@ def _fake_bridge(_channel_to_room={"chan-1": ("room-uuid", "!room:s")},_room_tenant=_room_tenant,)- ns._find_channel = lambda room_id=None, matrix_room_id=None: (- "chan-1" if matrix_room_id == "!room:s" else None+ ns._find_channel = lambda room_id=None, transport_room_id=None: (+ "chan-1" if transport_room_id == "!room:s" else None)- ns._outbound_thread_root_ref = BridgeCore._outbound_thread_root_ref.__get__(ns)- ns._download_matrix_media = BridgeCore._download_matrix_media.__get__(ns)+ ns._outbound_thread_root_ref = CollaborationCore._outbound_thread_root_ref.__get__(+ ns+ )+ ns._download_media = CollaborationCore._download_media.__get__(ns)ns._schedule_outbound_group_flush = (- BridgeCore._schedule_outbound_group_flush.__get__(ns)+ CollaborationCore._schedule_outbound_group_flush.__get__(ns))- ns._cancel_outbound_group_flush = BridgeCore._cancel_outbound_group_flush.__get__(- ns+ ns._cancel_outbound_group_flush = (+ CollaborationCore._cancel_outbound_group_flush.__get__(ns))- ns._relay_outbound_group = BridgeCore._relay_outbound_group.__get__(ns)- ns._relay_outbound_media = BridgeCore._relay_outbound_media.__get__(ns)- ns._counted_outbound = BridgeCore._counted_outbound.__get__(ns)+ ns._relay_outbound_group = CollaborationCore._relay_outbound_group.__get__(ns)+ ns._relay_outbound_media = CollaborationCore._relay_outbound_media.__get__(ns)+ ns._counted_outbound = CollaborationCore._counted_outbound.__get__(ns)ns._flush_incomplete_outbound_group = (- BridgeCore._flush_incomplete_outbound_group.__get__(ns)+ CollaborationCore._flush_incomplete_outbound_group.__get__(ns))async def _download_media(uri: str) -> DownloadResult:@@ -184,7 +186,7 @@ def _room() -> RoomRef:async def test_image_relays_via_send_attachment_and_records_map() -> None:bridge = _fake_bridge()- await BridgeCore.handle_outbound_media(+ await CollaborationCore.handle_outbound_media(bridge, _room(), _media_event(), bridge.client)@@ -211,7 +213,7 @@ async def test_image_relays_via_send_attachment_and_records_map() -> None:async def test_caption_convention_unpacks_body_and_filename() -> None:bridge = _fake_bridge()- await BridgeCore.handle_outbound_media(+ await CollaborationCore.handle_outbound_media(bridge,_room(),_media_event(body="look at this", filename="plot.png"),@@ -224,22 +226,22 @@ async def test_caption_convention_unpacks_body_and_filename() -> None:async def test_threaded_media_resolves_external_root() -> None:- bridge = _fake_bridge(matrix_to_external={"$root": "ext-root"})+ bridge = _fake_bridge(room_to_external={"$root": "ext-root"})- await BridgeCore.handle_outbound_media(+ await CollaborationCore.handle_outbound_media(bridge, _room(), _media_event(thread_root="$root"), bridge.client)assert bridge._adapter.attachments[0]["thread_root_id"] == "ext-root"-async def test_puppet_media_is_skipped() -> None:- # Media a puppet posted originated on the platform — relaying it back+async def test_human_actor_media_is_skipped() -> None:+ # Media a human actor posted originated on the platform — relaying it back# would echo it.bridge = _fake_bridge()- await BridgeCore.handle_outbound_media(- bridge, _room(), _media_event(sender="@puppet:s"), bridge.client+ await CollaborationCore.handle_outbound_media(+ bridge, _room(), _media_event(sender="@human actor:s"), bridge.client)assert bridge._adapter.attachments == []@@ -249,7 +251,7 @@ async def test_puppet_media_is_skipped() -> None:async def test_media_without_sender_name_is_skipped() -> None:bridge = _fake_bridge()- await BridgeCore.handle_outbound_media(+ await CollaborationCore.handle_outbound_media(bridge, _room(), _media_event(sender_name=None), bridge.client)@@ -262,7 +264,7 @@ async def test_non_image_file_relays_natively() -> None:notice — that was the reported bug."""bridge = _fake_bridge()- await BridgeCore.handle_outbound_media(+ await CollaborationCore.handle_outbound_media(bridge,_room(),_media_event(msgtype="m.file", body="report.pdf", mimetype="application/pdf"),@@ -281,7 +283,7 @@ async def test_non_image_file_relays_natively() -> None:async def test_download_failure_posts_disclosed_fallback() -> None:bridge = _fake_bridge(download=TransportError("boom"))- await BridgeCore.handle_outbound_media(+ await CollaborationCore.handle_outbound_media(bridge, _room(), _media_event(), bridge.client)@@ -293,7 +295,7 @@ async def test_download_failure_posts_disclosed_fallback() -> None:async def test_oversize_media_posts_disclosed_fallback() -> None:bridge = _fake_bridge(download=DownloadResult(body=b"too big"), max_bytes=3)- await BridgeCore.handle_outbound_media(+ await CollaborationCore.handle_outbound_media(bridge, _room(), _media_event(), bridge.client)@@ -314,7 +316,7 @@ async def test_grouped_attachments_relay_as_one_platform_post() -> None:("data.csv", "text/csv"),]):- await BridgeCore.handle_outbound_media(+ await CollaborationCore.handle_outbound_media(bridge,_room(),_media_event(@@ -345,13 +347,13 @@ async def test_grouped_attachments_relay_as_one_platform_post() -> None:async def test_incomplete_group_is_flushed_with_a_disclosed_notice() -> None:"""A group that never completes must still reach the platform, flagged —never silently held forever."""- import switch_core.bridges.collaboration.bridge_core as bc+ import switch_core.bridges.collaboration.collaboration_core as bcoriginal = bc.OUTBOUND_GROUP_TIMEOUT_SECONDSbc.OUTBOUND_GROUP_TIMEOUT_SECONDS = 0.01try:bridge = _fake_bridge()- await BridgeCore.handle_outbound_media(+ await CollaborationCore.handle_outbound_media(bridge,_room(),_media_event(diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_platform_rendering.py b/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_platform_rendering.pyindex 68bf04682..8acc1d6dc 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_platform_rendering.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_platform_rendering.py@@ -10,7 +10,7 @@ from __future__ import annotationsfrom typing import Any-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.clients.admin_messages import PLATFORM_MARKERfrom switch_core.transport import InboundMessage, RoomRef@@ -55,12 +55,12 @@ async def _tenant(*_args: Any, **_kwargs: Any) -> str:return "tenant-1"-def _bridge(adapter: _RecordingAdapter) -> BridgeCore:- core = object.__new__(BridgeCore)+def _bridge(adapter: _RecordingAdapter) -> CollaborationCore:+ core = object.__new__(CollaborationCore)core._bridge_type = "slack" # type: ignore[attr-defined]core._adapter = adapter # type: ignore[assignment]- core._puppet_matrix_ids = set() # type: ignore[assignment]- core._bridge_client_matrix_user_id = "@bridge:switch.local" # type: ignore[assignment]+ core._human_user_ids = set() # type: ignore[assignment]+ core._workspace_consumer_transport_user_id = "@bridge:switch.local" # type: ignore[assignment]core._find_channel = lambda **_kwargs: "C1" # type: ignore[assignment]core._channel_to_room = {"C1": ("room-uuid", "!r:switch.local")} # type: ignore[assignment]core._room_tenant = _tenant # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_self_mention_guidance.py b/core/tests/switch_core/bridges/collaboration/test_bridge_self_mention_guidance.pyindex 2bc78267e..ccb96b9ed 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_self_mention_guidance.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_self_mention_guidance.py@@ -3,7 +3,7 @@ from __future__ import annotationsfrom types import SimpleNamespacefrom typing import Any-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.models import InboundMessage# When a user tags the bridge bot itself ("Agent Switch") but the bot is not set@@ -88,7 +88,7 @@ async def test_unaliased_self_mention_posts_guidance() -> None:agents={"a1": _agent("agent-a"), "a2": _agent("agent-b")},)- await BridgeCore._maybe_guide_self_mention(+ await CollaborationCore._maybe_guide_self_mention(bridge, _msg(self_mention_token="UBOT"), "room-uuid")@@ -111,7 +111,7 @@ async def test_aliased_self_mention_posts_nothing() -> None:agents={"a1": _agent("agent-a")},)- await BridgeCore._maybe_guide_self_mention(+ await CollaborationCore._maybe_guide_self_mention(bridge, _msg(self_mention_token="UBOT"), "room-uuid")@@ -121,7 +121,7 @@ async def test_aliased_self_mention_posts_nothing() -> None:async def test_no_self_mention_posts_nothing() -> None:bridge = _fake_bridge(alias_agent=None, agents={"a1": _agent("agent-a")})- await BridgeCore._maybe_guide_self_mention(+ await CollaborationCore._maybe_guide_self_mention(bridge, _msg(self_mention_token=None), "room-uuid")@@ -131,7 +131,7 @@ async def test_no_self_mention_posts_nothing() -> None:async def test_self_mention_threads_under_existing_thread_root() -> None:bridge = _fake_bridge(alias_agent=None, agents={"a1": _agent("agent-a")})- await BridgeCore._maybe_guide_self_mention(+ await CollaborationCore._maybe_guide_self_mention(bridge, _msg(self_mention_token="UBOT", root_id="C123:100.1"), "room-uuid")@@ -146,7 +146,7 @@ async def test_guidance_omits_set_alias_for_non_alias_safe_token() -> None:agents={"a1": _agent("agent-a"), "a2": _agent("agent-b")},)- await BridgeCore._maybe_guide_self_mention(+ await CollaborationCore._maybe_guide_self_mention(bridge, _msg(self_mention_token="28:app-123"), "room-uuid")@@ -159,7 +159,7 @@ async def test_guidance_omits_set_alias_for_non_alias_safe_token() -> None:async def test_resolve_target_single_agent_unaliased() -> None:bridge = _fake_bridge(alias_agent=None, agents={"a1": _agent("agent-a")})- target = await BridgeCore._resolve_self_mention_target(+ target = await CollaborationCore._resolve_self_mention_target(bridge, _msg(self_mention_token="28:app-123"), "room-uuid")@@ -172,7 +172,7 @@ async def test_resolve_target_uses_alias_even_with_many_agents() -> None:agents={"a1": _agent("agent-a"), "a2": _agent("agent-b")},)- target = await BridgeCore._resolve_self_mention_target(+ target = await CollaborationCore._resolve_self_mention_target(bridge, _msg(self_mention_token="UBOT"), "room-uuid")@@ -185,7 +185,7 @@ async def test_resolve_target_ambiguous_returns_none() -> None:agents={"a1": _agent("agent-a"), "a2": _agent("agent-b")},)- target = await BridgeCore._resolve_self_mention_target(+ target = await CollaborationCore._resolve_self_mention_target(bridge, _msg(self_mention_token="28:app-123"), "room-uuid")@@ -195,7 +195,7 @@ async def test_resolve_target_ambiguous_returns_none() -> None:async def test_resolve_target_no_token_returns_none() -> None:bridge = _fake_bridge(alias_agent=None, agents={"a1": _agent("agent-a")})- target = await BridgeCore._resolve_self_mention_target(+ target = await CollaborationCore._resolve_self_mention_target(bridge, _msg(self_mention_token=None), "room-uuid")diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py b/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.pyindex ec8ff2e25..5e0850572 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py@@ -51,7 +51,7 @@ def _service() -> CollaborationBridgeLifecycleService:client_store=None, # type: ignore[arg-type]client_lifecycle=None, # type: ignore[arg-type]room_service=None, # type: ignore[arg-type]- matrix_admin=None, # type: ignore[arg-type]+ provisioning=None, # type: ignore[arg-type]session_factory=None, # type: ignore[arg-type]config=config,client_factory=None, # type: ignore[arg-type]diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_unknown_member_first_message.py b/core/tests/switch_core/bridges/collaboration/test_bridge_unknown_member_first_message.pyindex 50e589ae6..b9a4bc085 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_unknown_member_first_message.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_unknown_member_first_message.py@@ -5,16 +5,18 @@ from types import SimpleNamespaceimport pytest-from switch_core.bridges.collaboration import bridge_core as bridge_core_module-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration import (+ collaboration_core as collaboration_core_module,+)+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.models import InboundMessage# CHOO-1781: the first message from a channel member not yet known to the room-# must not be dropped. Provisioning only *invites* the external user's puppet —-# the join lands asynchronously from the puppet's own sync loop. Relaying before-# that join is rejected by the homeserver, so the triggering message vanishes.-# _ensure_user_in_matrix_room must therefore block until the join is observed,-# and must refuse to hand back a puppet that never joined.+# must not be dropped. Provisioning invites the external user's human actor and+# its membership can land after the call returns. A message written before the+# join is filtered as pre-join by the room's readers, so it vanishes.+# _ensure_human_in_room must therefore block until the join is observed,+# and must refuse to hand back a human actor that never joined.## For a Slack app the same drop is not a race but a certainty. Joins are keyed on# the `user` of a member_joined_channel event, whereas an app posting without a@@ -23,7 +25,7 @@ from switch_core.bridges.collaboration.models import InboundMessage# pre-warmed and always arrives here unknown — its first post hits the unjoined# window every single time.-MATRIX_ROOM_ID = "!matrix:switch.local"+TRANSPORT_ROOM_ID = "!matrix:switch.local"# Slack bot id of a third-party app, as the adapter reports it for a post with no# `user` field.@@ -40,11 +42,11 @@ async def _no_text_answer(_msg: object) -> None:return None-class _FakePuppet:- """Stands in for a ClientBase puppet whose join lands after the invite."""+class _FakeHumanActor:+ """Stands in for a Actor human actor whose join lands after the invite."""def __init__(self) -> None:- self.matrix_user_id = "@ext_alice:switch.local"+ self.transport_user_id = "@ext_alice:switch.local"self._joined = asyncio.Event()self.sent: list[tuple[str, str]] = []self.wait_joined_calls: list[tuple[str, float]] = []@@ -66,114 +68,114 @@ class _FakePuppet:async def send_message(self, room_id: str, content: str, **_kw: object) -> str:if not self._joined.is_set():# Mirrors the homeserver rejecting a send from a non-member.- raise AssertionError("puppet sent into a room it has not joined")+ raise AssertionError("human actor sent into a room it has not joined")self.sent.append((room_id, content))return "$event-1"def _bridge(- puppet: _FakePuppet, *, known_puppets: dict[str, str] | None = None+ human_actor: _FakeHumanActor, *, known_human_actors: dict[str, str] | None = None) -> SimpleNamespace:async def _ensure_client_in_room(room_id: str, client_id: str) -> None:return None # invite only — the join is asynchronous, as in productioncreated: list[tuple[str, str]] = []- async def _create_puppet(external_user_id: str, external_username: str) -> str:+ async def _create_human_actor(external_user_id: str, external_username: str) -> str:created.append((external_user_id, external_username))return "client-new"bridge = SimpleNamespace(_repair_placeholder_username=_noop_repair,- _user_puppets={"ext-alice": "client-1"}- if known_puppets is None- else known_puppets,- _client_lifecycle=SimpleNamespace(get=lambda _id: puppet),+ _human_actors={"ext-alice": "client-1"}+ if known_human_actors is None+ else known_human_actors,+ _client_lifecycle=SimpleNamespace(get=lambda _id: human_actor),_room_service=SimpleNamespace(ensure_client_in_room=_ensure_client_in_room),- _create_puppet=_create_puppet,+ _create_human_actor=_create_human_actor,)- bridge.created_puppets = created+ bridge.created_human_actors = createdreturn bridge-async def test_waits_for_puppet_join_before_returning() -> None:- puppet = _FakePuppet()- bridge = _bridge(puppet)+async def test_waits_for_human_actor_join_before_returning() -> None:+ human_actor = _FakeHumanActor()+ bridge = _bridge(human_actor)task = asyncio.create_task(- BridgeCore._ensure_user_in_matrix_room(+ CollaborationCore._ensure_human_in_room(bridge,external_user_id="ext-alice",external_username="alice",room_id="room-uuid",- matrix_room_id=MATRIX_ROOM_ID,+ transport_room_id=TRANSPORT_ROOM_ID,))await asyncio.sleep(0)- # Still blocked: the puppet has been invited but has not joined yet.+ # Still blocked: the human actor has been invited but has not joined yet.assert not task.done()- puppet.complete_join()- assert await task is puppet- assert puppet.wait_joined_calls == [- (MATRIX_ROOM_ID, bridge_core_module.PUPPET_JOIN_TIMEOUT)+ human_actor.complete_join()+ assert await task is human_actor+ assert human_actor.wait_joined_calls == [+ (TRANSPORT_ROOM_ID, collaboration_core_module.HUMAN_JOIN_TIMEOUT)]async def test_returns_none_when_join_never_lands(monkeypatch: pytest.MonkeyPatch,) -> None:- monkeypatch.setattr(bridge_core_module, "PUPPET_JOIN_TIMEOUT", 0.01)- puppet = _FakePuppet() # never joins+ monkeypatch.setattr(collaboration_core_module, "HUMAN_JOIN_TIMEOUT", 0.01)+ human_actor = _FakeHumanActor() # never joins- result = await BridgeCore._ensure_user_in_matrix_room(- _bridge(puppet),+ result = await CollaborationCore._ensure_human_in_room(+ _bridge(human_actor),external_user_id="ext-alice",external_username="alice",room_id="room-uuid",- matrix_room_id=MATRIX_ROOM_ID,+ transport_room_id=TRANSPORT_ROOM_ID,)- # Fail loud, never fake: no puppet handed back, so nothing is relayed into a+ # Fail loud, never fake: no human actor handed back, so nothing is relayed into a# room the sender is not a member of.assert result is None-async def test_app_sender_puppet_is_provisioned_then_awaited() -> None:- # An app is never pre-warmed by a join, so it always arrives with no puppet:+async def test_app_sender_human_actor_is_provisioned_then_awaited() -> None:+ # An app is never pre-warmed by a join, so it always arrives with no human actor:# the provisioning branch runs, and the join must still be awaited before the- # puppet is handed back. Without the wait this returns a puppet that is only+ # human actor is handed back. Without the wait this returns a human actor that is only# invited, and the app's very first post is lost — every time, not sometimes.- puppet = _FakePuppet()- bridge = _bridge(puppet, known_puppets={})+ human_actor = _FakeHumanActor()+ bridge = _bridge(human_actor, known_human_actors={})task = asyncio.create_task(- BridgeCore._ensure_user_in_matrix_room(+ CollaborationCore._ensure_human_in_room(bridge,external_user_id=APP_SENDER_ID,external_username="Datadog",room_id="room-uuid",- matrix_room_id=MATRIX_ROOM_ID,+ transport_room_id=TRANSPORT_ROOM_ID,))await asyncio.sleep(0)- assert bridge.created_puppets == [(APP_SENDER_ID, "Datadog")]+ assert bridge.created_human_actors == [(APP_SENDER_ID, "Datadog")]assert not task.done()- puppet.complete_join()- assert await task is puppet- assert puppet.wait_joined_calls == [- (MATRIX_ROOM_ID, bridge_core_module.PUPPET_JOIN_TIMEOUT)+ human_actor.complete_join()+ assert await task is human_actor+ assert human_actor.wait_joined_calls == [+ (TRANSPORT_ROOM_ID, collaboration_core_module.HUMAN_JOIN_TIMEOUT)]async def test_first_message_from_app_sender_is_relayed() -> None:# End-to-end for the guaranteed case: a third-party app posts into a channel- # for the first time (bot-id sender, no puppet anywhere) and the post must+ # for the first time (bot-id sender, no human actor anywhere) and the post must# land in the room rather than being swallowed.- puppet = _FakePuppet()+ human_actor = _FakeHumanActor()relayed: list[tuple[str, str]] = []async def _is_registered_agent(_name: str) -> bool:@@ -182,26 +184,26 @@ async def test_first_message_from_app_sender_is_relayed() -> None:async def _record_message_map(**kwargs: str) -> None:relayed.append((kwargs["transport_event_id"], kwargs["external_post_id"]))- inner = _bridge(puppet, known_puppets={})+ inner = _bridge(human_actor, known_human_actors={})- async def _ensure_user_in_matrix_room(**kwargs: object) -> object:+ async def _ensure_human_in_room(**kwargs: object) -> object:# Complete the join as the real invite/join round-trip would, so the# relay below exercises the post-join send rather than a stubbed one.- asyncio.get_running_loop().call_soon(puppet.complete_join)- return await BridgeCore._ensure_user_in_matrix_room(inner, **kwargs) # type: ignore[arg-type]+ asyncio.get_running_loop().call_soon(human_actor.complete_join)+ return await CollaborationCore._ensure_human_in_room(inner, **kwargs) # type: ignore[arg-type]bridge = SimpleNamespace(_repair_placeholder_username=_noop_repair,_is_registered_agent=_is_registered_agent,- _ensure_user_in_matrix_room=_ensure_user_in_matrix_room,+ _ensure_human_in_room=_ensure_human_in_room,_record_message_map=_record_message_map,_adapter=SimpleNamespace(translate_inbound=lambda text: text),_handle_text_answer=_no_text_answer,- _channel_to_room={"chan-1": ("room-uuid", MATRIX_ROOM_ID)},+ _channel_to_room={"chan-1": ("room-uuid", TRANSPORT_ROOM_ID)},_channel_locks={},)- await BridgeCore._handle_inbound_message(+ await CollaborationCore._handle_inbound_message(bridge,InboundMessage(channel_id="chan-1",@@ -213,22 +215,24 @@ async def test_first_message_from_app_sender_is_relayed() -> None:),)- assert inner.created_puppets == [(APP_SENDER_ID, "Datadog")]- assert puppet.sent == [(MATRIX_ROOM_ID, "Triggered: container restart spike")]+ assert inner.created_human_actors == [(APP_SENDER_ID, "Datadog")]+ assert human_actor.sent == [+ (TRANSPORT_ROOM_ID, "Triggered: container restart spike")+ ]assert relayed == [("$event-1", "slack-post-1")]async def test_first_message_from_unknown_member_is_relayed() -> None:- puppet = _FakePuppet()+ human_actor = _FakeHumanActor()relayed: list[tuple[str, str]] = []async def _is_registered_agent(_name: str) -> bool:return False- async def _ensure_user_in_matrix_room(**_kw: object) -> _FakePuppet:+ async def _ensure_human_in_room(**_kw: object) -> _FakeHumanActor:# Provisioning completes the join, as the real path now guarantees.- puppet.complete_join()- return puppet+ human_actor.complete_join()+ return human_actorasync def _record_message_map(**kwargs: str) -> None:relayed.append((kwargs["transport_event_id"], kwargs["external_post_id"]))@@ -236,15 +240,15 @@ async def test_first_message_from_unknown_member_is_relayed() -> None:bridge = SimpleNamespace(_repair_placeholder_username=_noop_repair,_is_registered_agent=_is_registered_agent,- _ensure_user_in_matrix_room=_ensure_user_in_matrix_room,+ _ensure_human_in_room=_ensure_human_in_room,_record_message_map=_record_message_map,_adapter=SimpleNamespace(translate_inbound=lambda text: text),_handle_text_answer=_no_text_answer,- _channel_to_room={"chan-1": ("room-uuid", MATRIX_ROOM_ID)},+ _channel_to_room={"chan-1": ("room-uuid", TRANSPORT_ROOM_ID)},_channel_locks={},)- await BridgeCore._handle_inbound_message(+ await CollaborationCore._handle_inbound_message(bridge,InboundMessage(channel_id="chan-1",@@ -256,5 +260,5 @@ async def test_first_message_from_unknown_member_is_relayed() -> None:),)- assert puppet.sent == [(MATRIX_ROOM_ID, "hello from a brand new member")]+ assert human_actor.sent == [(TRANSPORT_ROOM_ID, "hello from a brand new member")]assert relayed == [("$event-1", "mm-post-1")]diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_user_resolution.py b/core/tests/switch_core/bridges/collaboration/test_bridge_user_resolution.pyindex 28db8526d..8928e749e 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_user_resolution.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_user_resolution.py@@ -12,7 +12,7 @@ from __future__ import annotationsimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.models import DirectoryUserfrom switch_core.db.models import (TENANT_ZERO_ID,@@ -50,7 +50,7 @@ class _FakeLifecycle:):async with self._sf() as session:client = Client(- matrix_user_id=f"@{localpart}:test.local",+ transport_user_id=f"@{localpart}:test.local",display_name=display_name,type=client_type,)@@ -59,24 +59,24 @@ class _FakeLifecycle:class _Handle:client_id = client.id- matrix_user_id = client.matrix_user_id+ transport_user_id = client.transport_user_idreturn _Handle()async def _seed_bridge(session_factory) -> str:async with session_factory() as session:- bridge_client = Client(- matrix_user_id="@bridge:test.local",+ workspace_consumer = Client(+ transport_user_id="@bridge:test.local",display_name="bridge",type="collaboration_bridge",)- session.add(bridge_client)+ session.add(workspace_consumer)await session.flush()bridge = CollaborationBridge(type="slack",display_name="Slack",- client_id=bridge_client.id,+ client_id=workspace_consumer.id,status="active",)session.add(bridge)@@ -88,8 +88,8 @@ def _core(session_factory,bridge_id: str,adapter: _DirectoryAdapter,-) -> BridgeCore:- core = object.__new__(BridgeCore)+) -> CollaborationCore:+ core = object.__new__(CollaborationCore)core._bridge_id = bridge_idcore._bridge_type = "slack"core._adapter = adapter@@ -97,9 +97,9 @@ def _core(core._external_user_store = ExternalUserStore()core._agent_store = AgentStore()core._client_lifecycle = _FakeLifecycle(session_factory)- core._user_puppets = {}- core._puppet_locks = {}- core._puppet_matrix_ids = set()+ core._human_actors = {}+ core._human_actor_locks = {}+ core._human_user_ids = set()core._bridge_tenant_id = TENANT_ZERO_IDreturn corediff --git a/core/tests/switch_core/bridges/collaboration/test_command_thread_mapping.py b/core/tests/switch_core/bridges/collaboration/test_command_thread_mapping.pyindex 14aacb5fb..b09f7aa18 100644--- a/core/tests/switch_core/bridges/collaboration/test_command_thread_mapping.py+++ b/core/tests/switch_core/bridges/collaboration/test_command_thread_mapping.py@@ -2,7 +2,7 @@ from __future__ import annotationsfrom types import MethodType, SimpleNamespace-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.models import InboundCommandfrom switch_core.transport import SendResult, TransportError@@ -29,10 +29,10 @@ def _cmd(def _fake_bridge(send_result: SendResult | TransportError,*,- external_to_matrix: dict[str, str] | None = None,+ external_to_room: dict[str, str] | None = None,translate_inbound: object = None,) -> SimpleNamespace:- """A minimal BridgeCore stand-in for _handle_inbound_command.+ """A minimal CollaborationCore stand-in for _handle_inbound_command.`external_to_matrix` seeds the (external post -> Matrix event) lookup so wecan exercise the "thread root already bridged" branch.@@ -40,13 +40,13 @@ def _fake_bridge(recorded: list[dict[str, str]] = []sent_content: list[dict] = []pending: dict[str, str] = {}- lookup = external_to_matrix or {}+ lookup = external_to_room or {}translate = translate_inbound or (lambda raw: raw)- def _prerecord_message_map(matrix_event_id: str, external_post_id: str) -> None:- pending[matrix_event_id] = external_post_id+ def _prerecord_message_map(transport_event_id: str, external_post_id: str) -> None:+ pending[transport_event_id] = external_post_id- async def _ensure_user_in_matrix_room(**_kw: object) -> SimpleNamespace:+ async def _ensure_human_in_room(**_kw: object) -> SimpleNamespace:async def _send_event(_room_id: str, _type: str, content: dict) -> str:sent_content.append(content)if isinstance(send_result, TransportError):@@ -54,12 +54,12 @@ def _fake_bridge(return send_result.event_idreturn SimpleNamespace(- matrix_user_id="@puppet:switch.local",- client_id="puppet-1",+ transport_user_id="@human actor:switch.local",+ client_id="human-actor-1",send_event=_send_event,)- async def _matrix_event_for_external_post(external_post_id: str) -> str | None:+ async def _event_for_external_post(external_post_id: str) -> str | None:return lookup.get(external_post_id)async def _record_message_map(**kwargs: str) -> None:@@ -68,8 +68,8 @@ def _fake_bridge(bridge = SimpleNamespace(_channel_to_room={"chan-1": ("room-uuid", "!matrix:switch.local")},_adapter=SimpleNamespace(translate_inbound=translate),- _ensure_user_in_matrix_room=_ensure_user_in_matrix_room,- _matrix_event_for_external_post=_matrix_event_for_external_post,+ _ensure_human_in_room=_ensure_human_in_room,+ _event_for_external_post=_event_for_external_post,_record_message_map=_record_message_map,_prerecord_message_map=_prerecord_message_map,_pending_message_maps=pending,@@ -88,7 +88,9 @@ class TestCommandThreadMapping:event_id="$cmd-event", event_type="com.switch.command", content={}))- await BridgeCore._handle_inbound_command(bridge, _cmd(message_ref="mm-post-1"))+ await CollaborationCore._handle_inbound_command(+ bridge, _cmd(message_ref="mm-post-1")+ )assert bridge.recorded == [{@@ -108,9 +110,9 @@ class TestCommandThreadMapping:SendResult(event_id="$cmd-event", event_type="com.switch.command", content={}),- external_to_matrix={"mm-root": "$matrix-root"},+ external_to_room={"mm-root": "$matrix-root"},)- await BridgeCore._handle_inbound_command(+ await CollaborationCore._handle_inbound_command(bridge, _cmd(message_ref="mm-reply", root_id="mm-root"))@@ -128,7 +130,7 @@ class TestCommandThreadMapping:event_id="$cmd-event", event_type="com.switch.command", content={}))- await BridgeCore._handle_inbound_command(+ await CollaborationCore._handle_inbound_command(bridge, _cmd(message_ref="mm-reply", root_id="mm-root"))@@ -148,14 +150,16 @@ class TestCommandThreadMapping:event_id="$cmd-event", event_type="com.switch.command", content={}))- await BridgeCore._handle_inbound_command(bridge, _cmd(message_ref=None))+ await CollaborationCore._handle_inbound_command(bridge, _cmd(message_ref=None))assert bridge.recorded == []async def test_no_mapping_when_send_fails(self) -> None:err = TransportError("boom")bridge = _fake_bridge(err)- await BridgeCore._handle_inbound_command(bridge, _cmd(message_ref="mm-post-1"))+ await CollaborationCore._handle_inbound_command(+ bridge, _cmd(message_ref="mm-post-1")+ )assert bridge.recorded == []@@ -172,7 +176,7 @@ class TestCommandThreadMapping:"<!subteam^S123>", "@switch-onboarder"),)- await BridgeCore._handle_inbound_command(+ await CollaborationCore._handle_inbound_command(bridge,_cmd(message_ref="mm-post-1",@@ -195,10 +199,10 @@ class TestCommandResultThreadingRace:bridge = SimpleNamespace(_pending_message_maps={"$cmd-event": "chan-1:100.1"},_bridge_id="b",- _bridge_message_map_store=SimpleNamespace(get_by_matrix_event_id=_boom),+ _bridge_message_map_store=SimpleNamespace(get_by_transport_event_id=_boom),_session_factory=_boom,)- got = await BridgeCore._external_post_for_matrix_event(bridge, "$cmd-event")+ got = await CollaborationCore._external_post_for_event(bridge, "$cmd-event")assert got == "chan-1:100.1"async def test_top_level_command_result_threads_during_db_write(self) -> None:@@ -208,16 +212,16 @@ class TestCommandResultThreadingRace:# resolve the command's thread root, and is popped once the write returns.resolved: dict[str, str | None] = {}- async def _ensure_user_in_matrix_room(**_kw: object) -> SimpleNamespace:+ async def _ensure_human_in_room(**_kw: object) -> SimpleNamespace:async def _send_event(_room_id: str, _type: str, _content: dict) -> str:return "$cmd-event"return SimpleNamespace(- matrix_user_id="@puppet:switch.local",+ transport_user_id="@human actor:switch.local",send_event=_send_event,)- async def _matrix_event_for_external_post(_post: str) -> str | None:+ async def _event_for_external_post(_post: str) -> str | None:return None # top-level command: its own post is not yet bridgedasync def _get_none(*_a: object, **_k: object) -> None:@@ -239,14 +243,14 @@ class TestCommandResultThreadingRace:get_by_transport_event_id=_get_none),_session_factory=lambda: _NullSession(),- _ensure_user_in_matrix_room=_ensure_user_in_matrix_room,- _matrix_event_for_external_post=_matrix_event_for_external_post,+ _ensure_human_in_room=_ensure_human_in_room,+ _event_for_external_post=_event_for_external_post,)bridge._prerecord_message_map = MethodType(- BridgeCore._prerecord_message_map, bridge+ CollaborationCore._prerecord_message_map, bridge)- bridge._external_post_for_matrix_event = MethodType(- BridgeCore._external_post_for_matrix_event, bridge+ bridge._external_post_for_event = MethodType(+ CollaborationCore._external_post_for_event, bridge)async def _record_message_map(@@ -254,13 +258,11 @@ class TestCommandResultThreadingRace:) -> None:# Simulate the reply's outbound relay resolving the thread root while# this write is still in flight.- resolved["mid"] = await bridge._external_post_for_matrix_event(- transport_event_id- )+ resolved["mid"] = await bridge._external_post_for_event(transport_event_id)bridge._record_message_map = _record_message_map- await BridgeCore._handle_inbound_command(+ await CollaborationCore._handle_inbound_command(bridge, _cmd(message_ref="chan-1:100.1", command="help"))@@ -269,4 +271,4 @@ class TestCommandResultThreadingRace:# ...and it is cleared once the write returns...assert bridge._pending_message_maps == {}# ...after which resolution falls through to the DB (empty here).- assert await bridge._external_post_for_matrix_event("$cmd-event") is None+ assert await bridge._external_post_for_event("$cmd-event") is Nonediff --git a/core/tests/switch_core/bridges/collaboration/test_directory_search_capability.py b/core/tests/switch_core/bridges/collaboration/test_directory_search_capability.pyindex 9e0e3a4aa..23c1439b0 100644--- a/core/tests/switch_core/bridges/collaboration/test_directory_search_capability.py+++ b/core/tests/switch_core/bridges/collaboration/test_directory_search_capability.py@@ -14,7 +14,7 @@ from __future__ import annotationsimport pytest-from switch_core.bridges.collaboration.adapter import CollaborationAdapter+from switch_core.bridges.collaboration.adapter import PlatformAdapterfrom switch_core.bridges.collaboration.discord.adapter import DiscordAdapterfrom switch_core.bridges.collaboration.mattermost.adapter import MattermostAdapterfrom switch_core.bridges.collaboration.slack.adapter import SlackAdapter@@ -32,7 +32,7 @@ ADAPTERS = [@pytest.mark.parametrize("adapter_cls", ADAPTERS, ids=lambda c: c.__name__)async def test_the_flag_agrees_with_what_the_adapter_actually_does(- adapter_cls: type[CollaborationAdapter],+ adapter_cls: type[PlatformAdapter],) -> None:"""A platform declaring a directory must implement the search, and onedeclaring none must not — otherwise the flag is decoration and the UI is@@ -43,8 +43,7 @@ async def test_the_flag_agrees_with_what_the_adapter_actually_does(network call is itself the evidence that it was implemented."""implements = (- adapter_cls.search_directory_users- is not CollaborationAdapter.search_directory_users+ adapter_cls.search_directory_users is not PlatformAdapter.search_directory_users)assert adapter_cls.supports_directory_search == implements, (diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_eager_attach.py b/core/tests/switch_core/bridges/collaboration/test_discord_eager_attach.pyindex b741cd2aa..3ce736242 100644--- a/core/tests/switch_core/bridges/collaboration/test_discord_eager_attach.py+++ b/core/tests/switch_core/bridges/collaboration/test_discord_eager_attach.py@@ -16,7 +16,7 @@ from typing import Anyimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.collaboration.adapter import CollaborationAdapter+from switch_core.bridges.collaboration.adapter import PlatformAdapterfrom switch_core.bridges.collaboration.discord.adapter import (DiscordAdapter,DiscordConnectionConfig,@@ -128,9 +128,9 @@ class TestTheLifecycle:service = _service(session_factory)service.register_adapter("mattermost", _StubAdapter, _StubConfig)events: list[str] = []- handed: list[CollaborationAdapter] = []+ handed: list[PlatformAdapter] = []- def listener(adapter: CollaborationAdapter) -> None:+ def listener(adapter: PlatformAdapter) -> None:events.append("listener")handed.append(adapter)diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_isolation_guards.py b/core/tests/switch_core/bridges/collaboration/test_discord_isolation_guards.pyindex db374f8f0..4c5afa697 100644--- a/core/tests/switch_core/bridges/collaboration/test_discord_isolation_guards.py+++ b/core/tests/switch_core/bridges/collaboration/test_discord_isolation_guards.py@@ -66,7 +66,7 @@ async def test_each_guilds_bridge_has_its_own_identity_caches() -> None:"""The same Discord user in two tenants' guilds yields two independentrecords: each guild is served by its own adapter (one install = one tenant,decision D2), so a user-id-keyed cache on one is not shared with the other.- The database side is scoped the same way — puppet and external-user rows are+ The database side is scoped the same way — human actor and external-user rows arewritten under each bridge's tenant through row-level security."""tenant_a = DiscordAdapter(config=DiscordConnectionConfig(guild_id="1", event_delivery="shared")diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_sdk_only.py b/core/tests/switch_core/bridges/collaboration/test_discord_sdk_only.pyindex feb1e3f11..277ba50eb 100644--- a/core/tests/switch_core/bridges/collaboration/test_discord_sdk_only.py+++ b/core/tests/switch_core/bridges/collaboration/test_discord_sdk_only.py@@ -351,7 +351,7 @@ async def _card(**kwargs: Any) -> RequestCard:async def test_the_publication_is_the_only_account_of_a_turn() -> None:- """There is no second renderer to fall back to, and `bridge_core` reads+ """There is no second renderer to fall back to, and `collaboration_core` readsthis flag to decide whether to route sessions here at all — so a platformthat stopped declaring it would go quiet rather than draw the turn someother way."""diff --git a/core/tests/switch_core/bridges/collaboration/test_home_deeplinks.py b/core/tests/switch_core/bridges/collaboration/test_home_deeplinks.pyindex ae9b9e9fb..e4640f8df 100644--- a/core/tests/switch_core/bridges/collaboration/test_home_deeplinks.py+++ b/core/tests/switch_core/bridges/collaboration/test_home_deeplinks.py@@ -15,7 +15,7 @@ from __future__ import annotationsimport asynciofrom typing import Any-from switch_core.bridges.collaboration.adapter import CollaborationAdapter+from switch_core.bridges.collaboration.adapter import PlatformAdapterfrom switch_core.bridges.collaboration.discord.adapter import (DiscordAdapter,DiscordConnectionConfig,@@ -131,7 +131,7 @@ def test_mattermost_home_prefers_the_public_url() -> None:def test_base_adapter_offers_no_home_link() -> None:# A platform that has not implemented one must return None rather than# inherit something wrong — the caller hides the action instead.- assert _run(CollaborationAdapter.home_deeplink(object())) is None # type: ignore[arg-type]+ assert _run(PlatformAdapter.home_deeplink(object())) is None # type: ignore[arg-type]def test_no_home_link_carries_a_credential() -> None:@@ -146,7 +146,7 @@ def test_no_home_link_carries_a_credential() -> None:def test_base_adapter_offers_no_install_link() -> None:# Most platforms install their app through their own admin UI, and a link# invented for them would be a link to nowhere.- assert _run(CollaborationAdapter.install_links(object())) == [] # type: ignore[arg-type]+ assert _run(PlatformAdapter.install_links(object())) == [] # type: ignore[arg-type]def test_no_install_link_carries_a_credential() -> None:@@ -163,4 +163,4 @@ def test_no_install_link_carries_a_credential() -> None:def test_base_adapter_offers_no_install_note() -> None:# Most platforms have nothing to add beyond their links, and an empty# panel in the dialog would be worse than none.- assert _run(CollaborationAdapter.install_note(object())) is None # type: ignore[arg-type]+ assert _run(PlatformAdapter.install_note(object())) is None # type: ignore[arg-type]diff --git a/core/tests/switch_core/bridges/collaboration/test_install_service.py b/core/tests/switch_core/bridges/collaboration/test_install_service.pyindex 32757ba9d..8753798b9 100644--- a/core/tests/switch_core/bridges/collaboration/test_install_service.py+++ b/core/tests/switch_core/bridges/collaboration/test_install_service.py@@ -147,7 +147,7 @@ class _FakeLifecycle:self.registered.append(kwargs)async with tenant_session(self._factory, self._tenant_id) as session:client = Client(- matrix_user_id=f"@bridge-{len(self.registered)}:{self._suffix}",+ transport_user_id=f"@bridge-{len(self.registered)}:{self._suffix}",display_name=str(kwargs["display_name"]),type="collaboration_bridge",)diff --git a/core/tests/switch_core/bridges/collaboration/test_install_webhook.py b/core/tests/switch_core/bridges/collaboration/test_install_webhook.pyindex cc0f29250..ca48cc969 100644--- a/core/tests/switch_core/bridges/collaboration/test_install_webhook.py+++ b/core/tests/switch_core/bridges/collaboration/test_install_webhook.py@@ -36,7 +36,7 @@ from fastapi import FastAPIfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import async_sessionmaker-from switch_core.bridges.collaboration.adapter import CollaborationAdapter+from switch_core.bridges.collaboration.adapter import PlatformAdapterfrom switch_core.bridges.collaboration.install import (MessagingInstallerRegistry,commands_path,@@ -86,7 +86,7 @@ def _signed(body: bytes) -> dict[str, str]:}-class _SocketOnlyAdapter(CollaborationAdapter):+class _SocketOnlyAdapter(PlatformAdapter):"""A bridge that takes its events some other way.Concrete only so one can be built; every platform call is a stub, because@@ -159,10 +159,10 @@ class _GatedAdapter(_SocketOnlyAdapter):class _FakeLifecycle:def __init__(self, factory: async_sessionmaker) -> None:self._factory = factory- self.adapters: dict[str, CollaborationAdapter] = {}+ self.adapters: dict[str, PlatformAdapter] = {}self.removed: list[str] = []- def get_adapter(self, bridge_id: str) -> CollaborationAdapter | None:+ def get_adapter(self, bridge_id: str) -> PlatformAdapter | None:return self.adapters.get(bridge_id)async def remove(self, bridge_id: str) -> None:@@ -202,7 +202,7 @@ class _Fixture:async def _make_bridge(factory: async_sessionmaker, tenant_id: str, suffix: str) -> str:async with tenant_session(factory, tenant_id) as session:client = Client(- matrix_user_id=f"@bridge-{tenant_id}:{suffix}",+ transport_user_id=f"@bridge-{tenant_id}:{suffix}",display_name="bridge",type="collaboration_bridge",)diff --git a/core/tests/switch_core/bridges/collaboration/test_lifecycle_remove.py b/core/tests/switch_core/bridges/collaboration/test_lifecycle_remove.pyindex 4a2724a9c..42169336c 100644--- a/core/tests/switch_core/bridges/collaboration/test_lifecycle_remove.py+++ b/core/tests/switch_core/bridges/collaboration/test_lifecycle_remove.py@@ -9,7 +9,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.collaboration.lifecycle_service import (CollaborationBridgeLifecycleService,- _bridge_client_localpart,+ _workspace_consumer_localpart,)from switch_core.db.models import (TENANT_ZERO_ID,@@ -79,7 +79,7 @@ def _service(client_store=MagicMock(),client_lifecycle=client_lifecycle,room_service=MagicMock(),- matrix_admin=MagicMock(),+ provisioning=MagicMock(),session_factory=session_factory,config=MagicMock(),client_factory=MagicMock(),@@ -91,7 +91,7 @@ def _service(async def _make_client(session: AsyncSession, *, client_type: str) -> str:client = Client(- matrix_user_id=f"@{client_type}-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@{client_type}-{uuid.uuid4().hex[:8]}:test",display_name=f"{client_type} client",type=client_type,)@@ -115,7 +115,7 @@ async def _make_bridge(session: AsyncSession) -> tuple[str, str]:async def _make_bridged_room(session: AsyncSession, *, bridge_id: str) -> str:room = Room(- matrix_room_id=f"!{uuid.uuid4().hex[:8]}:test",+ transport_room_id=f"!{uuid.uuid4().hex[:8]}:test",name="bridged room",description="mirror of an external channel",bridge_id=bridge_id,@@ -195,7 +195,7 @@ async def test_remove_without_dependent_rooms_still_deletes(async def test_disconnecting_takes_every_identity_switch_made_for_it(session_factory: async_sessionmaker[AsyncSession],) -> None:- """The bridge's own Matrix client and the puppet behind each person it saw.+ """The bridge's own Matrix client and the human actor behind each person it saw.These were left behind, and the bridge one is not merely untidy: its Matrixname is derived from the app's type and display name, so disconnecting an@@ -204,8 +204,8 @@ async def test_disconnecting_takes_every_identity_switch_made_for_it("""service = _service(session_factory, _ClientLifecycle())async with session_factory() as session:- bridge_id, bridge_client_id = await _make_bridge(session)- _external_user_id, puppet_client_id = await _make_external_user(+ bridge_id, workspace_consumer_id = await _make_bridge(session)+ _external_user_id, human_actor_client_id = await _make_external_user(session, bridge_id=bridge_id)await session.commit()@@ -213,8 +213,8 @@ async def test_disconnecting_takes_every_identity_switch_made_for_it(await service.remove(bridge_id)async with session_factory() as session:- assert await ClientStore().get(session, bridge_client_id) is None- assert await ClientStore().get(session, puppet_client_id) is None+ assert await ClientStore().get(session, workspace_consumer_id) is None+ assert await ClientStore().get(session, human_actor_client_id) is None@pytest.mark.asyncio@@ -224,26 +224,26 @@ async def test_identities_that_were_in_rooms_go_too("""The case that actually happens: identities with room memberships.Both of these clients have been in a room — the bridge because it carries- the channel, the puppet because the person it stands for spoke there — and+ the channel, the human actor because the person it stands for spoke there — and`client_rooms` references `clients` with no `ON DELETE` rule, so thememberships have to go before the client rows can."""service = _service(session_factory, _ClientLifecycle())async with session_factory() as session:- bridge_id, bridge_client_id = await _make_bridge(session)+ bridge_id, workspace_consumer_id = await _make_bridge(session)room_id = await _make_bridged_room(session, bridge_id=bridge_id)- _external_user_id, puppet_client_id = await _make_external_user(+ _external_user_id, human_actor_client_id = await _make_external_user(session, bridge_id=bridge_id)- await RoomStore().add_client(session, bridge_client_id, room_id)- await RoomStore().add_client(session, puppet_client_id, room_id)+ await RoomStore().add_client(session, workspace_consumer_id, room_id)+ await RoomStore().add_client(session, human_actor_client_id, room_id)await session.commit()await service.remove(bridge_id)async with session_factory() as session:- assert await ClientStore().get(session, bridge_client_id) is None- assert await ClientStore().get(session, puppet_client_id) is None+ assert await ClientStore().get(session, workspace_consumer_id) is None+ assert await ClientStore().get(session, human_actor_client_id) is None# The room outlives the connection as an internal-only room, with# nobody left claiming to be a member on the platform's behalf.assert await RoomStore().get(session, room_id) is not None@@ -263,16 +263,16 @@ async def test_a_failed_client_delete_leaves_the_bridge_intact(lifecycle = _FailingClientLifecycle(fail_on_nth=2)service = _service(session_factory, lifecycle)async with session_factory() as session:- bridge_id, bridge_client_id = await _make_bridge(session)+ bridge_id, workspace_consumer_id = await _make_bridge(session)room_id = await _make_bridged_room(session, bridge_id=bridge_id)- _first_id, first_puppet = await _make_external_user(+ _first_id, first_human_actor = await _make_external_user(session, bridge_id=bridge_id)- _second_id, second_puppet = await _make_external_user(+ _second_id, second_human_actor = await _make_external_user(session, bridge_id=bridge_id)- await RoomStore().add_client(session, bridge_client_id, room_id)- await RoomStore().add_client(session, first_puppet, room_id)+ await RoomStore().add_client(session, workspace_consumer_id, room_id)+ await RoomStore().add_client(session, first_human_actor, room_id)await session.commit()with pytest.raises(RuntimeError):@@ -286,10 +286,10 @@ async def test_a_failed_client_delete_leaves_the_bridge_intact(assert room is not Noneassert room.bridge_id == bridge_idassert await ExternalUserStore().get_by_bridge(session, bridge_id) != []- for client_id in (bridge_client_id, first_puppet, second_puppet):+ for client_id in (workspace_consumer_id, first_human_actor, second_human_actor):assert await ClientStore().get(session, client_id) is not Noneassert sorted(await RoomStore().get_client_ids(session, room_id)) == sorted(- [bridge_client_id, first_puppet]+ [workspace_consumer_id, first_human_actor])@@ -300,16 +300,16 @@ async def test_an_app_with_nobody_on_it_still_loses_its_own_client(# Louis's case exactly: a Telegram connection nobody had messaged yet.service = _service(session_factory, _ClientLifecycle())async with session_factory() as session:- bridge_id, bridge_client_id = await _make_bridge(session)+ bridge_id, workspace_consumer_id = await _make_bridge(session)await session.commit()await service.remove(bridge_id)async with session_factory() as session:- assert await ClientStore().get(session, bridge_client_id) is None+ assert await ClientStore().get(session, workspace_consumer_id) is None-class TestTheBridgeClientName:+class TestTheWorkspaceConsumerName:"""Why deleting the row is necessary but not sufficient.The homeserver has no API for removing an account, so the Matrix user@@ -321,19 +321,19 @@ class TestTheBridgeClientName:"""def test_two_connections_of_the_same_name_do_not_collide(self) -> None:- first = _bridge_client_localpart("telegram", "Telegram louiss")- second = _bridge_client_localpart("telegram", "Telegram louiss")+ first = _workspace_consumer_localpart("telegram", "Telegram louiss")+ second = _workspace_consumer_localpart("telegram", "Telegram louiss")assert first != seconddef test_the_name_still_says_which_app_it_is(self) -> None:# It shows up as a Matrix user in rooms; a pure uuid would be unreadable.- localpart = _bridge_client_localpart("telegram", "Telegram louiss")+ localpart = _workspace_consumer_localpart("telegram", "Telegram louiss")assert localpart.startswith("switch-bridge-telegram-telegram-louiss")- def test_it_stays_a_legal_matrix_localpart(self) -> None:- localpart = _bridge_client_localpart("slack", "Ops & Eng (US)")+ def test_it_stays_a_legal_localpart(self) -> None:+ localpart = _workspace_consumer_localpart("slack", "Ops & Eng (US)")assert re.fullmatch(r"[a-z0-9._=/-]+", localpart)diff --git a/core/tests/switch_core/bridges/collaboration/test_lifecycle_start_guards.py b/core/tests/switch_core/bridges/collaboration/test_lifecycle_start_guards.pyindex d8f1dd5e9..d1722d7f1 100644--- a/core/tests/switch_core/bridges/collaboration/test_lifecycle_start_guards.py+++ b/core/tests/switch_core/bridges/collaboration/test_lifecycle_start_guards.py@@ -14,7 +14,7 @@ from collections.abc import Mappingimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.collaboration.adapter import CollaborationAdapter+from switch_core.bridges.collaboration.adapter import PlatformAdapterfrom switch_core.bridges.collaboration.models import BridgeStartRefusedfrom .test_lifecycle_tenant_binding import (@@ -42,7 +42,7 @@ async def test_a_refused_bridge_runs_nothing(service = _service(session_factory)service.register_adapter("mattermost", _StubAdapter, _StubConfig)asked: list[dict[str, object]] = []- handed: list[CollaborationAdapter] = []+ handed: list[PlatformAdapter] = []async def refuse(**kwargs: object) -> None:asked.append(kwargs)diff --git a/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py b/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.pyindex 52e802175..4c6e517b3 100644--- a/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py+++ b/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py@@ -24,7 +24,7 @@ import pytestfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.collaboration.adapter import CollaborationAdapter+from switch_core.bridges.collaboration.adapter import PlatformAdapterfrom switch_core.bridges.collaboration.lifecycle_service import (CollaborationBridgeLifecycleService,)@@ -64,7 +64,7 @@ def _service(client_store=ClientStore(),client_lifecycle=MagicMock(),room_service=MagicMock(),- matrix_admin=MagicMock(),+ provisioning=MagicMock(),session_factory=session_factory,config=config,client_factory=MagicMock(),@@ -74,7 +74,7 @@ def _service()-class _StubAdapter(CollaborationAdapter):+class _StubAdapter(PlatformAdapter):"""Concrete only so `start` can build one; no platform call is made."""def __init__(self, *, config: Any) -> None:@@ -110,7 +110,7 @@ async def _make_bridge(session: AsyncSession, *, tenant_id: str) -> tuple[str, s"""A bridge row and its client, in `tenant_id`. Returns (bridge, client)."""client = Client(tenant_id=tenant_id,- matrix_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",display_name="bridge client",type="bridge",)@@ -244,7 +244,7 @@ async def test_the_bridge_task_unbinds_and_then_binds_per_unit_of_work(bridge_id, client_id = await _make_bridge(session, tenant_id=bridge_tenant)room = Room(tenant_id=bridge_tenant,- matrix_room_id=f"!room-{uuid.uuid4().hex[:8]}:test",+ transport_room_id=f"!room-{uuid.uuid4().hex[:8]}:test",name="a bridged room",description="",bridge_id=bridge_id,@@ -267,8 +267,8 @@ async def test_the_bridge_task_unbinds_and_then_binds_per_unit_of_work(async def start(self) -> None:seen["client"] = current_tenant_id()- bridge_client = _Client()- bridge_client.client_id = client_id+ workspace_consumer = _Client()+ workspace_consumer.client_id = client_idleaked: list[str | None] = []with tenant_scope(caller_tenant):@@ -276,7 +276,7 @@ async def test_the_bridge_task_unbinds_and_then_binds_per_unit_of_work(bridge_id,bridge_tenant,_Core(), # type: ignore[arg-type]- bridge_client, # type: ignore[arg-type]+ workspace_consumer, # type: ignore[arg-type])leaked.append(current_tenant_id())@@ -338,7 +338,7 @@ async def test_a_host_resource_conflict_is_looked_for_across_every_tenant(await _make_tenant(session, newcomer_tenant)client = Client(tenant_id=incumbent_tenant,- matrix_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",display_name="bridge client",type="bridge",)@@ -406,7 +406,7 @@ async def test_a_tenant_scoped_read_of_the_same_data_would_have_missed_the_conflawait _make_tenant(session, newcomer_tenant)client = Client(tenant_id=incumbent_tenant,- matrix_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",display_name="bridge client",type="bridge",)@@ -454,7 +454,7 @@ async def test_a_same_tenant_conflict_names_the_incumbent_bridge(await _make_tenant(session, tenant)client = Client(tenant_id=tenant,- matrix_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",display_name="bridge client",type="bridge",)@@ -500,7 +500,7 @@ async def test_a_cross_tenant_conflict_does_not_name_the_incumbent_or_its_tenantawait _make_tenant(session, newcomer_tenant)client = Client(tenant_id=incumbent_tenant,- matrix_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",display_name="Their Secret Teams",type="bridge",)@@ -549,7 +549,7 @@ async def test_a_conflict_with_nothing_bound_fails_closed_to_the_non_disclosing_await _make_tenant(session, incumbent_tenant)client = Client(tenant_id=incumbent_tenant,- matrix_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",display_name="Their Secret Teams",type="bridge",)diff --git a/core/tests/switch_core/bridges/collaboration/test_placeholder_username_repair.py b/core/tests/switch_core/bridges/collaboration/test_placeholder_username_repair.pyindex fec17e8be..3495b5e82 100644--- a/core/tests/switch_core/bridges/collaboration/test_placeholder_username_repair.py+++ b/core/tests/switch_core/bridges/collaboration/test_placeholder_username_repair.py@@ -16,7 +16,7 @@ from __future__ import annotationsfrom types import SimpleNamespacefrom typing import Any-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.teams.adapter import (TeamsAdapter,TeamsConnectionConfig,@@ -53,7 +53,7 @@ class _Store:self._user.external_username = external_username-class _Puppet:+class _HumanActorStub:def __init__(self) -> None:self.names: list[str] = []@@ -62,11 +62,11 @@ class _Puppet:class _Lifecycle:- def __init__(self, puppet: Any) -> None:- self._puppet = puppet+ def __init__(self, human_actor: Any) -> None:+ self._human_actor = human_actordef get(self, client_id: str) -> Any:- return self._puppet+ return self._human_actordef _teams_adapter() -> TeamsAdapter:@@ -82,17 +82,17 @@ def _teams_adapter() -> TeamsAdapter:)-def _core(stored_name: str, *, adapter: Any = None, puppet: Any = None) -> Any:+def _core(stored_name: str, *, adapter: Any = None, human_actor: Any = None) -> Any:user = SimpleNamespace(id="eu-1", external_username=stored_name, client_id="client-1")- core = object.__new__(BridgeCore)+ core = object.__new__(CollaborationCore)core._session_factory = lambda: _FakeSession() # type: ignore[attr-defined]core._bridge_id = "bridge-1" # type: ignore[attr-defined]core._bridge_type = "teams" # type: ignore[attr-defined]core._adapter = adapter or _teams_adapter() # type: ignore[attr-defined]core._external_user_store = _Store(user) # type: ignore[attr-defined]- core._client_lifecycle = _Lifecycle(puppet or _Puppet()) # type: ignore[attr-defined]+ core._client_lifecycle = _Lifecycle(human_actor or _HumanActorStub()) # type: ignore[attr-defined]core._names_known_good = set() # type: ignore[attr-defined]return core@@ -117,22 +117,22 @@ def test_teams_does_not_mistake_a_name_for_an_id() -> None:def test_a_platform_whose_handles_are_handles_recognises_nothing() -> None:# The default: nothing to recognise, so nothing is ever renamed.- from switch_core.bridges.collaboration.adapter import CollaborationAdapter+ from switch_core.bridges.collaboration.adapter import PlatformAdapter- assert CollaborationAdapter.is_placeholder_username(None, _TEAMS_ID) is False # type: ignore[arg-type]+ assert PlatformAdapter.is_placeholder_username(None, _TEAMS_ID) is False # type: ignore[arg-type]# ── the repair ───────────────────────────────────────────────────────────────async def test_an_id_is_replaced_by_the_name_and_the_account_renamed() -> None:- puppet = _Puppet()- core = _core(_TEAMS_ID, puppet=puppet)+ human_actor = _HumanActorStub()+ core = _core(_TEAMS_ID, human_actor=human_actor)await core._repair_placeholder_username("aad-1", "ada.lovelace")assert core._external_user_store.renames == [("eu-1", "ada.lovelace")]- assert puppet.names == ["ada.lovelace"]+ assert human_actor.names == ["ada.lovelace"]async def test_a_real_name_already_stored_is_left_alone() -> None:@@ -183,11 +183,11 @@ async def test_an_empty_resolution_is_ignored() -> None:async def test_the_rename_stands_even_if_the_account_cannot_be_relabelled() -> None:# The stored name is what agents address; the Matrix label is cosmetic.# Losing the second is no reason to abandon the first.- class _Failing(_Puppet):+ class _Failing(_HumanActorStub):async def set_display_name(self, name: str) -> None:raise RuntimeError("homeserver said no")- core = _core(_TEAMS_ID, puppet=_Failing())+ core = _core(_TEAMS_ID, human_actor=_Failing())await core._repair_placeholder_username("aad-1", "ada.lovelace")diff --git a/core/tests/switch_core/bridges/collaboration/test_rich_content_port.py b/core/tests/switch_core/bridges/collaboration/test_rich_content_port.pyindex c2cee2e3f..edd1d54c7 100644--- a/core/tests/switch_core/bridges/collaboration/test_rich_content_port.py+++ b/core/tests/switch_core/bridges/collaboration/test_rich_content_port.py@@ -16,7 +16,7 @@ from typing import Anyimport pytestfrom switch_core.bridges.collaboration.adapter import (- CollaborationAdapter,+ PlatformAdapter,RequestCard,RichContentFailed,TurnActivity,@@ -27,7 +27,7 @@ from switch_core.bridges.collaboration.session.renderers.neutral import turn_sumfrom .session_fixtures import _item, _turn, open_request-class _BareAdapter(CollaborationAdapter):+class _BareAdapter(PlatformAdapter):"""Concrete only so it can be instantiated: `post_rich` / `update_rich`are what is under test, and nothing else here is called.diff --git a/core/tests/switch_core/bridges/collaboration/test_room_wide_mention_rendering.py b/core/tests/switch_core/bridges/collaboration/test_room_wide_mention_rendering.pyindex c4a8f36a6..fd95b829b 100644--- a/core/tests/switch_core/bridges/collaboration/test_room_wide_mention_rendering.py+++ b/core/tests/switch_core/bridges/collaboration/test_room_wide_mention_rendering.py@@ -12,8 +12,8 @@ from typing import Anyimport pytest-from switch_core.bridges.collaboration.adapter import CollaborationAdapter-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.adapter import PlatformAdapter+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.discord.adapter import (DiscordAdapter,DiscordConnectionConfig,@@ -244,7 +244,7 @@ def test_the_defusal_is_not_an_adapters_to_forget(platform: str) -> None:# An adapter renders in `_render_outbound`; `translate_outbound` is the# base class's, final, and defuses whatever comes back.assert "translate_outbound" not in type(ADAPTERS[platform]()).__dict__- assert getattr(CollaborationAdapter.translate_outbound, "__final__", False)+ assert getattr(PlatformAdapter.translate_outbound, "__final__", False)# ── The relay ────────────────────────────────────────────────────────────────@@ -253,7 +253,7 @@ def test_the_defusal_is_not_an_adapters_to_forget(platform: str) -> None:class _Recording:"""An adapter that records what the relay asked it to send."""- def __init__(self, platform: CollaborationAdapter) -> None:+ def __init__(self, platform: PlatformAdapter) -> None:self._platform = platformself.sent: list[dict[str, Any]] = []@@ -284,12 +284,12 @@ async def _tenant(*_args: Any, **_kwargs: Any) -> str:return "tenant-1"-def _bridge(adapter: _Recording) -> BridgeCore:- core = object.__new__(BridgeCore)+def _bridge(adapter: _Recording) -> CollaborationCore:+ core = object.__new__(CollaborationCore)core._bridge_type = "slack" # type: ignore[attr-defined]core._adapter = adapter # type: ignore[assignment]- core._puppet_matrix_ids = set() # type: ignore[assignment]- core._bridge_client_matrix_user_id = "@bridge:switch.local" # type: ignore[assignment]+ core._human_user_ids = set() # type: ignore[assignment]+ core._workspace_consumer_transport_user_id = "@bridge:switch.local" # type: ignore[assignment]core._find_channel = lambda **_kwargs: "C1" # type: ignore[assignment]core._channel_to_room = {"C1": ("room-uuid", "!r:switch.local")} # type: ignore[assignment]core._room_tenant = _tenant # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/collaboration/test_session_text_answers.py b/core/tests/switch_core/bridges/collaboration/test_session_text_answers.pyindex 4c721624a..0b8a9cb5b 100644--- a/core/tests/switch_core/bridges/collaboration/test_session_text_answers.py+++ b/core/tests/switch_core/bridges/collaboration/test_session_text_answers.py@@ -14,7 +14,7 @@ from typing import Anyimport pytest-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.models import InboundMessagefrom switch_core.bridges.collaboration.session.form import posted_formfrom switch_core.bridges.collaboration.session.refusal import Refused@@ -93,7 +93,7 @@ def _run(coro: Any) -> Any:def _bridge(approval_answers: Any) -> tuple[Any, list[dict[str, str]]]:"""A bridge core, and the list of messages that got past the answer path.- The channel maps to a room and the puppet step records what it was asked+ The channel maps to a room and the human actor step records what it was askedfor and then hands back nothing, which is where the relay stops. So amessage in that list is one the answer path let through on its way to theroom, and an empty list after a message is a message the room lost.@@ -109,11 +109,11 @@ def _bridge(approval_answers: Any) -> tuple[Any, list[dict[str, str]]]:async def _repair_placeholder_username(*args: Any, **kwargs: Any) -> None:return None- async def _ensure_user_in_matrix_room(**kwargs: str) -> None:+ async def _ensure_human_in_room(**kwargs: str) -> None:relayed.append(kwargs)return None- bridge = BridgeCore.__new__(BridgeCore)+ bridge = CollaborationCore.__new__(CollaborationCore)bridge._channel_to_room = {CHANNEL: ("room-uuid", "!room:test")}bridge._channel_locks = {}bridge._approval_answers = approval_answers@@ -122,7 +122,7 @@ def _bridge(approval_answers: Any) -> tuple[Any, list[dict[str, str]]]:# Instance attrs shadow the class methods so the DB is never touched.bridge._is_registered_agent = _is_registered_agent # type: ignore[assignment]bridge._repair_placeholder_username = _repair_placeholder_username # type: ignore[assignment]- bridge._ensure_user_in_matrix_room = _ensure_user_in_matrix_room # type: ignore[assignment]+ bridge._ensure_human_in_room = _ensure_human_in_room # type: ignore[assignment]return bridge, relayed@@ -171,7 +171,7 @@ def test_a_message_the_grammar_refuses_still_reaches_the_room(said: str) -> None"external_user_id": "U1","external_username": "someone","room_id": "room-uuid",- "matrix_room_id": "!room:test",+ "transport_room_id": "!room:test",}]diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_card_removal.py b/core/tests/switch_core/bridges/collaboration/test_slack_card_removal.pyindex 9798ac3b8..7637813fa 100644--- a/core/tests/switch_core/bridges/collaboration/test_slack_card_removal.py+++ b/core/tests/switch_core/bridges/collaboration/test_slack_card_removal.py@@ -20,7 +20,7 @@ import pytestfrom slack_sdk.errors import SlackApiErrorfrom switch_core.bridges.collaboration.adapter import (- CollaborationAdapter,+ PlatformAdapter,RemovalFailed,RichContentThrottled,)@@ -144,7 +144,7 @@ def test_a_platform_with_no_implementation_refuses_rather_than_pretends() -> Nonand then never redraw it, because the row says there is nothing there."""class Unimplemented:- remove_publication = CollaborationAdapter.remove_publication+ remove_publication = PlatformAdapter.remove_publicationassert getattr(Unimplemented(), "removes_answered_cards", False) is Falsewith pytest.raises(RemovalFailed):diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_sdk_only.py b/core/tests/switch_core/bridges/collaboration/test_teams_sdk_only.pyindex 2d4118d8c..214137f1a 100644--- a/core/tests/switch_core/bridges/collaboration/test_teams_sdk_only.py+++ b/core/tests/switch_core/bridges/collaboration/test_teams_sdk_only.py@@ -180,7 +180,7 @@ async def _card(**kwargs: Any) -> RequestCard:def test_the_publication_is_the_only_account_of_a_turn() -> None:- """There is no second renderer to fall back to, and `bridge_core` reads+ """There is no second renderer to fall back to, and `collaboration_core` readsthis flag to decide whether to route sessions here at all — so a platformthat stopped declaring it would go quiet rather than draw the turn someother way."""diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_zero_config.py b/core/tests/switch_core/bridges/collaboration/test_teams_zero_config.pyindex bb4ef501c..e76ce9a05 100644--- a/core/tests/switch_core/bridges/collaboration/test_teams_zero_config.py+++ b/core/tests/switch_core/bridges/collaboration/test_teams_zero_config.py@@ -12,7 +12,7 @@ from cryptography import x509from cryptography.hazmat.primitives.serialization import load_pem_private_keyfrom pydantic import ValidationError-from switch_core.bridges.collaboration.adapter import CollaborationAdapter+from switch_core.bridges.collaboration.adapter import PlatformAdapterfrom switch_core.bridges.collaboration.lifecycle_service import (CollaborationBridgeLifecycleService,)@@ -249,7 +249,7 @@ async def test_verify_credentials_reports_an_unreachable_microsoft(# ── register() wiring ────────────────────────────────────────────────────────-class _RecordingAdapter(CollaborationAdapter):+class _RecordingAdapter(PlatformAdapter):"""Records the order register() drives the two hooks in."""events: list[str] = []@@ -316,7 +316,7 @@ def _lifecycle() -> CollaborationBridgeLifecycleService:client_store=MagicMock(),client_lifecycle=MagicMock(),room_service=MagicMock(),- matrix_admin=MagicMock(),+ provisioning=MagicMock(),session_factory=MagicMock(),config=MagicMock(),client_factory=MagicMock(),@@ -383,7 +383,7 @@ async def test_exclusive_resource_is_the_listener_port() -> None:def test_outbound_only_adapters_claim_nothing() -> None:"""Slack, Discord and Mattermost dial out; any number can coexist."""- assert CollaborationAdapter.exclusive_resource({}) is None+ assert PlatformAdapter.exclusive_resource({}) is None# The one tenant these tests pretend the deployment has. Named rather than@@ -431,7 +431,7 @@ def _service_with_existing(client_store=MagicMock(),client_lifecycle=MagicMock(),room_service=MagicMock(),- matrix_admin=MagicMock(),+ provisioning=MagicMock(),session_factory=MagicMock(return_value=session),config=MagicMock(),client_factory=MagicMock(),@@ -617,7 +617,7 @@ async def test_concurrent_registration_cannot_take_the_same_port_twice(client_store=MagicMock(),client_lifecycle=MagicMock(),room_service=MagicMock(),- matrix_admin=MagicMock(),+ provisioning=MagicMock(),session_factory=MagicMock(return_value=session),config=MagicMock(),client_factory=MagicMock(),@@ -690,7 +690,7 @@ async def test_start_refuses_a_second_bridge_already_holding_the_port(client_store=MagicMock(),client_lifecycle=MagicMock(),room_service=MagicMock(),- matrix_admin=MagicMock(),+ provisioning=MagicMock(),session_factory=MagicMock(return_value=session),config=MagicMock(),client_factory=MagicMock(),diff --git a/core/tests/switch_core/bridges/collaboration/test_telegram_sdk_only.py b/core/tests/switch_core/bridges/collaboration/test_telegram_sdk_only.pyindex 930f3e0e3..10387af6a 100644--- a/core/tests/switch_core/bridges/collaboration/test_telegram_sdk_only.py+++ b/core/tests/switch_core/bridges/collaboration/test_telegram_sdk_only.py@@ -28,7 +28,7 @@ from telegram.error import (from switch_core.bridges.collaboration.adapter import (ActivityMarkRefused,- CollaborationAdapter,+ PlatformAdapter,RequestCard,RichContentFailed,RichContentThrottled,@@ -125,7 +125,7 @@ def _edited(adapter: TelegramAdapter) -> dict[str, Any]:def test_the_publication_is_the_only_account_of_a_turn() -> None:- """There is no second renderer to fall back to, and `bridge_core` reads+ """There is no second renderer to fall back to, and `collaboration_core` readsthis flag to decide whether to route sessions here at all — so a platformthat stopped declaring it would go quiet rather than draw the turn someother way."""@@ -399,7 +399,7 @@ def test_telegram_says_it_cannot_find_a_card_again_rather_than_implying_it_mightquestion in the chat that silently refuses the answer it asks for."""assert TelegramAdapter.recovers_uncertain_posts is Falseassert (- TelegramAdapter.find_request_card is CollaborationAdapter.find_request_card # noqa: E501 — the base's "nowhere to look"+ TelegramAdapter.find_request_card is PlatformAdapter.find_request_card # noqa: E501 — the base's "nowhere to look")diff --git a/core/tests/switch_core/bridges/resource/test_reference_types_service.py b/core/tests/switch_core/bridges/resource/test_reference_types_service.pyindex 62ad89d3d..cac0c3a92 100644--- a/core/tests/switch_core/bridges/resource/test_reference_types_service.py+++ b/core/tests/switch_core/bridges/resource/test_reference_types_service.py@@ -75,7 +75,7 @@ async def _shadow_github(session: AsyncSession, owner_id: str) -> ReferenceType:async def _make_room(session: AsyncSession, name: str) -> Room:room = Room(- matrix_room_id=f"!{name}:example.invalid",+ transport_room_id=f"!{name}:example.invalid",name=name,description="",)diff --git a/core/tests/switch_core/clients/test_actor_roles.py b/core/tests/switch_core/clients/test_actor_roles.pynew file mode 100644index 000000000..f958dcd7f--- /dev/null+++ b/core/tests/switch_core/clients/test_actor_roles.py@@ -0,0 +1,26 @@+"""Each kind of actor reports itself under its own role in message metrics."""++from __future__ import annotations++from typing import get_args++from switch_core.clients.actor import (+ Actor,+ ActorRole,+ AgentActor,+ HumanActor,+ SystemActor,+)+++def test_every_actor_class_has_its_own_role() -> None:+ roles = {cls: cls.role for cls in (Actor, HumanActor, AgentActor, SystemActor)}+ assert roles == {+ Actor: "bridge",+ HumanActor: "human",+ AgentActor: "agent",+ SystemActor: "system",+ }+ # Every role an actor can have is one a dashboard can expect, and no two+ # kinds of actor share one.+ assert set(roles.values()) == set(get_args(ActorRole.__value__))diff --git a/core/tests/switch_core/clients/test_addressing_enforcement.py b/core/tests/switch_core/clients/test_addressing_enforcement.pyindex f8ad6be17..f845b809c 100644--- a/core/tests/switch_core/clients/test_addressing_enforcement.py+++ b/core/tests/switch_core/clients/test_addressing_enforcement.py@@ -7,7 +7,7 @@ from types import SimpleNamespacefrom switch_core.budgets import BudgetGuardfrom switch_core.clients.admin_messages import AUTO_REPLY_FLAGfrom switch_core.clients.admin_messages import PLATFORM_MARKER as _PLATFORM_MARKER-from switch_core.clients.agent_client import AgentClient+from switch_core.clients.agent_consumer import AgentConsumerfrom switch_core.db.stores.budget_store import BudgetStandingfrom switch_core.delivery.addressing import (ADDRESSING_DENIED_MESSAGE as _ADDRESSING_DENIED_MESSAGE,@@ -69,7 +69,7 @@ class TestResolveSenderPrincipal:return list(claimants)return SimpleNamespace(- _client_store=SimpleNamespace(get_by_matrix_user_id=_get_by_mxid),+ _client_store=SimpleNamespace(get_by_transport_user_id=_get_by_mxid),_agent_store=SimpleNamespace(get_by_client_id=_agent_by_client),_external_user_store=SimpleNamespace(get_by_client_id=_ext_by_client, claimant_ids=_claimant_ids@@ -544,7 +544,7 @@ def _gate_client( # type: ignore[no-untyped-def]sent: list[dict] = []async def _addressing_allowed(- _session, _agent, _matrix_sender, _room_id, _content=None+ _session, _agent, _sender_user_id, _room_id, _content=None): # type: ignore[no-untyped-def]return _AddressingDecision(allowed=allowed, refusal="" if allowed else refusal)@@ -559,11 +559,11 @@ def _gate_client( # type: ignore[no-untyped-def]tenant_id="tenant-1",_budget_guard=BudgetGuard(_FakeBudgetStore(budgets or [])), # type: ignore[arg-type]_addressing_allowed=_addressing_allowed,- send_message=_send_message,+ actor=SimpleNamespace(send_message=_send_message),_sender_handle=_sender_handle,- _triggered_by_auto_reply=AgentClient._triggered_by_auto_reply,+ _triggered_by_auto_reply=AgentConsumer._triggered_by_auto_reply,)- client._post_auto_reply = AgentClient._post_auto_reply.__get__(client)+ client._post_auto_reply = AgentConsumer._post_auto_reply.__get__(client)client.sent = sent # type: ignore[attr-defined]return client@@ -576,7 +576,7 @@ async def _gate(client: SimpleNamespace, event: SimpleNamespace): # type: ignor"""Run the gate and post whatever refusal it hands back, the way on_messagedoes — the gate itself never touches Matrix, so that its caller can closethe database session first."""- outcome = await AgentClient._gate_addressed(+ outcome = await AgentConsumer._gate_addressed(client, None, client.agent, event, _meta())if outcome.refusal is not None:@@ -626,7 +626,7 @@ class TestGateAddressed:# session while the gate runs and must close it before talking to# Matrix.client = _gate_client(allowed=False)- outcome = await AgentClient._gate_addressed(+ outcome = await AgentConsumer._gate_addressed(client, None, client.agent, _event(), _meta())assert outcome.refusal == _ADDRESSING_DENIED_MESSAGE@@ -672,7 +672,7 @@ def _command_client(*, allowed: bool, targets_me: bool): # type: ignore[no-untyreplies: list[dict] = []async def _addressing_allowed(- _session, _agent, _matrix_sender, _room_id, _content=None+ _session, _agent, _sender_user_id, _room_id, _content=None): # type: ignore[no-untyped-def]return _AddressingDecision(allowed=allowed, refusal="" if allowed else _ADDRESSING_DENIED_MESSAGE@@ -707,7 +707,7 @@ class TestGateCommand:async def test_allowed_passes_through(self) -> None:client = _command_client(allowed=True, targets_me=True)- result = await AgentClient._gate_command(+ result = await AgentConsumer._gate_command(client, _room(), _command(args="@fixer"), _meta())assert result is True@@ -715,7 +715,7 @@ class TestGateCommand:async def test_denied_and_explicitly_targeted_replies(self) -> None:client = _command_client(allowed=False, targets_me=True)- result = await AgentClient._gate_command(+ result = await AgentConsumer._gate_command(client, _room(), _command(args="@fixer"), _meta())assert result is False@@ -729,7 +729,7 @@ class TestGateCommand:# `!reset-all-agents` (or a bare `!reset`) makes no claim about this# agent; answering every one would flood a room of restricted agents.client = _command_client(allowed=False, targets_me=False)- result = await AgentClient._gate_command(+ result = await AgentConsumer._gate_command(client, _room(), _command(command="reset-all-agents", args=""), _meta())assert result is False@@ -752,7 +752,7 @@ class TestCommandTargetsMeExplicitly:_text_tags_my_alias=_tags_alias,_text_tags_my_role=_tags_role,)- client._args_tag_my_name = lambda text: AgentClient._args_tag_my_name( # type: ignore[attr-defined]+ client._args_tag_my_name = lambda text: AgentConsumer._args_tag_my_name( # type: ignore[attr-defined]client, text)return client@@ -760,14 +760,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, None, "", "room-1")+ await AgentConsumer._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(+ await AgentConsumer._command_targets_me_explicitly(client, None, "@fixer", "room-1")is True@@ -776,7 +778,7 @@ class TestCommandTargetsMeExplicitly:async def test_another_agents_name_is_not_explicit(self) -> None:client = self._client()assert (- await AgentClient._command_targets_me_explicitly(+ await AgentConsumer._command_targets_me_explicitly(client, None, "@someone-else", "room-1")is False@@ -785,7 +787,7 @@ class TestCommandTargetsMeExplicitly:async def test_alias_is_explicit(self) -> None:client = self._client(alias=True)assert (- await AgentClient._command_targets_me_explicitly(+ await AgentConsumer._command_targets_me_explicitly(client, None, "@nickname", "room-1")is True@@ -794,7 +796,7 @@ class TestCommandTargetsMeExplicitly:async def test_held_role_is_explicit(self) -> None:client = self._client(role=True)assert (- await AgentClient._command_targets_me_explicitly(+ await AgentConsumer._command_targets_me_explicitly(client, None, "@manager", "room-1")is Truediff --git a/core/tests/switch_core/clients/test_agent_client_attachment_groups.py b/core/tests/switch_core/clients/test_agent_consumer_attachment_groups.pysimilarity index 93%rename from core/tests/switch_core/clients/test_agent_client_attachment_groups.pyrename to core/tests/switch_core/clients/test_agent_consumer_attachment_groups.pyindex 82c99589a..3e5a17f73 100644--- a/core/tests/switch_core/clients/test_agent_client_attachment_groups.py+++ b/core/tests/switch_core/clients/test_agent_consumer_attachment_groups.py@@ -5,8 +5,8 @@ from contextlib import asynccontextmanagerfrom types import SimpleNamespacefrom typing import Any-import switch_core.clients.agent_client as ac-from switch_core.clients.agent_client import AgentClient, _GateOutcome+import switch_core.clients.agent_consumer as ac+from switch_core.clients.agent_consumer import AgentConsumer, _GateOutcomefrom switch_core.clients.room_meta import RoomMetafrom switch_core.transport import InboundMedia, RoomRef@@ -65,7 +65,7 @@ def _fake_client() -> SimpleNamespace:queue = _FakeQueue()meta = RoomMeta(room_id="room-1", name="Room", bridge_id="bridge-1")- async def _resolve_room_meta(_matrix_room_id: str) -> RoomMeta:+ async def _resolve_room_meta(_transport_room_id: str) -> RoomMeta:return metaasync def _addressed(event: Any, _meta: RoomMeta) -> bool:@@ -95,15 +95,15 @@ def _fake_client() -> SimpleNamespace:_gate_addressed=_gate_addressed,queue=queue,)- ns._emit_media = AgentClient._emit_media.__get__(ns)+ ns._emit_media = AgentConsumer._emit_media.__get__(ns)ns._schedule_attachment_group_flush = (- AgentClient._schedule_attachment_group_flush.__get__(ns)+ AgentConsumer._schedule_attachment_group_flush.__get__(ns))ns._cancel_attachment_group_flush = (- AgentClient._cancel_attachment_group_flush.__get__(ns)+ AgentConsumer._cancel_attachment_group_flush.__get__(ns))ns._flush_incomplete_attachment_group = (- AgentClient._flush_incomplete_attachment_group.__get__(ns)+ AgentConsumer._flush_incomplete_attachment_group.__get__(ns))return ns@@ -121,7 +121,7 @@ async def test_grouped_media_coalesces_into_one_event() -> None:]for index, (name, mimetype, msgtype) in enumerate(parts):- await AgentClient.on_media(+ await AgentConsumer.on_media(client,_room(),_media_event(@@ -154,7 +154,7 @@ async def test_grouped_media_coalesces_out_of_order() -> None:names = {0: "a.png", 1: "b.png", 2: "c.png"}for index in order:- await AgentClient.on_media(+ await AgentConsumer.on_media(client,_room(),_media_event(@@ -177,7 +177,7 @@ async def test_grouped_media_coalesces_out_of_order() -> None:async def test_ungrouped_media_emits_immediately() -> None:client = _fake_client()- await AgentClient.on_media(+ await AgentConsumer.on_media(client, _room(), _media_event(body="cat.png", mimetype="image/png"))@@ -195,7 +195,7 @@ async def test_incomplete_group_flushes_with_disclosed_notice() -> None:try:client = _fake_client()for index, name in [(0, "cat.png"), (1, "notes.md")]:- await AgentClient.on_media(+ await AgentConsumer.on_media(client,_room(),_media_event(@@ -228,7 +228,7 @@ async def test_group_is_anchored_on_part_zero_not_the_completing_part() -> None:# Part 0 arrives FIRST, so a later part completes the group — otherwise the# completing event happens to be part 0 and the assertion proves nothing.for index, name in [(0, "a.png"), (1, "b.md"), (2, "c.csv")]:- await AgentClient.on_media(+ await AgentConsumer.on_media(client,_room(),_media_event(@@ -250,7 +250,7 @@ async def test_incomplete_group_is_anchored_on_part_zero() -> None:try:client = _fake_client()for index, name in [(0, "a.png"), (2, "c.csv")]:- await AgentClient.on_media(+ await AgentConsumer.on_media(client,_room(),_media_event(@@ -290,7 +290,7 @@ async def test_group_timeout_bounds_the_group_not_the_gap_between_parts(monkeypatch.setattr(asyncio.get_running_loop(), "call_later", call_later)client = _fake_client()- await AgentClient.on_media(+ await AgentConsumer.on_media(client,_room(),_media_event(@@ -306,7 +306,7 @@ async def test_group_timeout_bounds_the_group_not_the_gap_between_parts(# Parts keep trickling in below the deadline; the timer must NOT be# pushed back by each arrival.for index, name in [(1, "b.md"), (2, "c.csv")]:- await AgentClient.on_media(+ await AgentConsumer.on_media(client,_room(),_media_event(@@ -343,7 +343,7 @@ class TestAddressingSurvivesCoalescing:async def test_a_mention_on_part_zero_addresses_the_whole_group(self) -> None:client = _fake_client()for index, name in [(0, "one.png"), (1, "two.png")]:- await AgentClient.on_media(+ await AgentConsumer.on_media(client,_room(),_media_event(@@ -365,7 +365,7 @@ class TestAddressingSurvivesCoalescing:async def test_it_holds_when_the_captioned_part_arrives_last(self) -> None:client = _fake_client()for index, name in [(1, "two.png"), (0, "one.png")]:- await AgentClient.on_media(+ await AgentConsumer.on_media(client,_room(),_media_event(@@ -382,7 +382,7 @@ class TestAddressingSurvivesCoalescing:# The fix must carry addressing across the group, not assert it.client = _fake_client()for index, name in [(0, "one.png"), (1, "two.png")]:- await AgentClient.on_media(+ await AgentConsumer.on_media(client,_room(),_media_event(@@ -402,7 +402,7 @@ class TestAddressingSurvivesCoalescing:ac.ATTACHMENT_GROUP_TIMEOUT_SECONDS = 0.01try:client = _fake_client()- await AgentClient.on_media(+ await AgentConsumer.on_media(client,_room(),_media_event(@@ -412,7 +412,7 @@ class TestAddressingSurvivesCoalescing:group={"id": "grp-addr-partial", "index": 0, "total": 3},),)- await AgentClient.on_media(+ await AgentConsumer.on_media(client,_room(),_media_event(@@ -433,7 +433,7 @@ class TestAddressingSurvivesCoalescing:async def test_a_single_attachment_is_unaffected(self) -> None:# One screenshot always worked; it takes no group and no buffering.client = _fake_client()- await AgentClient.on_media(+ await AgentConsumer.on_media(client, _room(), _media_event(body="@agent-a one picture"))diff --git a/core/tests/switch_core/clients/test_agent_client_pool_checkouts.py b/core/tests/switch_core/clients/test_agent_consumer_pool_checkouts.pysimilarity index 90%rename from core/tests/switch_core/clients/test_agent_client_pool_checkouts.pyrename to core/tests/switch_core/clients/test_agent_consumer_pool_checkouts.pyindex f300d3e66..bc9a5cdad 100644--- a/core/tests/switch_core/clients/test_agent_client_pool_checkouts.py+++ b/core/tests/switch_core/clients/test_agent_consumer_pool_checkouts.py@@ -1,4 +1,4 @@-"""How many pool checkouts one inbound room message costs an agent client.+"""How many pool checkouts one inbound room message costs an agent consumer.A room fans every Matrix message out to *all* of its agent clients at once, ina single event-loop tick. So this number is multiplied by the size of the room@@ -19,9 +19,10 @@ from typing import Anyfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistryfrom switch_core.budgets import BudgetGuard-from switch_core.clients.agent_client import AgentClient+from switch_core.clients.actor import AgentActor+from switch_core.clients.agent_consumer import AgentConsumerfrom switch_core.clients.room_meta import RoomMetafrom switch_core.db.models import Agent, ApiKey, Client, Room, Userfrom switch_core.db.stores.agent_session_store import AgentSessionStore@@ -34,7 +35,7 @@ from switch_core.db.stores.room_store import RoomStorefrom switch_core.delivery.addressing import AddressingResolverfrom switch_core.transport import InboundMessage, RoomRef-MATRIX_ROOM_ID = "!r:test"+TRANSPORT_ROOM_ID = "!r:test"class _CountingSessionFactory:@@ -82,7 +83,7 @@ async def _seed(type="agent",)client = Client(- matrix_user_id=f"@{name}:test",+ transport_user_id=f"@{name}:test",display_name=name,type="agent",)@@ -101,7 +102,7 @@ async def _seed(session.add(agent)await session.flush()agents[name] = agent- room = Room(matrix_room_id=MATRIX_ROOM_ID, name="room", description="d")+ room = Room(transport_room_id=TRANSPORT_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()])@@ -111,25 +112,27 @@ async def _seed(def _client(counting: _CountingSessionFactory, agent: Agent, room_id: str-) -> AgentClient:- """An AgentClient wired to the real stores, with its room-meta cache warm.+) -> AgentConsumer:+ """An AgentConsumer wired to the real stores, with its room-meta cache warm.The cache is warm because that is the steady state: a client resolves aroom 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.tenant_id = agent.tenant_id- client._agent = agent+ actor = object.__new__(AgentActor)+ actor.session_factory = counting # type: ignore[assignment]+ actor.client_store = ClientStore()+ actor.transport_user_id = f"@{agent.name}:test"+ actor.client_id = agent.client_id+ actor.tenant_id = agent.tenant_id+ actor._agent = agent+ client = object.__new__(AgentConsumer)+ client.actor = actorclient._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._connections = AgentConnectionRegistry()client._addressing = AddressingResolver(room_store=client._room_store,room_role_store=client._room_role_store,@@ -141,7 +144,7 @@ def _client(client._budget_guard = BudgetGuard(BudgetStore())client._frontend_base_url = Noneclient._room_meta = {- MATRIX_ROOM_ID: RoomMeta(+ TRANSPORT_ROOM_ID: RoomMeta(room_id=room_id,name="room",bridge_id=None,@@ -152,11 +155,11 @@ def _client(client._attachment_group_timers = {}client.sent = [] # type: ignore[attr-defined]- async def _send_message(matrix_room_id: str, body: str, **kwargs: Any) -> str:+ async def _send_message(transport_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]+ actor.send_message = _send_message # type: ignore[assignment, method-assign]client._event_buffer = SimpleNamespace( # type: ignore[assignment]enqueue=lambda *_a, **_k: None)@@ -165,7 +168,7 @@ def _client(def _message(body: str, sender: str = "@switch-slack-louisa:test") -> InboundMessage:return InboundMessage(- room_id=MATRIX_ROOM_ID,+ room_id=TRANSPORT_ROOM_ID,event_id="$trigger",sender=sender,timestamp=0,@@ -176,7 +179,7 @@ def _message(body: str, sender: str = "@switch-slack-louisa:test") -> InboundMesdef _room() -> RoomRef:- return RoomRef(room_id=MATRIX_ROOM_ID)+ return RoomRef(room_id=TRANSPORT_ROOM_ID)class TestInboundMessageCheckouts:diff --git a/core/tests/switch_core/clients/test_client_construction.py b/core/tests/switch_core/clients/test_client_construction.pyindex 0046050f1..2d28081fd 100644--- a/core/tests/switch_core/clients/test_client_construction.py+++ b/core/tests/switch_core/clients/test_client_construction.py@@ -1,7 +1,7 @@"""Every client subclass must be constructible through the real signature.-Three subclasses take `**kwargs: Any` and forward to `ClientBase`, which-hides the constructor from the type checker: a keyword `ClientBase` no+Three subclasses take `**kwargs: Any` and forward to `Actor`, which+hides the constructor from the type checker: a keyword `Actor` nolonger accepts type-checks clean and fails at runtime, when the clientstarts. That is how a `device_id` left behind by the transport port tookdown all four collaboration bridges while mypy stayed green.@@ -18,16 +18,19 @@ from typing import Anyimport pytest-from switch_core.clients.admin_client import AdminClient-from switch_core.clients.bridge_client import BridgeClient, BridgeClientConfig-from switch_core.clients.client_base import ClientBase, ClientConfig+from switch_core.clients.actor import Actor, ClientConfig, HumanActor, SystemActor+from switch_core.clients.command_consumer import CommandConsumer+from switch_core.clients.workspace_consumer import (+ WorkspaceConsumer,+ WorkspaceConsumerConfig,+)def _base_kwargs() -> dict[str, Any]:return {"client_id": "client-1","tenant_id": "tenant-1",- "matrix_user_id": "@switch-agent-1:switch.local",+ "transport_user_id": "@switch-agent-1:switch.local","display_name": "agent-one","session_factory": object(),"client_store": object(),@@ -35,25 +38,35 @@ def _base_kwargs() -> dict[str, Any]:}-def test_client_base_takes_what_the_factory_passes() -> None:- client = ClientBase(config=ClientConfig(), **_base_kwargs())+def test_an_actor_takes_what_the_factory_passes() -> None:+ client = Actor(config=ClientConfig(), **_base_kwargs())assert client.client_id == "client-1"-def test_bridge_client_construction_matches_its_lifecycle_call_site() -> None:- client = BridgeClient(- bridge_core=object(), # type: ignore[arg-type]- config=BridgeClientConfig(bridge_id="bridge-1"),- **_base_kwargs(),+def test_workspace_consumer_construction_matches_its_lifecycle_call_site() -> None:+ client = WorkspaceConsumer(+ collaboration_core=object(), # type: ignore[arg-type]+ actor=Actor(+ config=WorkspaceConsumerConfig(bridge_id="bridge-1"), **_base_kwargs()+ ),)- assert client.config.bridge_id == "bridge-1"+ assert client.actor.config.bridge_id == "bridge-1"[email protected]("cls", [AdminClient])-def test_every_registered_client_type_constructs(cls: type) -> None:+ ("actor_cls", "cls"),+ [(SystemActor, CommandConsumer), (HumanActor, None)],+)+def test_every_registered_client_type_constructs(+ actor_cls: type, cls: type | None+) -> None:base = _base_kwargs()+ actor = actor_cls(config=actor_cls.config_class(), **base)+ assert isinstance(actor, Actor)+ if cls is None:+ return# Collaborators the factory injects as extra kwargs differ per class, so# stub whatever each one declares rather than naming them here.collaborators: dict[str, Any] = {}@@ -61,22 +74,21 @@ def test_every_registered_client_type_constructs(cls: type) -> None:if (param.kind is not inspect.Parameter.KEYWORD_ONLYor param.default is not inspect.Parameter.empty- or name in base- or name == "config"+ or name == "actor"):continue# A plain object() stands in for a collaborator, but a few are strings# the constructor manipulates on the way in.collaborators[name] = "" if "str" in str(param.annotation) else object()- client = cls(config=cls.config_class(), **base, **collaborators)+ consumer = cls(actor=actor, **collaborators)- assert isinstance(client, ClientBase)+ assert consumer.actor is actordef test_no_client_holds_transport_credentials() -> None:"""A client is a row, not a session: there is nothing to authenticate."""- client = ClientBase(config=ClientConfig(), **_base_kwargs())+ client = Actor(config=ClientConfig(), **_base_kwargs())for attribute in ("access_token", "device_id", "password", "session_state"):assert not hasattr(client, attribute)diff --git a/core/tests/switch_core/clients/test_client_lifecycle_tenant_binding.py b/core/tests/switch_core/clients/test_client_lifecycle_tenant_binding.pyindex 1a023f03a..00e15b169 100644--- a/core/tests/switch_core/clients/test_client_lifecycle_tenant_binding.py+++ b/core/tests/switch_core/clients/test_client_lifecycle_tenant_binding.py@@ -7,7 +7,7 @@ globally unique client id — and then works one room at a time, binding thatroom's tenant per delivery.`_run_client` unbinds first, and the creator matters here more than anywhere-else. A puppet client is minted mid-conversation, from inside an inbound+else. A human actor is minted mid-conversation, from inside an inboundbridge event bound to *that* room's tenant, and then reused for every room theperson it stands for ever speaks in. Whatever the first room was must notbecome the client's identity for the rest of its life.@@ -35,7 +35,7 @@ class _RecordingClient:def __init__(self, seen: list[str | None]) -> None:self.display_name = "recorded"- self.matrix_user_id = "@recorded:test"+ self.transport_user_id = "@recorded:test"self._seen = seenasync def start(self) -> None:@@ -51,7 +51,7 @@ def _service(client_factory: object,) -> ClientLifecycleService:return ClientLifecycleService(- matrix_admin=MagicMock(),+ provisioning=MagicMock(),client_store=ClientStore(),tenant_store=TenantStore(),client_factory=client_factory, # type: ignore[arg-type]@@ -63,18 +63,19 @@ def _service(async def test_a_client_task_runs_with_no_tenant_bound(session_factory: async_sessionmaker[AsyncSession],) -> None:- """The puppet case, in miniature: created from inside a room's tenant,+ """The human actor case, in miniature: created from inside a room's tenant,and it must not keep it."""room_tenant = f"tenant-{uuid.uuid4().hex[:8]}"seen: list[str | None] = []service = _service(session_factory, MagicMock())with tenant_scope(room_tenant):- service._start_task("client-1", _RecordingClient(seen)) # type: ignore[arg-type]+ recording = _RecordingClient(seen)+ service._start_task("client-1", recording, recording) # type: ignore[arg-type]await asyncio.sleep(0)assert seen == [None], (- "the client's task kept the tenant of whatever created it; a puppet "+ "the client's task kept the tenant of whatever created it; a human actor ""reused in a second room would act as the first room's tenant")@@ -83,12 +84,12 @@ async def test_a_client_task_does_not_keep_the_room_it_was_created_in(session_factory: async_sessionmaker[AsyncSession],) -> None:"""The bridge's inbound handler binds its room as log context, and a- puppet minted there must not log as that room for the rest of its life."""+ human actor minted there must not log as that room for the rest of its life."""client = _RecordingClient([])service = _service(session_factory, MagicMock())with log_context(room_id="room-where-it-was-minted"):- service._start_task("client-1", client) # type: ignore[arg-type]+ service._start_task("client-1", client, client) # type: ignore[arg-type]await asyncio.sleep(0)assert client.room_seen is None@@ -111,7 +112,7 @@ async def test_start_all_binds_nothing_around_starting_each_client(session.add(Client(tenant_id=tenant_id,- matrix_user_id=f"@agent-{tenant_id}:test",+ transport_user_id=f"@agent-{tenant_id}:test",display_name="agent",type="agent",)@@ -120,7 +121,10 @@ async def test_start_all_binds_nothing_around_starting_each_client(seen: list[str | None] = []client_factory = MagicMock()- client_factory.create.side_effect = lambda record: _RecordingClient(seen)+ client_factory.create.side_effect = lambda record: (+ (recording := _RecordingClient(seen)),+ recording,+ )service = _service(session_factory, client_factory)await service.start_all()diff --git a/core/tests/switch_core/clients/test_client_registry_tenants.py b/core/tests/switch_core/clients/test_client_registry_tenants.pyindex 835e7a8aa..2d8175597 100644--- a/core/tests/switch_core/clients/test_client_registry_tenants.py+++ b/core/tests/switch_core/clients/test_client_registry_tenants.py@@ -45,7 +45,7 @@ class _StubClient:def __init__(self, record: Client) -> None:self.client_id = record.id- self.matrix_user_id = record.matrix_user_id+ self.transport_user_id = record.transport_user_idself.display_name = record.display_nameself._stopped = asyncio.Event()@@ -58,19 +58,21 @@ class _StubClient:class _StubFactory:def create(self, record: Client) -> Any:- return _StubClient(record)+ # The stub reads for itself: it is the actor and its own consumer.+ client = _StubClient(record)+ return client, clientdef _service(session_factory: async_sessionmaker[AsyncSession],) -> ClientLifecycleService:return ClientLifecycleService(- matrix_admin=MagicMock(),+ provisioning=MagicMock(),client_store=ClientStore(),tenant_store=TenantStore(),client_factory=_StubFactory(), # type: ignore[arg-type]session_factory=session_factory,- config=SimpleNamespace(matrix_server_name="test"), # type: ignore[arg-type]+ config=SimpleNamespace(id_server_name="test"), # type: ignore[arg-type])@@ -78,7 +80,7 @@ def _record(tenant_id: str, client_id: str) -> Client:return Client(id=client_id,tenant_id=tenant_id,- matrix_user_id="@switch-admin:test",+ transport_user_id="@switch-admin:test",display_name="admin",type="admin",)diff --git a/core/tests/switch_core/clients/test_client_task_replacement.py b/core/tests/switch_core/clients/test_client_task_replacement.pyindex 725b3d4d6..a4a4d953e 100644--- a/core/tests/switch_core/clients/test_client_task_replacement.py+++ b/core/tests/switch_core/clients/test_client_task_replacement.py@@ -19,11 +19,12 @@ from switch_core.db.stores.tenant_store import TenantStoreclass _BlockingClient:- """A client whose task never finishes on its own, like a receive loop."""+ """A consumer whose task never finishes on its own, like a receive loop.+ It stands in for its own actor too: the task only reads a name off it."""def __init__(self) -> None:self.display_name = "blocking"- self.matrix_user_id = "@blocking:test"+ self.transport_user_id = "@blocking:test"self.stopped = Falseasync def start(self) -> None:@@ -35,7 +36,7 @@ class _BlockingClient:def _service() -> ClientLifecycleService:return ClientLifecycleService(- matrix_admin=MagicMock(),+ provisioning=MagicMock(),client_store=ClientStore(),tenant_store=TenantStore(),client_factory=MagicMock(),@@ -46,11 +47,13 @@ def _service() -> ClientLifecycleService:async def test_starting_a_client_twice_cancels_the_first_task() -> None:service = _service()- service._start_task("client-1", _BlockingClient()) # type: ignore[arg-type]+ client = _BlockingClient()+ service._start_task("client-1", client, client) # type: ignore[arg-type]await asyncio.sleep(0)first = service._tasks["client-1"]- service._start_task("client-1", _BlockingClient()) # type: ignore[arg-type]+ client = _BlockingClient()+ service._start_task("client-1", client, client) # type: ignore[arg-type]second = service._tasks["client-1"]await asyncio.gather(first, return_exceptions=True)@@ -68,9 +71,10 @@ async def test_stop_all_waits_for_the_tasks_it_cancelled() -> None:service = _service()client = _BlockingClient()service._clients["client-1"] = client # type: ignore[assignment]+ service._consumers["client-1"] = client # type: ignore[assignment]service._client_types["client-1"] = "agent"service._client_tenants["client-1"] = "tenant-1"- service._start_task("client-1", client) # type: ignore[arg-type]+ service._start_task("client-1", client, client) # type: ignore[arg-type]await asyncio.sleep(0)task = service._tasks["client-1"]diff --git a/core/tests/switch_core/clients/test_client_tenant_plumbing.py b/core/tests/switch_core/clients/test_client_tenant_plumbing.pyindex f14b7969a..bf06ac251 100644--- a/core/tests/switch_core/clients/test_client_tenant_plumbing.py+++ b/core/tests/switch_core/clients/test_client_tenant_plumbing.py@@ -2,13 +2,13 @@There was an eighth exempt lookup, `tenant_of_client`, and it was the mostcalled of them: every `PostgresTransport` asked it once, and so did every-`AgentClient.start`. Both were built from a `clients` row that names the+`AgentConsumer.start`. Both were built from a `clients` row that names thetenant in a column, so the question went to the database with the answeralready in hand — and a `SECURITY DEFINER` function nobody needs is still afunction to audit and still one more thing the runtime role's credentialsreach.-So `ClientBase` and `PostgresTransport` take a `tenant_id` the way they take a+So `Actor` and `PostgresTransport` take a `tenant_id` the way they take a`client_id`. That moves the risk rather than removing it: a lookup thatresolves the tenant from a primary key cannot be given the wrong one, and aparameter can. These tests are what stands in for it.@@ -17,7 +17,7 @@ Three things are pinned:- **the factory**, which is the one place the value is read off a row, forboth the client and the transport it is handed;-- **the write path**, because the freshest caller — a puppet minted+- **the write path**, because the freshest caller — a human actor mintedmid-conversation — passes a record that was flushed a moment ago rather thanread back, and `record.tenant_id` has to be populated by then;- **every call site**, by scanning for one that names a `client_id` and not a@@ -38,7 +38,7 @@ import pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerimport switch_core-from switch_core.clients.client_base import ClientBase, ClientConfig+from switch_core.clients.actor import Actor, ClientConfigfrom switch_core.clients.client_factory import ClientFactoryfrom switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.db.models import TENANT_ZERO_ID, Client, Tenant@@ -57,7 +57,7 @@ def _factory(session_factory: async_sessionmaker[AsyncSession]) -> ClientFactoryfactory = ClientFactory(client_store=ClientStore(),session_factory=session_factory,- config=SimpleNamespace(matrix_server_name="test"), # type: ignore[arg-type]+ config=SimpleNamespace(id_server_name="test"), # type: ignore[arg-type]room_store=RoomStore(),message_store=MessageStore(),usage_store=UsageStore(),@@ -66,7 +66,7 @@ def _factory(session_factory: async_sessionmaker[AsyncSession]) -> ClientFactoryinvites=InviteBus(),ephemeral=EphemeralBus(),)- factory.register("user", ClientBase)+ factory.register("user", Actor)return factory@@ -75,8 +75,8 @@ def _record(tenant_id: str) -> Client:return Client(id=f"client-{suffix}",tenant_id=tenant_id,- matrix_user_id=f"@puppet-{suffix}:test",- display_name="a puppet",+ transport_user_id=f"@human-actor-{suffix}:test",+ display_name="a human actor",type="user",)@@ -87,7 +87,7 @@ class TestTheFactoryReadsItOffTheRow:) -> None:tenant_id = f"tenant-{uuid.uuid4().hex[:8]}"- client = _factory(session_factory).create(_record(tenant_id))+ client, _ = _factory(session_factory).create(_record(tenant_id))assert client.tenant_id == tenant_id@@ -101,7 +101,7 @@ class TestTheFactoryReadsItOffTheRow:tenant_id = f"tenant-{uuid.uuid4().hex[:8]}"factory = _factory(session_factory)- client = factory.create(_record(tenant_id))+ client, _ = factory.create(_record(tenant_id))transport = factory.transport_for(client)assert transport.tenant_id == tenant_id # type: ignore[attr-defined]@@ -111,12 +111,12 @@ class TestTheFactoryReadsItOffTheRow:) -> None:"""Required rather than defaulted. A client that fell back to whateverwas ambient would be silently correct in the common case — boot, one- tenant — and silently wrong for the puppet a bridge mints while+ tenant — and silently wrong for the human actor a bridge mints whilehandling another tenant's message."""with pytest.raises(TypeError):- ClientBase( # type: ignore[call-arg]+ Actor( # type: ignore[call-arg]client_id="c",- matrix_user_id="@a:test",+ transport_user_id="@a:test",display_name="a client",session_factory=session_factory,client_store=ClientStore(),@@ -128,7 +128,7 @@ class TestTheFactoryReadsItOffTheRow:class TestAFreshlyWrittenRowAlreadyCarriesIt:"""`create_client` writes the row and hands it straight to the factory.- A puppet is created and started inside one inbound message, so the record+ A human actor is created and started inside one inbound message, so the recordthe factory sees has been flushed rather than read back. `tenant_id` is aPython-side default (`db/models.py`'s `TenantScoped`) applied at flush, andthe session factory does not expire on commit, so the value is there — but@@ -145,17 +145,17 @@ class TestAFreshlyWrittenRowAlreadyCarriesIt:await session.commit()service = ClientLifecycleService(- matrix_admin=MagicMock(),+ provisioning=MagicMock(),client_store=ClientStore(),tenant_store=TenantStore(),client_factory=MagicMock(),session_factory=session_factory,- config=SimpleNamespace(matrix_server_name="test"), # type: ignore[arg-type]+ config=SimpleNamespace(id_server_name="test"), # type: ignore[arg-type])with tenant_scope(tenant_id):record = await service.create_client(- client_type="user", display_name="a puppet"+ client_type="user", display_name="a human actor")assert record.tenant_id == tenant_id@@ -166,16 +166,16 @@ class TestAFreshlyWrittenRowAlreadyCarriesIt:"""The other direction, so the test above is not satisfied by aconstant: with tenant zero bound, that is what the row gets."""service = ClientLifecycleService(- matrix_admin=MagicMock(),+ provisioning=MagicMock(),client_store=ClientStore(),tenant_store=TenantStore(),client_factory=MagicMock(),session_factory=session_factory,- config=SimpleNamespace(matrix_server_name="test"), # type: ignore[arg-type]+ config=SimpleNamespace(id_server_name="test"), # type: ignore[arg-type])record = await service.create_client(- client_type="user", display_name="another puppet"+ client_type="user", display_name="another human actor")assert record.tenant_id == TENANT_ZERO_ID@@ -213,5 +213,5 @@ def test_no_call_site_names_a_client_without_naming_its_tenant() -> None:f"name a client_id and no tenant_id: {offenders}. Take it off the ""`clients` row the client_id came from — every caller is holding one ""— rather than from whatever tenant happens to be bound, which for a "- "puppet minted mid-conversation is the wrong one."+ "human actor minted mid-conversation is the wrong one.")diff --git a/core/tests/switch_core/clients/test_admin_client.py b/core/tests/switch_core/clients/test_command_consumer.pysimilarity index 86%rename from core/tests/switch_core/clients/test_admin_client.pyrename to core/tests/switch_core/clients/test_command_consumer.pyindex 3bf69d0ba..964692689 100644--- a/core/tests/switch_core/clients/test_admin_client.py+++ b/core/tests/switch_core/clients/test_command_consumer.py@@ -5,8 +5,9 @@ from contextlib import asynccontextmanagerfrom types import SimpleNamespacefrom switch_core.bridges.agent.commands import dispatch_admin_command-from switch_core.clients.admin_client import AdminClient+from switch_core.clients.actor import SystemActorfrom switch_core.clients.admin_messages import ADMIN_MARKER, AdminMessageType+from switch_core.clients.command_consumer import CommandConsumerfrom switch_core.events import CommandEventfrom switch_core.transport import InboundMessage, RoomRef@@ -56,7 +57,7 @@ def _admin_client(roles: list[SimpleNamespace] | None = None,live_role_ids: set[str] | None = None,) -> tuple[SimpleNamespace, list[dict[str, object]]]:- """Fake AdminClient surface for the warning methods.+ """Fake CommandConsumer surface for the warning methods.`members`: agent ids in the room. `agents_by_name`: registered agents keyedby lowercased name (the case-insensitive resolver). `roles`: defined room@@ -105,10 +106,12 @@ def _admin_client(})+ actor = SimpleNamespace(send_message=_send_message)+ actor.send_admin = lambda *a, **k: SystemActor.send_admin(actor, *a, **k)client = SimpleNamespace(+ actor=actor,session_factory=_session_factory,_connections=_no_connections(),- send_message=_send_message,_room_store=SimpleNamespace(get_agent_ids=_get_agent_ids),_room_role_store=SimpleNamespace(list_roles=_list_roles,@@ -116,8 +119,7 @@ def _admin_client(),_agent_store=SimpleNamespace(get_by_name_insensitive=_get_by_name_insensitive),)- client._send_admin = lambda *a, **k: AdminClient._send_admin(client, *a, **k)- client._sender_handle = lambda event: AdminClient._sender_handle(client, event)+ client._sender_handle = lambda event: CommandConsumer._sender_handle(client, event)return client, sent@@ -132,7 +134,7 @@ class TestAdminUnreachableRoleWarning:roles = [SimpleNamespace(id="r-mgr", name="manager")]client, sent = _admin_client(roles=roles, live_role_ids=set())event = _event("@manager please review")- await AdminClient._warn_unreachable_roles(+ await CommandConsumer._warn_unreachable_roles(client, _room(), event, "room-1", None)assert len(sent) == 1@@ -143,7 +145,7 @@ class TestAdminUnreachableRoleWarning:roles = [SimpleNamespace(id="r-mgr", name="manager")]client, sent = _admin_client(roles=roles, live_role_ids=set())event = _event("@manager review?", sender_name="bob")- await AdminClient._warn_unreachable_roles(+ await CommandConsumer._warn_unreachable_roles(client, _room(), event, "room-1", None)assert "@bob" in sent[0]["body"]@@ -153,7 +155,7 @@ class TestAdminUnreachableRoleWarning:roles = [SimpleNamespace(id="r-mgr", name="manager")]client, sent = _admin_client(roles=roles, live_role_ids=set())event = _event("@manager please review")- await AdminClient._warn_unreachable_roles(+ await CommandConsumer._warn_unreachable_roles(client, _room(), event, "room-1", "thread-42")assert sent[0]["thread_root_id"] == "thread-42"@@ -162,7 +164,7 @@ class TestAdminUnreachableRoleWarning:roles = [SimpleNamespace(id="r-mgr", name="manager")]client, sent = _admin_client(roles=roles, live_role_ids={"r-mgr"})event = _event("@manager status?")- await AdminClient._warn_unreachable_roles(+ await CommandConsumer._warn_unreachable_roles(client, _room(), event, "room-1", None)assert sent == []@@ -171,7 +173,7 @@ class TestAdminUnreachableRoleWarning:roles = [SimpleNamespace(id="r-mgr", name="manager")]client, sent = _admin_client(roles=roles, live_role_ids=set())event = _event("just chatting, no tags")- await AdminClient._warn_unreachable_roles(+ await CommandConsumer._warn_unreachable_roles(client, _room(), event, "room-1", None)assert sent == []@@ -180,7 +182,7 @@ class TestAdminUnreachableRoleWarning:roles = [SimpleNamespace(id="r-lead", name="lead")]client, sent = _admin_client(roles=roles, live_role_ids=set())event = _event("@lead-dev ping")- await AdminClient._warn_unreachable_roles(+ await CommandConsumer._warn_unreachable_roles(client, _room(), event, "room-1", None)assert sent == []@@ -195,7 +197,9 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(agents_by_name=agents)event = _event("@web-searcher can you look this up?")- await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)+ await CommandConsumer._warn_absent_agents(+ client, _room(), event, "room-1", None+ )assert len(sent) == 1assert "web-searcher" in sent[0]["body"]assert "isn't in this room" in sent[0]["body"]@@ -209,7 +213,9 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(agents_by_name=agents)event = _event("@web-searcher ping", sender_name="carol")- await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)+ await CommandConsumer._warn_absent_agents(+ client, _room(), event, "room-1", None+ )assert "@carol" in sent[0]["body"]assert sent[0]["mentions"] == ["@carol:switch.local"]@@ -221,7 +227,7 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(agents_by_name=agents)event = _event("@web-searcher ping")- await AdminClient._warn_absent_agents(+ await CommandConsumer._warn_absent_agents(client, _room(), event, "room-1", "thread-42")assert sent[0]["thread_root_id"] == "thread-42"@@ -234,14 +240,18 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(members={"a-web"}, agents_by_name=agents)event = _event("@web-searcher status?")- await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)+ await CommandConsumer._warn_absent_agents(+ client, _room(), event, "room-1", None+ )assert sent == []async def test_no_warning_for_unknown_token(self) -> None:# A human user or a typo resolves to no agent — stay silent.client, sent = _admin_client(agents_by_name={})event = _event("@dave what do you think?")- await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)+ await CommandConsumer._warn_absent_agents(+ client, _room(), event, "room-1", None+ )assert sent == []async def test_prefix_name_not_falsely_warned(self) -> None:@@ -252,7 +262,9 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(agents_by_name=agents)event = _event("@cc-bug-fixing-2 please run")- await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)+ await CommandConsumer._warn_absent_agents(+ client, _room(), event, "room-1", None+ )assert sent == []async def test_room_wide_mention_word_skipped(self) -> None:@@ -264,7 +276,9 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(agents_by_name=agents)event = _event("@everyone the deploy is at five")- await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)+ await CommandConsumer._warn_absent_agents(+ client, _room(), event, "room-1", None+ )assert sent == []async def test_role_token_skipped(self) -> None:@@ -272,7 +286,9 @@ class TestAdminAbsentAgentWarning:roles = [SimpleNamespace(id="r-mgr", name="manager")]client, sent = _admin_client(agents_by_name={}, roles=roles)event = _event("@manager please review")- await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)+ await CommandConsumer._warn_absent_agents(+ client, _room(), event, "room-1", None+ )assert sent == []async def test_combines_multiple_absent_agents(self) -> None:@@ -286,7 +302,9 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(agents_by_name=agents)event = _event("@web-searcher @doc-expert can you pair up?")- await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)+ await CommandConsumer._warn_absent_agents(+ client, _room(), event, "room-1", None+ )assert len(sent) == 1assert "web-searcher" in sent[0]["body"]assert "doc-expert" in sent[0]["body"]@@ -302,7 +320,9 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(agents_by_name=agents)event = _event("@switchdev can you look this up?")- await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)+ await CommandConsumer._warn_absent_agents(+ client, _room(), event, "room-1", None+ )assert "**Switch Dev (`switchdev`)**" in sent[0]["body"]async def test_warning_without_a_display_name_names_it_once(self) -> None:@@ -311,7 +331,9 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(agents_by_name=agents)event = _event("@switchdev ping")- await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)+ await CommandConsumer._warn_absent_agents(+ client, _room(), event, "room-1", None+ )assert "**switchdev**" in sent[0]["body"]assert "(`switchdev`)" not in sent[0]["body"]@@ -323,7 +345,9 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(agents_by_name=agents)event = _event("@switchdev ping", sender_name="carol")- await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)+ await CommandConsumer._warn_absent_agents(+ client, _room(), event, "room-1", None+ )body = sent[0]["body"]# The one live mention left is the asker the notice is addressed to.assert _MENTION.findall(body) == ["@carol"]@@ -339,7 +363,9 @@ class TestAdminAbsentAgentWarning:}client, sent = _admin_client(agents_by_name=agents)event = _event("@switchdev ping")- await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)+ await CommandConsumer._warn_absent_agents(+ client, _room(), event, "room-1", None+ )assert "](https://example.invalid)" not in sent[0]["body"]@@ -361,7 +387,7 @@ def _command_host() -> tuple[SimpleNamespace, list[dict[str, object]]]:):sent.append({"body": body, "thread_root_id": thread_root_id})- async def _is_direct_room(_matrix_room_id: str) -> bool:+ async def _is_direct_room(_transport_room_id: str) -> bool:return Falsehost = SimpleNamespace(@@ -374,7 +400,7 @@ def _command_host() -> tuple[SimpleNamespace, list[dict[str, object]]]:class TestAdminCommandDispatch:async def test_reply_command_is_marked_as_command_result(self) -> None:client, sent = _admin_client()- client.reply_command = lambda *a, **k: AdminClient.reply_command(+ client.reply_command = lambda *a, **k: CommandConsumer.reply_command(client, *a, **k)await client.reply_command("!m", "the result")diff --git a/core/tests/switch_core/clients/test_ensure_system_client.py b/core/tests/switch_core/clients/test_ensure_system_client.pyindex eb42b26cb..4312b8c45 100644--- a/core/tests/switch_core/clients/test_ensure_system_client.py+++ b/core/tests/switch_core/clients/test_ensure_system_client.py@@ -47,12 +47,12 @@ def _service(session_factory: async_sessionmaker[AsyncSession],) -> ClientLifecycleService:return ClientLifecycleService(- matrix_admin=MagicMock(),+ provisioning=MagicMock(),client_store=ClientStore(),tenant_store=TenantStore(),client_factory=MagicMock(),session_factory=session_factory,- config=SimpleNamespace(matrix_server_name="test"), # type: ignore[arg-type]+ config=SimpleNamespace(id_server_name="test"), # type: ignore[arg-type])@@ -83,7 +83,7 @@ async def test_a_fresh_database_gets_an_admin_client_rather_than_an_exception(clients = await _admin_clients(rls_harness.owner)assert [c.tenant_id for c in clients] == [TENANT_ZERO_ID]- assert clients[0].matrix_user_id == "@switch-admin:test"+ assert clients[0].transport_user_id == "@switch-admin:test"async def test_each_tenant_gets_its_own_row(rls_harness: RLSHarness) -> None:@@ -150,4 +150,4 @@ async def test_a_tenant_created_after_startup_gets_a_working_admin_client(clients = await _admin_clients(rls_harness.owner)assert sorted(c.tenant_id for c in clients) == sorted([TENANT_ZERO_ID, tenant.id])acme_client = next(c for c in clients if c.tenant_id == tenant.id)- assert acme_client.matrix_user_id == "@switch-admin:test"+ assert acme_client.transport_user_id == "@switch-admin:test"diff --git a/core/tests/switch_core/clients/test_join_greeting_suppression.py b/core/tests/switch_core/clients/test_join_greeting_suppression.pyindex ff759a54d..4106abdf8 100644--- a/core/tests/switch_core/clients/test_join_greeting_suppression.py+++ b/core/tests/switch_core/clients/test_join_greeting_suppression.py@@ -4,7 +4,7 @@ from types import SimpleNamespaceimport pytest-from switch_core.clients.agent_client import AgentClient+from switch_core.clients.agent_consumer import AgentConsumerclass _Recorder:@@ -24,10 +24,10 @@ def _fake_self(is_direct: bool = False,agent_greetings_enabled: bool = True,) -> SimpleNamespace:- async def _is_direct_room(_matrix_room_id: str) -> bool:+ async def _is_direct_room(_transport_room_id: str) -> bool:return is_direct- async def _resolve_room_meta(_matrix_room_id: str) -> SimpleNamespace:+ async def _resolve_room_meta(_transport_room_id: str) -> SimpleNamespace:return SimpleNamespace(room_id="room-uuid",name="Some Room",@@ -40,7 +40,7 @@ def _fake_self(agent=SimpleNamespace(id="agent-1", name="cc-bug-fixing"),_is_direct_room=_is_direct_room,_resolve_room_meta=_resolve_room_meta,- send_message=send_message,+ actor=SimpleNamespace(send_message=send_message),)@@ -53,7 +53,7 @@ async def test_self_join_greeting_suppressed_when_disabled() -> None:# CHOO-617: when the room's bridge has agent greetings toggled off, the# per-agent self-join greeting is suppressed.send_message = _Recorder()- await AgentClient.on_self_join(+ await AgentConsumer.on_self_join(_fake_self(send_message, agent_greetings_enabled=False), _ROOM, _EVENT)assert send_message.calls == []@@ -62,7 +62,7 @@ async def test_self_join_greeting_suppressed_when_disabled() -> None:@pytest.mark.asyncioasync def test_self_join_greeting_sent_when_enabled() -> None:send_message = _Recorder()- await AgentClient.on_self_join(+ await AgentConsumer.on_self_join(_fake_self(send_message, agent_greetings_enabled=True), _ROOM, _EVENT)assert len(send_message.calls) == 1@@ -73,7 +73,7 @@ async def test_direct_greeting_suppressed_when_disabled() -> None:# The toggle also covers the 1:1 "Hi! I'm …" greeting — it's an agent# greeting too.send_message = _Recorder()- await AgentClient.on_self_join(+ await AgentConsumer.on_self_join(_fake_self(send_message, is_direct=True, agent_greetings_enabled=False),_ROOM,_EVENT,@@ -84,7 +84,7 @@ async def test_direct_greeting_suppressed_when_disabled() -> None:@pytest.mark.asyncioasync def test_direct_greeting_sent_when_enabled() -> None:send_message = _Recorder()- await AgentClient.on_self_join(+ await AgentConsumer.on_self_join(_fake_self(send_message, is_direct=True, agent_greetings_enabled=True),_ROOM,_EVENT,diff --git a/core/tests/switch_core/clients/test_mention_routing.py b/core/tests/switch_core/clients/test_mention_routing.pyindex 3bafeeb00..41f98492d 100644--- a/core/tests/switch_core/clients/test_mention_routing.py+++ b/core/tests/switch_core/clients/test_mention_routing.py@@ -8,9 +8,9 @@ import pytest_asynciofrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.agent.commands import _addressed_by_name_or_role-from switch_core.clients.agent_client import (+from switch_core.clients.agent_consumer import (_STARTING_SESSION_MESSAGE,- AgentClient,+ AgentConsumer,_role_elsewhere_message,)from switch_core.delivery.addressing import (@@ -74,12 +74,12 @@ def _resolver(**attrs: object) -> SimpleNamespace:def _client(name: str) -> SimpleNamespace:- """An AgentClient-shaped double: an agent, an mxid, and a resolver."""+ """An AgentConsumer-shaped double: an agent, an mxid, and a resolver."""return SimpleNamespace(agent=SimpleNamespace(name=name),- matrix_user_id=f"@switch-agent-{name}:switch.local",+ transport_user_id=f"@switch-agent-{name}:switch.local",_addressing=_resolver(),- _as_incoming=AgentClient._as_incoming,+ _as_incoming=AgentConsumer._as_incoming,)@@ -87,7 +87,7 @@ def _is_mentioned(name: str, body: str) -> bool:return AddressingResolver.mentions_name(_resolver(),agent=SimpleNamespace(name=name), # type: ignore[arg-type]- agent_matrix_id=f"@switch-agent-{name}:switch.local",+ agent_user_id=f"@switch-agent-{name}:switch.local",message=_event(body),)@@ -98,7 +98,9 @@ async def _command_addresses(name: str, args: str) -> bool:client = SimpleNamespace(agent=SimpleNamespace(name=name), session_factory=_session_factory)- client._args_tag_my_name = lambda text: AgentClient._args_tag_my_name(client, text)+ client._args_tag_my_name = lambda text: AgentConsumer._args_tag_my_name(+ client, text+ )async def _no(_session: object, _text: str, _room_id: str) -> bool:return False@@ -157,7 +159,7 @@ class TestTruePositives:body="hello",formatted_body='<a href="...@switch-agent-cc-bug-fixing:switch.local">x</a>',)- assert AgentClient._is_mentioned(client, event) is True+ assert AgentConsumer._is_mentioned(client, event) is Trueclass TestMediaEventWithoutFormattedBody:@@ -173,19 +175,19 @@ class TestMediaEventWithoutFormattedBody:media_event = SimpleNamespace(body="@cc-bug-fixing look at this", content={}, sender="@u:test")- assert AgentClient._is_mentioned(client, media_event) is True+ assert AgentConsumer._is_mentioned(client, media_event) is Truedef test_media_without_mention_not_addressed(self) -> None:client = _client("cc-bug-fixing")media_event = SimpleNamespace(body="cat.png", content={}, sender="@u:test")- assert AgentClient._is_mentioned(client, media_event) is False+ assert AgentConsumer._is_mentioned(client, media_event) is Falseclass TestStripMention:def test_strips_exact_mention_only(self) -> None:client = _client("cc-bug-fixing")# Should strip its own mention...- assert AgentClient._strip_mention(client, "@cc-bug-fixing hello").strip() == (+ assert AgentConsumer._strip_mention(client, "@cc-bug-fixing hello").strip() == ("hello")@@ -193,7 +195,7 @@ class TestStripMention:client = _client("cc-bug-fixing")# ...but must not partially strip a longer agent's mention.assert (- AgentClient._strip_mention(client, "@cc-bug-fixing-2 hello")+ AgentConsumer._strip_mention(client, "@cc-bug-fixing-2 hello")== "@cc-bug-fixing-2 hello")@@ -224,7 +226,7 @@ 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(+ await AgentConsumer._text_tags_my_role(client, None, "@manager review", "room-1")is True@@ -234,7 +236,7 @@ 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(+ await AgentConsumer._text_tags_my_role(client, None, "@manager review", "room-1")is False@@ -244,7 +246,7 @@ 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(+ await AgentConsumer._text_tags_my_role(client, None, "@manager review", "room-1")is False@@ -254,7 +256,7 @@ 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(+ await AgentConsumer._text_tags_my_role(client, None, "@lead-dev ping", "room-1")is False@@ -263,7 +265,7 @@ class TestRoleMentionRouting: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, None, "no at here", "room-1")+ await AgentConsumer._text_tags_my_role(client, None, "no at here", "room-1")is False)@@ -290,7 +292,7 @@ class TestAliasMentionRouting:async def test_alias_addresses_agent(self) -> None:client = _alias_client("claude-code.aq-switch-2", {"room-1": "fixer"})assert (- await AgentClient._text_tags_my_alias(+ await AgentConsumer._text_tags_my_alias(client, None, "@fixer please look", "room-1")is True@@ -299,7 +301,7 @@ 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, None, "@FIXER hi", "room-1")+ await AgentConsumer._text_tags_my_alias(client, None, "@FIXER hi", "room-1")is True)@@ -307,14 +309,14 @@ class TestAliasMentionRouting:# 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, None, "@fixer hi", "room-2")+ await AgentConsumer._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, None, "@fixer hi", "room-1")+ await AgentConsumer._text_tags_my_alias(client, None, "@fixer hi", "room-1")is False)@@ -322,14 +324,18 @@ 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, None, "@fixer ping", "room-1")+ await AgentConsumer._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, None, "no at here", "room-1")+ await AgentConsumer._text_tags_my_alias(+ client, None, "no at here", "room-1"+ )is False)@@ -344,21 +350,21 @@ 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, None, "@manager", "room-1")+ await AgentConsumer._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, None, "@manager", "room-1")+ await AgentConsumer._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, None, "@lead-dev", "room-1")+ await AgentConsumer._text_tags_my_role(client, None, "@lead-dev", "room-1")is False)@@ -460,7 +466,7 @@ class TestUnavailableHereReply:) -> 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(+ msg = await AgentConsumer._reply_when_unavailable_here(client, db, client.agent, _here(), "asker")assert msg == _role_elsewhere_message("Room room-B")@@ -471,7 +477,7 @@ 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(+ msg = await AgentConsumer._reply_when_unavailable_here(client, db, client.agent, _here(), "asker")assert msg == "ELSEWHERE: Room room-B, Room room-C"@@ -482,7 +488,7 @@ class TestUnavailableHereReply:# 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(+ await AgentConsumer._reply_when_unavailable_here(client, db, client.agent, _here(), "asker")== "OFFLINE"@@ -491,7 +497,7 @@ class TestUnavailableHereReply:async def test_no_live_sessions_is_offline(self, db: AsyncSession) -> None:client = _unavailable_client(live_rooms=[], role_here=False)assert (- await AgentClient._reply_when_unavailable_here(+ await AgentConsumer._reply_when_unavailable_here(client, db, client.agent, _here(), "asker")== "OFFLINE"@@ -506,14 +512,14 @@ class TestConnectedNotLive:self, db: AsyncSession) -> None:client = _unavailable_client(live_rooms=[], role_here=False, bound_here=True)- msg = await AgentClient._reply_when_unavailable_here(+ msg = await AgentConsumer._reply_when_unavailable_here(client, db, client.agent, _here(), "asker")assert msg == "NOT_LIVE"async def test_no_binding_is_offline(self, db: AsyncSession) -> None:client = _unavailable_client(live_rooms=[], role_here=False, bound_here=False)- msg = await AgentClient._reply_when_unavailable_here(+ msg = await AgentConsumer._reply_when_unavailable_here(client, db, client.agent, _here(), "asker")assert msg == "OFFLINE"@@ -528,7 +534,7 @@ class TestConnectedNotLive:connection_model="session_passive",bound_here=True,)- msg = await AgentClient._reply_when_unavailable_here(+ msg = await AgentConsumer._reply_when_unavailable_here(client, db, client.agent, _here(), "asker")assert msg == "OFFLINE"@@ -541,7 +547,7 @@ 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(+ msg = await AgentConsumer._reply_when_unavailable_here(client, db, client.agent, _here(), "asker")assert msg == "NOT_LIVE"@@ -553,7 +559,7 @@ class TestConnectedNotLive:client = _unavailable_client(live_rooms=["room-B"], role_here=False, bound_here=True)- msg = await AgentClient._reply_when_unavailable_here(+ msg = await AgentConsumer._reply_when_unavailable_here(client, db, client.agent, _here(), "asker")assert msg == "ELSEWHERE: Room room-B"@@ -568,7 +574,7 @@ class TestStartingASessionIsAPromise:client = _unavailable_client(live_rooms=[], role_here=False, connection_model="auto_session", spawns=True)- msg = await AgentClient._reply_when_unavailable_here(+ msg = await AgentConsumer._reply_when_unavailable_here(client, db, client.agent, _here(), "asker")assert msg == _STARTING_SESSION_MESSAGE@@ -583,7 +589,7 @@ class TestStartingASessionIsAPromise:connection_model="auto_session",watching=True,)- msg = await AgentClient._reply_when_unavailable_here(+ msg = await AgentConsumer._reply_when_unavailable_here(client, db, client.agent, _here(), "asker")assert msg == _STARTING_SESSION_MESSAGE@@ -604,7 +610,7 @@ class TestStartingASessionIsAPromise:connection_model="auto_session",connected=True,)- msg = await AgentClient._reply_when_unavailable_here(+ msg = await AgentConsumer._reply_when_unavailable_here(client, db, client.agent, _here(), "asker")assert msg == "OFFLINE"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 1f67a9c74..335f8666a 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@@ -6,10 +6,10 @@ from types import SimpleNamespaceimport pytestfrom switch_core.clients.admin_messages import PLATFORM_MARKER-from switch_core.clients.agent_client import (+from switch_core.clients.agent_consumer import (_STARTING_SESSION_MESSAGE,AUTO_REPLY_FLAG,- AgentClient,+ AgentConsumer,_GateOutcome,)from switch_core.transport import InboundMessage, RoomRef@@ -44,9 +44,9 @@ def _fake_self(send_message: _Recorder,unavailable_reply: str = "I don't have a session connected to this room.",) -> SimpleNamespace:- """A minimal AgentClient stand-in: addressed, offline, non-moderator."""+ """A minimal AgentConsumer stand-in: addressed, offline, non-moderator."""- async def _resolve_room_meta(_matrix_room_id: str) -> SimpleNamespace:+ async def _resolve_room_meta(_transport_room_id: str) -> SimpleNamespace:return _meta()def _addressed_without_lookup(_event: object, _meta: object) -> bool:@@ -84,13 +84,13 @@ def _fake_self(_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,+ _triggered_by_auto_reply=AgentConsumer._triggered_by_auto_reply,+ actor=SimpleNamespace(send_message=send_message),_event_buffer=SimpleNamespace(enqueue=lambda *a, **k: None),)# 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)+ ns._sender_handle = AgentConsumer._sender_handle.__get__(ns)+ ns._post_auto_reply = AgentConsumer._post_auto_reply.__get__(ns)return ns@@ -114,7 +114,7 @@ def _event(thread_id: str | None, *, is_auto_reply: bool = False) -> InboundMessasync def test_no_session_reply_threads_under_triggering_mention() -> None:send_message = _Recorder()room = RoomRef(room_id="!matrix:server")- await AgentClient.on_message(+ await AgentConsumer.on_message(_fake_self(send_message), room, _event(thread_id="$thread-root"))@@ -134,8 +134,8 @@ async def test_no_session_reply_threads_under_triggering_mention() -> None:@pytest.mark.asyncioasync def test_a_command_reply_is_not_metered() -> None:send_message = _Recorder()- await AgentClient.reply_command(- SimpleNamespace(send_message=send_message), # type: ignore[arg-type]+ await AgentConsumer.reply_command(+ SimpleNamespace(actor=SimpleNamespace(send_message=send_message)), # type: ignore[arg-type]"!matrix:server","the result",)@@ -150,7 +150,7 @@ async def test_no_session_reply_not_triggered_by_another_auto_reply() -> None:# reply, so the loop can never form.send_message = _Recorder()room = RoomRef(room_id="!matrix:server")- await AgentClient.on_message(+ await AgentConsumer.on_message(_fake_self(send_message),room,_event(thread_id="$thread-root", is_auto_reply=True),@@ -166,7 +166,7 @@ async def test_no_session_reply_does_not_double_tag_the_asker() -> None:# tag them once, not "@louisa @louisa".send_message = _Recorder()room = RoomRef(room_id="!matrix:server")- await AgentClient.on_message(+ await AgentConsumer.on_message(_fake_self(send_message, unavailable_reply="@louisa\n\nmy operator should run …"),@@ -186,7 +186,7 @@ async def test_no_session_reply_tags_distinct_asker_and_operator() -> None:# both the asker and that operator are tagged.send_message = _Recorder()room = RoomRef(room_id="!matrix:server")- await AgentClient.on_message(+ await AgentConsumer.on_message(_fake_self(send_message, unavailable_reply="@operator\n\nmy operator should run …"),@@ -219,7 +219,7 @@ class TestStartingSessionNoticeGoesWhereItWasAsked:send_message = _Recorder()room = RoomRef(room_id="!matrix:server")- await AgentClient.on_message(+ await AgentConsumer.on_message(_fake_self(send_message, unavailable_reply=_STARTING_SESSION_MESSAGE),room,_event(thread_id=None),@@ -236,7 +236,7 @@ class TestStartingSessionNoticeGoesWhereItWasAsked:send_message = _Recorder()room = RoomRef(room_id="!matrix:server")- await AgentClient.on_message(+ await AgentConsumer.on_message(_fake_self(send_message, unavailable_reply=_STARTING_SESSION_MESSAGE),room,_event(thread_id="$thread-root"),@@ -260,7 +260,7 @@ class TestTerminalReplyThreadsOffTheTrigger:send_message = _Recorder()room = RoomRef(room_id="!matrix:server")- await AgentClient.on_message(+ await AgentConsumer.on_message(_fake_self(send_message), room, _event(thread_id=None))@@ -274,7 +274,7 @@ class TestTerminalReplyThreadsOffTheTrigger:send_message = _Recorder()room = RoomRef(room_id="!matrix:server")- await AgentClient.on_message(+ await AgentConsumer.on_message(_fake_self(send_message), room, _event(thread_id="$thread-root"))@@ -293,7 +293,7 @@ async def test_a_kickoff_that_wants_the_channel_gets_its_reply_at_top_level() ->"on_behalf_of": {"user_id": "u9", "name": "dantas.abel"},"reply_in_channel": True,}- await AgentClient.on_message(_fake_self(send_message), room, event)+ await AgentConsumer.on_message(_fake_self(send_message), room, event)assert len(send_message.calls) == 1assert send_message.calls[0]["thread_root_id"] is Nonediff --git a/core/tests/switch_core/clients/test_offline_owner_reply.py b/core/tests/switch_core/clients/test_offline_owner_reply.pyindex 20d5f8b03..04d41aaeb 100644--- a/core/tests/switch_core/clients/test_offline_owner_reply.py+++ b/core/tests/switch_core/clients/test_offline_owner_reply.py@@ -2,7 +2,7 @@ from __future__ import annotationsfrom types import SimpleNamespace-from switch_core.clients.agent_client import AgentClient, _offline_owner_message+from switch_core.clients.agent_consumer import AgentConsumer, _offline_owner_message"""The reply an auto_session agent gives when it is addressed and nothing isthere to bring it online (CHOO-2344).@@ -54,7 +54,7 @@ def _client(owner_handle: str | None) -> SimpleNamespace:async def _reply(client: SimpleNamespace, agent: SimpleNamespace, **kwargs: object) -> str:- return await AgentClient._unavailable_reply(+ return await AgentConsumer._unavailable_reply(client,None,_meta(),diff --git a/core/tests/switch_core/clients/test_owner_notification_handle.py b/core/tests/switch_core/clients/test_owner_notification_handle.pyindex 1eb0b4610..902884054 100644--- a/core/tests/switch_core/clients/test_owner_notification_handle.py+++ b/core/tests/switch_core/clients/test_owner_notification_handle.py@@ -14,7 +14,7 @@ from __future__ import annotationsfrom types import SimpleNamespace-from switch_core.clients.agent_client import AgentClient+from switch_core.clients.agent_consumer import AgentConsumerdef _claimed(bridge_id: str, username: str) -> SimpleNamespace:@@ -39,7 +39,7 @@ 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(+ handle = await AgentConsumer.owner_handle_in(client, None, _agent("u1"), "slack-1")@@ -53,7 +53,9 @@ class TestResolvingTheOwnersHandle:)assert (- await AgentClient.owner_handle_in(client, None, _agent("u1"), "telegram-1")+ await AgentConsumer.owner_handle_in(+ client, None, _agent("u1"), "telegram-1"+ )== "louisa")@@ -63,7 +65,9 @@ class TestResolvingTheOwnersHandle:client = _client([_claimed("slack-1", "louis.amaudruz")])assert (- await AgentClient.owner_handle_in(client, None, _agent("u1"), "telegram-1")+ await AgentConsumer.owner_handle_in(+ client, None, _agent("u1"), "telegram-1"+ )is None)@@ -71,7 +75,7 @@ class TestResolvingTheOwnersHandle:client = _client([_claimed("slack-1", "louis.amaudruz")])assert (- await AgentClient.owner_handle_in(client, None, _agent(None), "slack-1")+ await AgentConsumer.owner_handle_in(client, None, _agent(None), "slack-1")is None)@@ -80,7 +84,8 @@ class TestResolvingTheOwnersHandle:client = _client([_claimed("slack-1", "louis.amaudruz")])assert (- await AgentClient.owner_handle_in(client, None, _agent("u1"), None) is None+ await AgentConsumer.owner_handle_in(client, None, _agent("u1"), None)+ is None)async def test_the_same_account_every_time_when_they_hold_several(self) -> None:@@ -88,8 +93,10 @@ class TestResolvingTheOwnersHandle:# between one message and the next.client = _client([_claimed("slack-1", "zoe"), _claimed("slack-1", "adam")])- first = await AgentClient.owner_handle_in(client, None, _agent("u1"), "slack-1")- second = await AgentClient.owner_handle_in(+ first = await AgentConsumer.owner_handle_in(+ client, None, _agent("u1"), "slack-1"+ )+ second = await AgentConsumer.owner_handle_in(client, None, _agent("u1"), "slack-1")diff --git a/core/tests/switch_core/clients/test_platform_sender_replies.py b/core/tests/switch_core/clients/test_platform_sender_replies.pyindex 7827a3e78..1e9188aea 100644--- a/core/tests/switch_core/clients/test_platform_sender_replies.py+++ b/core/tests/switch_core/clients/test_platform_sender_replies.py@@ -7,7 +7,7 @@ from __future__ import annotationsfrom types import SimpleNamespacefrom switch_core.clients.admin_messages import PLATFORM_MARKER-from switch_core.clients.agent_client import AgentClient+from switch_core.clients.agent_consumer import AgentConsumerfrom switch_core.transport import InboundMessage@@ -25,7 +25,7 @@ def _event(content: dict) -> InboundMessage:def _handle(event: InboundMessage) -> str:ns = SimpleNamespace()- return AgentClient._sender_handle(ns, event) # type: ignore[arg-type]+ return AgentConsumer._sender_handle(ns, event) # type: ignore[arg-type]def test_reply_handle_is_the_person_behind_a_platform_message() -> None:diff --git a/core/tests/switch_core/clients/test_removed_from_room.py b/core/tests/switch_core/clients/test_removed_from_room.pyindex b1c29d831..1c80a59ef 100644--- a/core/tests/switch_core/clients/test_removed_from_room.py+++ b/core/tests/switch_core/clients/test_removed_from_room.py@@ -12,15 +12,16 @@ from __future__ import annotationsfrom types import SimpleNamespace-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (PROTOCOL_VERSION,+ AgentConnectionRegistry,ClientDeclaration,- ConnectionRegistry,)from switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.bridges.agent.protocol.types import AgentEvent, MessagePayload-from switch_core.clients.agent_client import AgentClient, RoomMeta-from switch_core.clients.client_base import ClientBase+from switch_core.clients.actor import Actor+from switch_core.clients.agent_consumer import AgentConsumer, RoomMeta+from switch_core.clients.consumer import Consumerfrom switch_core.transport import InboundMembership, RoomRefAGENT = "agent-1"@@ -55,8 +56,10 @@ def _leave(transport_room_id: str) -> InboundMembership:)-def _client(buffer: EventBuffer, connections: ConnectionRegistry) -> SimpleNamespace:- """A minimal fake `self` for the unbound `AgentClient.on_removed`."""+def _client(+ buffer: EventBuffer, connections: AgentConnectionRegistry+) -> SimpleNamespace:+ """A minimal fake `self` for the unbound `AgentConsumer.on_removed`."""meta = {"!left:test": RoomMeta(room_id=LEFT,@@ -66,8 +69,8 @@ def _client(buffer: EventBuffer, connections: ConnectionRegistry) -> SimpleNames),}- async def _resolve_room_meta(matrix_room_id: str) -> RoomMeta | None:- return meta.get(matrix_room_id)+ async def _resolve_room_meta(transport_room_id: str) -> RoomMeta | None:+ return meta.get(transport_room_id)return SimpleNamespace(_event_buffer=buffer,@@ -78,7 +81,7 @@ def _client(buffer: EventBuffer, connections: ConnectionRegistry) -> SimpleNamesasync def _removed(stub: SimpleNamespace, transport_room_id: str) -> None:- await AgentClient.on_removed(+ await AgentConsumer.on_removed(stub, # type: ignore[arg-type]RoomRef(room_id=transport_room_id),_leave(transport_room_id),@@ -90,7 +93,7 @@ async def test_the_rooms_retained_events_are_forgotten() -> None:buffer.enqueue(AGENT, LEFT, _message(LEFT, "said in the old room"))buffer.enqueue(AGENT, KEPT, _message(KEPT, "said in this one"))- await _removed(_client(buffer, ConnectionRegistry()), "!left:test")+ await _removed(_client(buffer, AgentConnectionRegistry()), "!left:test")# Read at the level every reader is built on, filter or no filter: this is# what closes it for the stream, which has no membership of its own to@@ -99,7 +102,7 @@ async def test_the_rooms_retained_events_are_forgotten() -> None:async def test_the_rooms_claim_is_released() -> None:- connections = ConnectionRegistry()+ connections = AgentConnectionRegistry()conn = connections.open(agent_id=AGENT,connection_id="c1",@@ -122,7 +125,7 @@ async def test_a_room_that_cannot_be_resolved_drops_nothing() -> None:buffer = EventBuffer()buffer.enqueue(AGENT, LEFT, _message(LEFT, "still here"))- await _removed(_client(buffer, ConnectionRegistry()), "!unknown:test")+ await _removed(_client(buffer, AgentConnectionRegistry()), "!unknown:test")assert [item.room_id for item in buffer.read_from(AGENT, 0)] == [LEFT]@@ -135,13 +138,15 @@ class _CapturingTransport:self.handlers = handlers-class _BareClient(ClientBase):- """Enough of a client for `setup` to run and a hook to be observed."""+class _BareClient(Consumer):+ """Enough of a consumer for `setup` to run and a hook to be observed."""def __init__(self, transport: _CapturingTransport) -> None:- self.matrix_user_id = "@agent:test"+ actor = Actor.__new__(Actor)+ actor.transport_user_id = "@agent:test"# `_transport` is a property over this, and raises until it is set.- self.transport = transport+ actor.transport = transport+ self.actor = actorself._self_join_dispatched: set[str] = set()self.removed: list[str] = []diff --git a/core/tests/switch_core/clients/test_room_join_events.py b/core/tests/switch_core/clients/test_room_join_events.pyindex a927dd61f..8c49d1cb0 100644--- a/core/tests/switch_core/clients/test_room_join_events.py+++ b/core/tests/switch_core/clients/test_room_join_events.py@@ -4,7 +4,7 @@ from contextlib import asynccontextmanagerfrom types import SimpleNamespacefrom switch_core.bridges.agent.protocol.types import AgentEvent, RoomJoinPayload-from switch_core.clients.agent_client import AgentClient, RoomMeta+from switch_core.clients.agent_consumer import AgentConsumer, RoomMetafrom switch_core.transport import InboundMembership, RoomRef@@ -22,10 +22,10 @@ class _FakeClientStore:def __init__(self, names: dict[str, str]) -> None:self._names = names- async def get_by_matrix_user_id(- self, _session: object, matrix_user_id: str+ async def get_by_transport_user_id(+ self, _session: object, transport_user_id: str) -> object | None:- name = self._names.get(matrix_user_id)+ name = self._names.get(transport_user_id)return SimpleNamespace(display_name=name) if name else None@@ -45,7 +45,7 @@ def _client(receives: bool = True,known: dict[str, str] | None = None,) -> SimpleNamespace:- """A minimal fake `self` for the unbound AgentClient.on_member_event.+ """A minimal fake `self` for the unbound AgentConsumer.on_member_event.Stubs the event queue, agent identity, room-meta resolution, and the roomstore / session factory so the handler can run without a DB or live Matrix@@ -59,7 +59,7 @@ def _client(channel_type="channel_public",)- async def _resolve_room_meta(_matrix_room_id: str) -> RoomMeta | None:+ async def _resolve_room_meta(_transport_room_id: str) -> RoomMeta | None:return resolved@asynccontextmanager@@ -77,7 +77,7 @@ def _client(session_factory=_session_factory,)# Bound, so the handler resolves the name through the real implementation.- stub._member_name = lambda session, event: AgentClient._member_name(+ stub._member_name = lambda session, event: AgentConsumer._member_name(stub, session, event)return stub@@ -108,7 +108,7 @@ def _member_event(async def _run(client: SimpleNamespace, event: InboundMembership) -> None:- await AgentClient.on_member_event(client, RoomRef("!matrix:switch.local"), event)+ await AgentConsumer.on_member_event(client, RoomRef("!matrix:switch.local"), event)class TestRoomJoinEnqueue:@@ -174,7 +174,7 @@ class TestRoomJoinEnqueue:assert client._event_buffer.enqueued == []async def test_no_room_meta_does_not_enqueue(self) -> None:- async def _none(_matrix_room_id: str) -> RoomMeta | None:+ async def _none(_transport_room_id: str) -> RoomMeta | None:return Noneclient = _client()diff --git a/core/tests/switch_core/clients/test_self_join_dispatch.py b/core/tests/switch_core/clients/test_self_join_dispatch.pyindex 932212e08..6bd624195 100644--- a/core/tests/switch_core/clients/test_self_join_dispatch.py+++ b/core/tests/switch_core/clients/test_self_join_dispatch.py@@ -11,20 +11,23 @@ from __future__ import annotationsimport pytest-from switch_core.clients.client_base import ClientBase+from switch_core.clients.actor import Actor+from switch_core.clients.consumer import Consumerfrom switch_core.transport import InboundMembership, RoomRef-MATRIX_ROOM_ID = "!matrix:switch.local"+TRANSPORT_ROOM_ID = "!matrix:switch.local"SELF = "@switch-agent-1:switch.local"-class _Client(ClientBase):+class _Client(Consumer):def __init__(self) -> None:- self.matrix_user_id = SELF- self.client_id = "client-1"- self.display_name = "client one"- self.room_join_times = {}- self._room_joined_events = {}+ actor = Actor.__new__(Actor)+ actor.transport_user_id = SELF+ actor.client_id = "client-1"+ actor.display_name = "client one"+ actor.room_join_times = {}+ actor._room_joined_events = {}+ self.actor = actorself._self_join_dispatched = set()self._startup_ts = 1000self.self_joins: list[str] = []@@ -38,7 +41,7 @@ class _Client(ClientBase):def _room() -> RoomRef:- return RoomRef(room_id=MATRIX_ROOM_ID)+ return RoomRef(room_id=TRANSPORT_ROOM_ID)def _member_event(@@ -49,7 +52,7 @@ def _member_event(timestamp: int = 2000,) -> InboundMembership:return InboundMembership(- room_id=MATRIX_ROOM_ID,+ room_id=TRANSPORT_ROOM_ID,event_id="$member",sender=state_key,timestamp=timestamp,@@ -63,11 +66,11 @@ def _member_event(async def test_self_join_fires_after_the_client_joined_itself() -> None:client = _Client()# Auto-accepting the invite records membership before sync reports the join.- client._mark_joined(MATRIX_ROOM_ID, 1500)+ client.actor.mark_joined(TRANSPORT_ROOM_ID, 1500)await client._handle_member_event(_room(), _member_event())- assert client.self_joins == [MATRIX_ROOM_ID]+ assert client.self_joins == [TRANSPORT_ROOM_ID]@pytest.mark.asyncio@@ -78,7 +81,7 @@ async def test_self_join_fires_only_once_for_the_same_join() -> None:await client._handle_member_event(_room(), event)await client._handle_member_event(_room(), event)- assert client.self_joins == [MATRIX_ROOM_ID]+ assert client.self_joins == [TRANSPORT_ROOM_ID]@pytest.mark.asyncio@@ -115,7 +118,7 @@ async def test_rejoining_after_leaving_is_a_fresh_arrival() -> None:_room(), _member_event(prev_membership="leave", timestamp=4000))- assert client.self_joins == [MATRIX_ROOM_ID, MATRIX_ROOM_ID]+ assert client.self_joins == [TRANSPORT_ROOM_ID, TRANSPORT_ROOM_ID]@pytest.mark.asynciodiff --git a/core/tests/switch_core/clients/test_send_media.py b/core/tests/switch_core/clients/test_send_media.pyindex 2dc94eed8..c76a6d8e3 100644--- a/core/tests/switch_core/clients/test_send_media.py+++ b/core/tests/switch_core/clients/test_send_media.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport pytest-from switch_core.clients.client_base import ClientBase+from switch_core.clients.actor import Actorfrom switch_core.transport import TransportError, UploadResultfrom tests.switch_core.transport.fake import FakeTransport@@ -16,11 +16,11 @@ class _FailingUploadTransport(FakeTransport):raise TransportError(f"Failed to upload media '{filename}'")-def _client(transport: FakeTransport) -> ClientBase:- client = object.__new__(ClientBase)+def _client(transport: FakeTransport) -> Actor:+ client = object.__new__(Actor)client.transport = transport # type: ignore[attr-defined]client.display_name = "Alice" # type: ignore[attr-defined]- client.matrix_user_id = "@alice:switch.local" # type: ignore[attr-defined]+ client.transport_user_id = "@alice:switch.local" # type: ignore[attr-defined]client.client_id = "client-1" # type: ignore[attr-defined]return clientdiff --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 ae02e66a5..2315249a3 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@@ -21,7 +21,7 @@ from types import SimpleNamespaceimport pytestfrom switch_core.clients.admin_messages import ADMIN_MARKER, admin_extra_content-from switch_core.clients.agent_client import AgentClient+from switch_core.clients.agent_consumer import AgentConsumerfrom switch_core.clients.room_meta import RoomMetafrom switch_core.delivery.addressing import AddressingResolverfrom switch_core.transport import InboundMessage@@ -53,7 +53,7 @@ def _client(name: str = "flintai-sdk.ts") -> SimpleNamespace:"""resolver = SimpleNamespace(agent=SimpleNamespace(name=name),- matrix_user_id=f"@switch-agent-{name}:switch.local",+ transport_user_id=f"@switch-agent-{name}:switch.local",)async def _no(*_a: object, **_k: object) -> bool:@@ -79,10 +79,10 @@ async def _addressed(resolver,object(),agent=resolver.agent,- agent_matrix_id=resolver.matrix_user_id,+ agent_user_id=resolver.transport_user_id,room_id=meta.room_id,channel_type=meta.channel_type,- message=AgentClient._as_incoming(event),+ message=AgentConsumer._as_incoming(event),)diff --git a/core/tests/switch_core/clients/test_wait_joined_existing_membership.py b/core/tests/switch_core/clients/test_wait_joined_existing_membership.pyindex 6ff386e4b..bedb1d029 100644--- a/core/tests/switch_core/clients/test_wait_joined_existing_membership.py+++ b/core/tests/switch_core/clients/test_wait_joined_existing_membership.py@@ -4,10 +4,10 @@ import asyncioimport pytest-from switch_core.clients.client_base import ClientBase+from switch_core.clients.actor import Actorfrom tests.switch_core.transport.fake import FakeTransport-MATRIX_ROOM_ID = "!matrix:switch.local"+TRANSPORT_ROOM_ID = "!matrix:switch.local"class _CountingTransport(FakeTransport):@@ -22,31 +22,31 @@ class _CountingTransport(FakeTransport):return await super().joined_rooms()-def _client(transport: FakeTransport) -> ClientBase:- client = ClientBase.__new__(ClientBase)- client.matrix_user_id = "@ext_alice:switch.local"+def _client(transport: FakeTransport) -> Actor:+ client = Actor.__new__(Actor)+ client.transport_user_id = "@ext_alice:switch.local"client.transport = transportclient.room_join_times = {}client._room_joined_events = {}- client._startup_ts = 1000+ client._connected_at = 1000return clientasync def test_wait_joined_accepts_membership_that_predates_this_process() -> None:- """A puppet joined in an earlier run replays no member event: the client+ """A human actor joined in an earlier run replays no member event: the clientresumes from a stored next_batch token, and re-inviting an existing memberis a no-op. Waiting on sync alone times out and the message is dropped."""- transport = _CountingTransport([MATRIX_ROOM_ID])+ transport = _CountingTransport([TRANSPORT_ROOM_ID])client = _client(transport)- assert await client.wait_joined(MATRIX_ROOM_ID, 0.05) is True+ assert await client.wait_joined(TRANSPORT_ROOM_ID, 0.05) is Trueassert transport.calls == 1# The join predates startup, so it must not shift the ignore cutoff forward# and suppress events already in flight.- assert client.room_join_times[MATRIX_ROOM_ID] == client._startup_ts+ assert client.room_join_times[TRANSPORT_ROOM_ID] == client._connected_at# Membership is cached — no second round trip.- assert await client.wait_joined(MATRIX_ROOM_ID, 0.05) is True+ assert await client.wait_joined(TRANSPORT_ROOM_ID, 0.05) is Trueassert transport.calls == 1@@ -55,16 +55,16 @@ async def test_wait_joined_still_waits_for_a_pending_join() -> None:async def join_late() -> None:await asyncio.sleep(0.01)- client._mark_joined(MATRIX_ROOM_ID, 2000)+ client.mark_joined(TRANSPORT_ROOM_ID, 2000)task = asyncio.create_task(join_late())- assert await client.wait_joined(MATRIX_ROOM_ID, 1.0) is True+ assert await client.wait_joined(TRANSPORT_ROOM_ID, 1.0) is Trueawait taskasync def test_wait_joined_times_out_when_the_join_never_lands() -> None:client = _client(_CountingTransport([]))- assert await client.wait_joined(MATRIX_ROOM_ID, 0.05) is False+ assert await client.wait_joined(TRANSPORT_ROOM_ID, 0.05) is Falseasync def test_wait_joined_falls_back_to_waiting_when_the_lookup_reports_nothing() -> (@@ -75,9 +75,26 @@ async def test_wait_joined_falls_back_to_waiting_when_the_lookup_reports_nothingtransport = _CountingTransport([])client = _client(transport)- assert await client.wait_joined(MATRIX_ROOM_ID, 0.05) is False+ assert await client.wait_joined(TRANSPORT_ROOM_ID, 0.05) is Falseassert transport.calls == 1- assert MATRIX_ROOM_ID not in client.room_join_times+ assert TRANSPORT_ROOM_ID not in client.room_join_times+++async def test_an_actor_with_no_consumer_sees_a_join_that_lands_later() -> None:+ """A HumanActor runs no read loop, so no member event ever reaches it.+ Membership written by someone else after the wait began is found by+ re-reading, not by an event."""+ transport = _CountingTransport([])+ client = _client(transport)++ async def joined_by_someone_else() -> None:+ await asyncio.sleep(0.05)+ transport._joined.append(TRANSPORT_ROOM_ID)++ task = asyncio.create_task(joined_by_someone_else())+ assert await client.wait_joined(TRANSPORT_ROOM_ID, 1.0) is True+ assert transport.calls >= 2+ await taskif __name__ == "__main__":diff --git a/core/tests/switch_core/db/stores/test_agent_session_store.py b/core/tests/switch_core/db/stores/test_agent_session_store.pyindex 2c1ec4851..1e607621e 100644--- a/core/tests/switch_core/db/stores/test_agent_session_store.py+++ b/core/tests/switch_core/db/stores/test_agent_session_store.py@@ -32,7 +32,7 @@ async def _make_agent(session: AsyncSession, name: str) -> Agent:type="agent",)client = Client(- matrix_user_id=f"@{name}:test",+ transport_user_id=f"@{name}:test",display_name=name,type="agent",)@@ -54,7 +54,7 @@ async def _make_agent(session: AsyncSession, name: str) -> Agent:async def _make_room(session: AsyncSession, name: str) -> Room:room = Room(- matrix_room_id=f"!{name}:test",+ transport_room_id=f"!{name}:test",name=name,description=f"{name} desc",)diff --git a/core/tests/switch_core/db/stores/test_agent_store.py b/core/tests/switch_core/db/stores/test_agent_store.pyindex 555e65538..ae1d69cfb 100644--- a/core/tests/switch_core/db/stores/test_agent_store.py+++ b/core/tests/switch_core/db/stores/test_agent_store.py@@ -29,7 +29,7 @@ async def _make_agent(session: AsyncSession, name: str, *, unique: str = "") ->type="agent",)client = Client(- matrix_user_id=f"@{slug}:test",+ transport_user_id=f"@{slug}:test",display_name=name,type="agent",)@@ -50,7 +50,9 @@ async def _make_agent(session: AsyncSession, name: str, *, unique: str = "") ->async def _make_room(session: AsyncSession, name: str) -> Room:- room = Room(matrix_room_id=f"!{name}:test", name=name, description=f"{name} desc")+ room = Room(+ transport_room_id=f"!{name}:test", name=name, description=f"{name} desc"+ )session.add(room)await session.flush()return roomdiff --git a/core/tests/switch_core/db/stores/test_api_key_agent_join.py b/core/tests/switch_core/db/stores/test_api_key_agent_join.pyindex 72d5a034a..9916e995c 100644--- a/core/tests/switch_core/db/stores/test_api_key_agent_join.py+++ b/core/tests/switch_core/db/stores/test_api_key_agent_join.py@@ -34,7 +34,7 @@ async def _make_key(async def _make_agent(session: AsyncSession, name: str, api_key: ApiKey) -> Agent:client = Client(- matrix_user_id=f"@{name}:test",+ transport_user_id=f"@{name}:test",display_name=name,type="agent",)diff --git a/core/tests/switch_core/db/stores/test_bridge_message_map_store.py b/core/tests/switch_core/db/stores/test_bridge_message_map_store.pyindex 30a5c2c13..e6fdde730 100644--- a/core/tests/switch_core/db/stores/test_bridge_message_map_store.py+++ b/core/tests/switch_core/db/stores/test_bridge_message_map_store.py@@ -11,7 +11,7 @@ from switch_core.db.stores.bridge_message_map_store import BridgeMessageMapStoreasync def _make_bridge(session: AsyncSession) -> str:"""Insert the Client + CollaborationBridge a mapping row depends on."""client = Client(- matrix_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",display_name="bridge client",type="bridge",)diff --git a/core/tests/switch_core/db/stores/test_budget_store.py b/core/tests/switch_core/db/stores/test_budget_store.pyindex d29460674..da4d5528e 100644--- a/core/tests/switch_core/db/stores/test_budget_store.py+++ b/core/tests/switch_core/db/stores/test_budget_store.py@@ -32,7 +32,7 @@ async def _agent(session: AsyncSession, name: str) -> Agent:)session.add(owner)await session.flush()- client = Client(matrix_user_id=f"@{name}:test", display_name=name, type="agent")+ client = Client(transport_user_id=f"@{name}:test", display_name=name, type="agent")key = ApiKey(user_id=owner.id,key_hash=f"hash-{name}",diff --git a/core/tests/switch_core/db/stores/test_client_store.py b/core/tests/switch_core/db/stores/test_client_store.pyindex 77a7de14a..1d3bd760f 100644--- a/core/tests/switch_core/db/stores/test_client_store.py+++ b/core/tests/switch_core/db/stores/test_client_store.py@@ -12,10 +12,10 @@ from switch_core.db.stores.client_store import ClientStorefrom switch_core.db.stores.room_store import RoomStore-async def _make_client(session: AsyncSession, matrix_user_id: str) -> Client:+async def _make_client(session: AsyncSession, transport_user_id: str) -> Client:client = Client(- matrix_user_id=matrix_user_id,- display_name=matrix_user_id,+ transport_user_id=transport_user_id,+ display_name=transport_user_id,type="agent",)session.add(client)@@ -25,7 +25,7 @@ async def _make_client(session: AsyncSession, matrix_user_id: str) -> Client:async def _make_room(session: AsyncSession) -> str:room = Room(- matrix_room_id=f"!{uuid.uuid4().hex[:8]}:test",+ transport_room_id=f"!{uuid.uuid4().hex[:8]}:test",name="a room",description="somewhere a client can be a member of",)@@ -39,7 +39,7 @@ class TestDeleteClearsMemberships:`client_rooms` references `clients` with no `ON DELETE` rule, so themembership rows would otherwise hold the client row hostage — and every- client worth deleting has them: a bridge puppet has been in every room the+ client worth deleting has them: a bridge human actor has been in every room theperson it stands for spoke in."""@@ -161,7 +161,7 @@ class TestDeleteDoesNotReachAcrossTenants:other.add(Client(id=client_id,- matrix_user_id=f"@copy-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@copy-{uuid.uuid4().hex[:8]}:test",display_name="a second tenant reusing the id",type="agent",)@@ -169,10 +169,10 @@ class TestDeleteDoesNotReachAcrossTenants:await other.commit()-class TestGetByMatrixUserIdMultiTenant:+class TestGetByTransportUserIdMultiTenant:"""`Client.matrix_user_id` is unique per tenant(`uq_clients_tenant_matrix_user_id`), not globally — two tenants may each- puppet the same Matrix user id. Before scoping the read, an unfiltered+ human actor the same Matrix user id. Before scoping the read, an unfiltered`get_by_matrix_user_id` matched both rows and raised`MultipleResultsFound` out of message routing and provisioning, whichresolve the sending client from an inbound event this way.@@ -191,24 +191,28 @@ class TestGetByMatrixUserIdMultiTenant:) -> None:store = ClientStore()other_tenant = f"tenant-{uuid.uuid4().hex[:8]}"- shared_matrix_user_id = "@shared:switch.local"+ shared_transport_user_id = "@shared:switch.local"async with session_factory() as session:session.add(Tenant(id=other_tenant, slug=other_tenant, name=other_tenant))await session.flush()- own_id = (await _make_client(session, shared_matrix_user_id)).id+ own_id = (await _make_client(session, shared_transport_user_id)).idawait session.commit()async with tenant_session(session_factory, other_tenant) as other_session:- other_id = (await _make_client(other_session, shared_matrix_user_id)).id+ other_id = (await _make_client(other_session, shared_transport_user_id)).idawait other_session.commit()async with session_factory() as verify:- result = await store.get_by_matrix_user_id(verify, shared_matrix_user_id)+ result = await store.get_by_transport_user_id(+ verify, shared_transport_user_id+ )assert result is not Noneassert result.id == own_idasync with tenant_session(session_factory, other_tenant) as verify:- result = await store.get_by_matrix_user_id(verify, shared_matrix_user_id)+ result = await store.get_by_transport_user_id(+ verify, shared_transport_user_id+ )assert result is not Noneassert result.id == other_iddiff --git a/core/tests/switch_core/db/stores/test_collaboration_bridge_store.py b/core/tests/switch_core/db/stores/test_collaboration_bridge_store.pyindex 19b4953e9..6ed3b1a2d 100644--- a/core/tests/switch_core/db/stores/test_collaboration_bridge_store.py+++ b/core/tests/switch_core/db/stores/test_collaboration_bridge_store.py@@ -14,7 +14,7 @@ from switch_core.tenant_context import tenant_scopeasync def _make_bridge(session: AsyncSession) -> str:client = Client(- matrix_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",display_name="bridge client",type="bridge",)diff --git a/core/tests/switch_core/db/stores/test_delivery_cursor_store.py b/core/tests/switch_core/db/stores/test_delivery_cursor_store.pyindex c6b700663..b640e6a74 100644--- a/core/tests/switch_core/db/stores/test_delivery_cursor_store.py+++ b/core/tests/switch_core/db/stores/test_delivery_cursor_store.py@@ -24,7 +24,7 @@ async def _agent(session: AsyncSession) -> Agent:type="agent",)client = Client(- matrix_user_id=f"@{name}:test",+ transport_user_id=f"@{name}:test",display_name=name,type="agent",)@@ -46,7 +46,7 @@ async def _agent(session: AsyncSession) -> Agent:async def _make_agent_and_room(session: AsyncSession) -> tuple[str, str]:room = Room(- matrix_room_id=f"!room-{uuid.uuid4().hex[:8]}:test",+ transport_room_id=f"!room-{uuid.uuid4().hex[:8]}:test",name="a room",description="",)@@ -134,7 +134,7 @@ class TestAdvancing:async with session_factory() as session:agent_id, first_room = await _make_agent_and_room(session)second_room = Room(- matrix_room_id=f"!room-{uuid.uuid4().hex[:8]}:test",+ transport_room_id=f"!room-{uuid.uuid4().hex[:8]}:test",name="another room",description="",)diff --git a/core/tests/switch_core/db/stores/test_external_user_claims.py b/core/tests/switch_core/db/stores/test_external_user_claims.pyindex f2c1e29f4..514a62928 100644--- a/core/tests/switch_core/db/stores/test_external_user_claims.py+++ b/core/tests/switch_core/db/stores/test_external_user_claims.py@@ -25,7 +25,7 @@ _STORE = ExternalUserStore()async def _make_client(session: AsyncSession, *, client_type: str) -> str:client = Client(- matrix_user_id=f"@{client_type}-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@{client_type}-{uuid.uuid4().hex[:8]}:test",display_name=f"{client_type} client",type=client_type,)diff --git a/core/tests/switch_core/db/stores/test_message_store.py b/core/tests/switch_core/db/stores/test_message_store.pyindex d284e6349..182f4b93b 100644--- a/core/tests/switch_core/db/stores/test_message_store.py+++ b/core/tests/switch_core/db/stores/test_message_store.py@@ -22,7 +22,7 @@ from switch_core.db.stores.message_store import MessageStoreasync def _make_room(session: AsyncSession, name: str) -> Room:room = Room(- matrix_room_id=f"!{name}-{uuid.uuid4().hex[:8]}:test",+ transport_room_id=f"!{name}-{uuid.uuid4().hex[:8]}:test",name=name,description=f"{name} desc",)@@ -33,7 +33,7 @@ async def _make_room(session: AsyncSession, name: str) -> Room:async def _make_client(session: AsyncSession, name: str) -> Client:client = Client(- matrix_user_id=f"@{name}-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@{name}-{uuid.uuid4().hex[:8]}:test",display_name=name,type="agent",)diff --git a/core/tests/switch_core/db/stores/test_reference_store_listing.py b/core/tests/switch_core/db/stores/test_reference_store_listing.pyindex 37c536a99..9ed6f1d32 100644--- a/core/tests/switch_core/db/stores/test_reference_store_listing.py+++ b/core/tests/switch_core/db/stores/test_reference_store_listing.py@@ -64,8 +64,10 @@ async def _make_reference(return ref-async def _make_room(session: AsyncSession, *, matrix_room_id: str, name: str) -> Room:- room = Room(matrix_room_id=matrix_room_id, name=name, description="room")+async def _make_room(+ session: AsyncSession, *, transport_room_id: str, name: str+) -> Room:+ room = Room(transport_room_id=transport_room_id, name=name, description="room")session.add(room)await session.flush()return room@@ -394,7 +396,7 @@ class TestAttachToRoomIsIdempotent:alice = await _make_user(session, name="alice")ref = await _make_reference(session, owner=alice, name="repo")room = await _make_room(- session, matrix_room_id="!attach-twice:test", name="Attach Twice"+ session, transport_room_id="!attach-twice:test", name="Attach Twice")await session.commit()@@ -425,7 +427,7 @@ class TestAttachToRoomIsIdempotent:alice = await _make_user(session, name="alice")ref = await _make_reference(session, owner=alice, name="repo")room = await _make_room(- session, matrix_room_id="!detach:test", name="Detach"+ session, transport_room_id="!detach:test", name="Detach")await session.commit()diff --git a/core/tests/switch_core/db/stores/test_room_alias_store.py b/core/tests/switch_core/db/stores/test_room_alias_store.pyindex 07dd993cb..85feb480c 100644--- a/core/tests/switch_core/db/stores/test_room_alias_store.py+++ b/core/tests/switch_core/db/stores/test_room_alias_store.py@@ -19,7 +19,7 @@ async def _make_agent(session: AsyncSession, name: str) -> Agent:type="agent",)client = Client(- matrix_user_id=f"@{name}:test",+ transport_user_id=f"@{name}:test",display_name=name,type="agent",)@@ -40,7 +40,7 @@ async def _make_agent(session: AsyncSession, name: str) -> Agent:async def _make_room(session: AsyncSession, name: str) -> Room:- room = Room(matrix_room_id=f"!{name}:test", name=name, description="d")+ room = Room(transport_room_id=f"!{name}:test", name=name, description="d")session.add(room)await session.flush()return roomdiff --git a/core/tests/switch_core/db/stores/test_room_archive.py b/core/tests/switch_core/db/stores/test_room_archive.pyindex fc4537de6..69a360b0f 100644--- a/core/tests/switch_core/db/stores/test_room_archive.py+++ b/core/tests/switch_core/db/stores/test_room_archive.py@@ -10,7 +10,7 @@ from switch_core.db.stores.room_store import RoomStoreasync def _make_room(rooms: RoomStore, session: AsyncSession, name: str) -> Room:return await rooms.create(session,- Room(matrix_room_id=f"!{name}:test", name=name, description=f"{name} desc"),+ Room(transport_room_id=f"!{name}:test", name=name, description=f"{name} desc"),)@@ -28,7 +28,7 @@ async def _make_agent(session: AsyncSession, name: str) -> Agent:type="agent",)client = Client(- matrix_user_id=f"@{name}:test",+ transport_user_id=f"@{name}:test",display_name=name,type="agent",)diff --git a/core/tests/switch_core/db/stores/test_room_channel_type.py b/core/tests/switch_core/db/stores/test_room_channel_type.pyindex ccf142991..ad5ded812 100644--- a/core/tests/switch_core/db/stores/test_room_channel_type.py+++ b/core/tests/switch_core/db/stores/test_room_channel_type.py@@ -16,7 +16,7 @@ CHAT = "19:[email protected]"async def _make_bridge(session: AsyncSession) -> str:client = Client(- matrix_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",display_name="teams client",type="bridge",)@@ -43,7 +43,7 @@ async def _make_room(room = await RoomStore().create(session,Room(- matrix_room_id=f"!{uuid.uuid4().hex[:8]}:test",+ transport_room_id=f"!{uuid.uuid4().hex[:8]}:test",name="room",description="room desc",bridge_id=bridge_id,diff --git a/core/tests/switch_core/db/stores/test_room_external_channel.py b/core/tests/switch_core/db/stores/test_room_external_channel.pyindex 7ede9c36d..0cd7f1179 100644--- a/core/tests/switch_core/db/stores/test_room_external_channel.py+++ b/core/tests/switch_core/db/stores/test_room_external_channel.py@@ -23,7 +23,7 @@ NEW_ID = "-1009876543210"async def _make_bridge(session: AsyncSession, name: str) -> CollaborationBridge:client = Client(- matrix_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",display_name=f"{name} client",type="bridge",)@@ -52,7 +52,7 @@ async def _make_room(return await store.create(session,Room(- matrix_room_id=f"!{name}:test",+ transport_room_id=f"!{name}:test",name=name,description=f"{name} desc",bridge_id=bridge_id,diff --git a/core/tests/switch_core/db/stores/test_room_group_store.py b/core/tests/switch_core/db/stores/test_room_group_store.pyindex d4e7fa6d9..020406ac6 100644--- a/core/tests/switch_core/db/stores/test_room_group_store.py+++ b/core/tests/switch_core/db/stores/test_room_group_store.py@@ -16,7 +16,7 @@ async def _make_room() -> Room:room = await rooms.create(session,- Room(matrix_room_id=f"!{name}:test", name=name, description=f"{name} desc"),+ Room(transport_room_id=f"!{name}:test", name=name, description=f"{name} desc"),)if group_id is not None:await rooms.set_group(session, room.id, group_id)diff --git a/core/tests/switch_core/db/stores/test_room_join_events_store.py b/core/tests/switch_core/db/stores/test_room_join_events_store.pyindex 2dd5309aa..66c5ed857 100644--- a/core/tests/switch_core/db/stores/test_room_join_events_store.py+++ b/core/tests/switch_core/db/stores/test_room_join_events_store.py@@ -10,7 +10,7 @@ from switch_core.db.stores.room_store import RoomStoreasync def _make_room(rooms: RoomStore, session: AsyncSession, name: str) -> Room:return await rooms.create(session,- Room(matrix_room_id=f"!{name}:test", name=name, description=f"{name} desc"),+ Room(transport_room_id=f"!{name}:test", name=name, description=f"{name} desc"),)@@ -26,7 +26,7 @@ async def _make_agent(session: AsyncSession, name: str) -> Agent:type="agent",)client = Client(- matrix_user_id=f"@{name}:test",+ transport_user_id=f"@{name}:test",display_name=name,type="agent",)diff --git a/core/tests/switch_core/db/stores/test_room_link_archive.py b/core/tests/switch_core/db/stores/test_room_link_archive.pyindex c95c476d1..4f9d400bc 100644--- a/core/tests/switch_core/db/stores/test_room_link_archive.py+++ b/core/tests/switch_core/db/stores/test_room_link_archive.py@@ -10,7 +10,7 @@ from switch_core.db.stores.room_store import RoomStoreasync def _make_room(rooms: RoomStore, session: AsyncSession, name: str) -> Room:return await rooms.create(session,- Room(matrix_room_id=f"!{name}:test", name=name, description=f"{name} desc"),+ Room(transport_room_id=f"!{name}:test", name=name, description=f"{name} desc"),)diff --git a/core/tests/switch_core/db/stores/test_room_membership_lookup.py b/core/tests/switch_core/db/stores/test_room_membership_lookup.pyindex 3be1bb165..46ab59b04 100644--- a/core/tests/switch_core/db/stores/test_room_membership_lookup.py+++ b/core/tests/switch_core/db/stores/test_room_membership_lookup.py@@ -21,7 +21,7 @@ async def _make_agent(session: AsyncSession, name: str) -> Agent:type="agent",)client = Client(- matrix_user_id=f"@{name}:test",+ transport_user_id=f"@{name}:test",display_name=name,type="agent",)@@ -48,7 +48,8 @@ class TestGetWithMembership:store = RoomStore()async with session_factory() as session:room = await store.create(- session, Room(matrix_room_id="!a:test", name="alpha", description="d")+ session,+ Room(transport_room_id="!a:test", name="alpha", description="d"),)agent = await _make_agent(session, "member")await store.add_agents(session, room.id, [agent.id])@@ -70,7 +71,7 @@ class TestGetWithMembership:store = RoomStore()async with session_factory() as session:room = await store.create(- session, Room(matrix_room_id="!b:test", name="beta", description="d")+ session, Room(transport_room_id="!b:test", name="beta", description="d"))outsider = await _make_agent(session, "outsider")await session.commit()@@ -103,7 +104,8 @@ class TestGetWithMembership:store = RoomStore()async with session_factory() as session:room = await store.create(- session, Room(matrix_room_id="!c:test", name="gamma", description="d")+ session,+ Room(transport_room_id="!c:test", name="gamma", description="d"),)insider = await _make_agent(session, "insider")outsider = await _make_agent(session, "stranger")diff --git a/core/tests/switch_core/db/stores/test_room_membership_write.py b/core/tests/switch_core/db/stores/test_room_membership_write.pyindex 9693d2a3f..931137d36 100644--- a/core/tests/switch_core/db/stores/test_room_membership_write.py+++ b/core/tests/switch_core/db/stores/test_room_membership_write.py@@ -21,12 +21,12 @@ from switch_core.db.stores.room_store import RoomStoreasync def _client_and_room(session: AsyncSession) -> tuple[str, str]:client = Client(- matrix_user_id=f"@someone-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@someone-{uuid.uuid4().hex[:8]}:test",display_name="someone",type="agent",)room = Room(- matrix_room_id=f"!{uuid.uuid4().hex[:8]}:test",+ transport_room_id=f"!{uuid.uuid4().hex[:8]}:test",name="a room",description="",)diff --git a/core/tests/switch_core/db/stores/test_room_role_store.py b/core/tests/switch_core/db/stores/test_room_role_store.pyindex 252463e88..d0e2765d6 100644--- a/core/tests/switch_core/db/stores/test_room_role_store.py+++ b/core/tests/switch_core/db/stores/test_room_role_store.py@@ -29,7 +29,7 @@ async def _make_agent(session: AsyncSession, name: str) -> Agent:type="agent",)client = Client(- matrix_user_id=f"@{name}:test",+ transport_user_id=f"@{name}:test",display_name=name,type="agent",)@@ -51,7 +51,7 @@ async def _make_agent(session: AsyncSession, name: str) -> Agent:async def _make_room(session: AsyncSession, name: str) -> Room:room = Room(- matrix_room_id=f"!{name}:test",+ transport_room_id=f"!{name}:test",name=name,description=f"{name} desc",)diff --git a/core/tests/switch_core/db/stores/test_room_store.py b/core/tests/switch_core/db/stores/test_room_store.pyindex 423d8be72..df845f221 100644--- a/core/tests/switch_core/db/stores/test_room_store.py+++ b/core/tests/switch_core/db/stores/test_room_store.py@@ -10,10 +10,10 @@ from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.room_store import RoomStore-async def _make_room(session: AsyncSession, matrix_room_id: str) -> Room:+async def _make_room(session: AsyncSession, transport_room_id: str) -> Room:room = Room(- matrix_room_id=matrix_room_id,- name=matrix_room_id,+ transport_room_id=transport_room_id,+ name=transport_room_id,description="test room",)session.add(room)@@ -21,7 +21,7 @@ async def _make_room(session: AsyncSession, matrix_room_id: str) -> Room:return room-class TestGetByMatrixRoomIdMultiTenant:+class TestGetByTransportRoomIdMultiTenant:"""`Room.matrix_room_id` is unique per tenant(`uq_rooms_tenant_matrix_room_id`), not globally — two tenants may eachhave a room bound to the same transport room id. Before scoping the read,@@ -43,32 +43,36 @@ class TestGetByMatrixRoomIdMultiTenant:) -> None:store = RoomStore()other_tenant = f"tenant-{uuid.uuid4().hex[:8]}"- shared_matrix_room_id = "!shared:switch.local"+ shared_transport_room_id = "!shared:switch.local"async with session_factory() as session:session.add(Tenant(id=other_tenant, slug=other_tenant, name=other_tenant))await session.flush()- own_id = (await _make_room(session, shared_matrix_room_id)).id+ own_id = (await _make_room(session, shared_transport_room_id)).idawait session.commit()async with tenant_session(session_factory, other_tenant) as other_session:- other_id = (await _make_room(other_session, shared_matrix_room_id)).id+ other_id = (await _make_room(other_session, shared_transport_room_id)).idawait other_session.commit()async with session_factory() as verify:- result = await store.get_by_matrix_room_id(verify, shared_matrix_room_id)+ result = await store.get_by_transport_room_id(+ verify, shared_transport_room_id+ )assert result is not Noneassert result.id == own_idasync with tenant_session(session_factory, other_tenant) as verify:- result = await store.get_by_matrix_room_id(verify, shared_matrix_room_id)+ result = await store.get_by_transport_room_id(+ verify, shared_transport_room_id+ )assert result is not Noneassert result.id == other_id-class TestGetByMatrixRoomIdRequiresATenant:+class TestGetByTransportRoomIdRequiresATenant:"""No caller left reaches `get_by_matrix_room_id` with nothing bound- (CHOO-2623): `PostgresTransport` and the two `ClientBase` subclasses carry+ (CHOO-2623): `PostgresTransport` and the two `Actor` subclasses carrytheir own tenant, and `PostgresProvisioning` is only ever invoked frominside a `tenant_scope` bound to the room it acts on. An unfilteredfallback for "nothing bound" therefore has no legitimate caller left to@@ -85,7 +89,7 @@ class TestGetByMatrixRoomIdRequiresATenant:store = RoomStore()tenant_a = f"tenant-{uuid.uuid4().hex[:8]}"tenant_b = f"tenant-{uuid.uuid4().hex[:8]}"- shared_matrix_room_id = "!shared-unbound:switch.local"+ shared_transport_room_id = "!shared-unbound:switch.local"async with session_factory() as session:session.add_all(@@ -97,13 +101,13 @@ class TestGetByMatrixRoomIdRequiresATenant:await session.commit()async with tenant_session(session_factory, tenant_a) as session:- await _make_room(session, shared_matrix_room_id)+ await _make_room(session, shared_transport_room_id)await session.commit()async with tenant_session(session_factory, tenant_b) as session:- await _make_room(session, shared_matrix_room_id)+ await _make_room(session, shared_transport_room_id)await session.commit()async with session_factory() as verify:with pytest.raises(TenantNotBoundError):- await store.get_by_matrix_room_id(verify, shared_matrix_room_id)+ await store.get_by_transport_room_id(verify, shared_transport_room_id)diff --git a/core/tests/switch_core/db/stores/test_usage_store.py b/core/tests/switch_core/db/stores/test_usage_store.pyindex ecdf9c8f5..1fa2eeef5 100644--- a/core/tests/switch_core/db/stores/test_usage_store.py+++ b/core/tests/switch_core/db/stores/test_usage_store.py@@ -27,7 +27,7 @@ OTHER_TENANT = "11111111-1111-1111-1111-111111111111"async def _client(session: AsyncSession, name: str) -> str:- client = Client(matrix_user_id=f"@{name}:test", display_name=name, type="agent")+ client = Client(transport_user_id=f"@{name}:test", display_name=name, type="agent")session.add(client)await session.flush()return client.iddiff --git a/core/tests/switch_core/db/test_dead_peer_detection.py b/core/tests/switch_core/db/test_dead_peer_detection.pyindex 4958f9e66..c0ddce799 100644--- a/core/tests/switch_core/db/test_dead_peer_detection.py+++ b/core/tests/switch_core/db/test_dead_peer_detection.py@@ -35,7 +35,7 @@ _BASE_KWARGS = dict(db_user="postgres",db_password="pw",db_name="switch",- matrix_server_name="switch.local",+ id_server_name="switch.local",agent_registration_token="token",jwt_secret_key="jwt",gateway_admin_email="[email protected]",diff --git a/core/tests/switch_core/db/test_multi_tenant_scoping.py b/core/tests/switch_core/db/test_multi_tenant_scoping.pyindex 80b57b237..6bd603d1d 100644--- a/core/tests/switch_core/db/test_multi_tenant_scoping.py+++ b/core/tests/switch_core/db/test_multi_tenant_scoping.py@@ -46,12 +46,12 @@ async def _make_user(session: AsyncSession, name: str) -> User:async def _make_client(- session: AsyncSession, tenant_id: str, matrix_user_id: str+ session: AsyncSession, tenant_id: str, transport_user_id: str) -> Client:client = Client(tenant_id=tenant_id,- matrix_user_id=matrix_user_id,- display_name=matrix_user_id,+ transport_user_id=transport_user_id,+ display_name=transport_user_id,type="agent",)session.add(client)@@ -152,7 +152,7 @@ class TestPerTenantUniqueness:assert agent_a.id != agent_b.idassert agent_a.name == agent_b.name == "reviewer"- async def test_same_matrix_user_id_in_two_tenants(+ async def test_same_transport_user_id_in_two_tenants(self, session_factory: async_sessionmaker[AsyncSession]) -> None:async with session_factory() as session:@@ -164,9 +164,13 @@ class TestPerTenantUniqueness:await session.commit()assert client_a.id != client_b.id- assert client_a.matrix_user_id == client_b.matrix_user_id == "@shared:test"+ assert (+ client_a.transport_user_id+ == client_b.transport_user_id+ == "@shared:test"+ )- async def test_same_matrix_room_id_in_two_tenants(+ async def test_same_transport_room_id_in_two_tenants(self, session_factory: async_sessionmaker[AsyncSession]) -> None:async with session_factory() as session:@@ -175,13 +179,13 @@ class TestPerTenantUniqueness:room_a = Room(tenant_id=tenant_a.id,- matrix_room_id="!shared:test",+ transport_room_id="!shared:test",name="room",description="room desc",)room_b = Room(tenant_id=tenant_b.id,- matrix_room_id="!shared:test",+ transport_room_id="!shared:test",name="room",description="room desc",)@@ -189,7 +193,9 @@ class TestPerTenantUniqueness:await session.commit()assert room_a.id != room_b.id- assert room_a.matrix_room_id == room_b.matrix_room_id == "!shared:test"+ assert (+ room_a.transport_room_id == room_b.transport_room_id == "!shared:test"+ )async def test_each_tenant_can_have_its_own_default_bridge(self, session_factory: async_sessionmaker[AsyncSession]diff --git a/core/tests/switch_core/db/test_tenant_admin_role_split.py b/core/tests/switch_core/db/test_tenant_admin_role_split.pyindex 9f87d889f..3af5082c9 100644--- a/core/tests/switch_core/db/test_tenant_admin_role_split.py+++ b/core/tests/switch_core/db/test_tenant_admin_role_split.py@@ -200,7 +200,7 @@ class TestRoomAuthzThroughTenantRole:await _membership(session, TENANT_ZERO_ID, owner.id, "owner")room = Room(tenant_id=TENANT_ZERO_ID,- matrix_room_id="!private-room:test",+ transport_room_id="!private-room:test",name="private room",description="desc",owner_id=someone_else.id,@@ -225,7 +225,7 @@ class TestRoomAuthzThroughTenantRole:await _membership(session, tenant_b.id, owner.id, "member")room = Room(tenant_id=TENANT_ZERO_ID,- matrix_room_id="!private-room-2:test",+ transport_room_id="!private-room-2:test",name="private room",description="desc",owner_id=someone_else.id,@@ -252,7 +252,7 @@ class TestRoomAuthzThroughTenantRole:await _membership(session, TENANT_ZERO_ID, member.id, "member")room = Room(tenant_id=TENANT_ZERO_ID,- matrix_room_id="!private-room-3:test",+ transport_room_id="!private-room-3:test",name="private room",description="desc",owner_id=someone_else.id,diff --git a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py b/core/tests/switch_core/db/test_tenant_exemption_allowlist.pyindex baeb6ec01..ed60a1f4d 100644--- a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py+++ b/core/tests/switch_core/db/test_tenant_exemption_allowlist.py@@ -64,7 +64,7 @@ _ALLOWED_MODULES = {# The runtime-state sweep reads every tenant's stale rows, one tenant at a# time; `register_agent_with_token` resolves a registration credential by# its globally unique hash, which is the read that produces a tenant.- "switch_core.bridges.agent.protocol.service",+ "switch_core.bridges.agent.protocol.agent_core",# Bearer and OIDC authentication: the credential's tenant, before its row."switch_core.bridges.agent.auth",# The gateway's JWT subject resolves to its membership, and@@ -80,7 +80,7 @@ _ALLOWED_MODULES = {"switch_core.bridges.agent.server_connectors.lifecycle",# `_room_tenant`'s fallback: which tenant is this room in, asked when the# answer is not already cached alongside the channel mapping.- "switch_core.bridges.collaboration.bridge_core",+ "switch_core.bridges.collaboration.collaboration_core",# An inbound webhook from an installed workspace: the platform's signature# proves the sender and the payload names a workspace, and nothing in# either names a tenant. It is the one read that must happen before a@@ -88,7 +88,7 @@ _ALLOWED_MODULES = {# the tenant it produced, so a wrong answer here is a miss rather than a# cross-tenant read."switch_core.bridges.collaboration.install_service",- # `switch_core.transport.postgres` and `switch_core.clients.agent_client`+ # `switch_core.transport.postgres` and `switch_core.clients.agent_consumer`# came off this list with `tenant_of_client`: both were built from a# `clients` row that already named the tenant, so they carry it instead of# asking for it.@@ -125,13 +125,13 @@ _RAW_SESSION_FACTORY_MODULES = {# ── Reached only from inside a unit of work that has already bound the# tenant of the row it is acting on — an inbound bridge event, a delivery,# a sweep row, an authenticated agent operation.- "switch_core.bridges.agent.protocol.service",+ "switch_core.bridges.agent.protocol.agent_core","switch_core.bridges.agent.commands",- "switch_core.bridges.collaboration.bridge_core",+ "switch_core.bridges.collaboration.collaboration_core","switch_core.bridges.collaboration.lifecycle_service","switch_core.bridges.agent.server_connectors.lifecycle",- "switch_core.clients.agent_client",- "switch_core.clients.admin_client",+ "switch_core.clients.agent_consumer",+ "switch_core.clients.command_consumer","switch_core.clients.client_lifecycle_service","switch_core.provisioning.postgres","switch_core.room_service",diff --git a/core/tests/switch_core/db/test_tenant_lookup.py b/core/tests/switch_core/db/test_tenant_lookup.pyindex 503b43572..f10b2710e 100644--- a/core/tests/switch_core/db/test_tenant_lookup.py+++ b/core/tests/switch_core/db/test_tenant_lookup.py@@ -202,13 +202,13 @@ async def _two_populated_tenants(harness: RLSHarness) -> _Fixture:for tenant_id, tag in ((fixture.tenant_a, "a"), (fixture.tenant_b, "b")):client = Client(tenant_id=tenant_id,- matrix_user_id=f"@client-{tag}-{suffix}:test",+ transport_user_id=f"@client-{tag}-{suffix}:test",display_name=f"client {tag}",type="agent",)room = Room(tenant_id=tenant_id,- matrix_room_id=f"!room-{tag}-{suffix}:test",+ transport_room_id=f"!room-{tag}-{suffix}:test",name=f"room {tag}",description="",)diff --git a/core/tests/switch_core/db/test_tenant_session_hook.py b/core/tests/switch_core/db/test_tenant_session_hook.pyindex 1df1246cb..82206741d 100644--- a/core/tests/switch_core/db/test_tenant_session_hook.py+++ b/core/tests/switch_core/db/test_tenant_session_hook.py@@ -337,7 +337,7 @@ class TestARowFromAnotherTenantIsRefusedFromTheIdentityMap:Client(id=client_id,tenant_id=TENANT_A,- matrix_user_id=f"@{client_id}:localhost",+ transport_user_id=f"@{client_id}:localhost",display_name="a client",type="agent",)diff --git a/core/tests/switch_core/gateway/agent_route_harness.py b/core/tests/switch_core/gateway/agent_route_harness.pyindex 697437dbf..bde2343c8 100644--- a/core/tests/switch_core/gateway/agent_route_harness.py+++ b/core/tests/switch_core/gateway/agent_route_harness.py@@ -41,7 +41,7 @@ async def add_agent() -> Agent:client = Client(type="agent",- matrix_user_id=f"@{name}:test",+ transport_user_id=f"@{name}:test",display_name=name,)session.add(client)diff --git a/core/tests/switch_core/gateway/test_bridge_delete_guard.py b/core/tests/switch_core/gateway/test_bridge_delete_guard.pyindex c0c39ea18..b9be2d859 100644--- a/core/tests/switch_core/gateway/test_bridge_delete_guard.py+++ b/core/tests/switch_core/gateway/test_bridge_delete_guard.py@@ -73,7 +73,7 @@ async def _make_admin(session: AsyncSession) -> User:async def _make_bridge(session: AsyncSession) -> str:client = Client(- matrix_user_id=f"@bridge-{uuid.uuid4().hex[:12]}:test",+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:12]}:test",display_name="bridge client",type="bridge",)@@ -92,7 +92,7 @@ async def _make_bridge(session: AsyncSession) -> str:async def _make_room(session: AsyncSession, *, bridge_id: str) -> str:room = Room(- matrix_room_id=f"!{uuid.uuid4().hex[:8]}:test",+ transport_room_id=f"!{uuid.uuid4().hex[:8]}:test",name="bridged room",description="mirror of an external channel",bridge_id=bridge_id,diff --git a/core/tests/switch_core/gateway/test_collaborations_authz.py b/core/tests/switch_core/gateway/test_collaborations_authz.pyindex aeeeb8b53..6000ee150 100644--- a/core/tests/switch_core/gateway/test_collaborations_authz.py+++ b/core/tests/switch_core/gateway/test_collaborations_authz.py@@ -161,7 +161,7 @@ class TestIdentityRoutesAreSelfOrAdmin:class TestProvisioningNeedsARealAccount:- """Claiming an account Switch has not seen mints a Matrix puppet, and the+ """Claiming an account Switch has not seen mints a Matrix human actor, and theid comes from the request body. Anyone signed in may claim any *real*account — that is the point of non-exclusive claims — but conjuring rowsfor ids the platform has never heard of is a different thing."""@@ -186,7 +186,7 @@ class TestProvisioningNeedsARealAccount:async def test_platform_without_a_directory_is_refused(self) -> None:# Nothing can be checked, so the person has to be seen speaking first- # rather than have a puppet minted on their behalf.+ # rather than have a human actor minted on their behalf.with pytest.raises(HTTPException) as excinfo:await _require_directory_account(_StubLifecycle(NotImplementedError("no searchable directory")),@@ -273,7 +273,7 @@ def test_every_collaboration_route_requires_authentication() -> None:async def _make_bridge(session: AsyncSession, *, is_default: bool = False) -> str:client = Client(- matrix_user_id=f"@bridge-{uuid.uuid4().hex[:12]}:test",+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:12]}:test",display_name="bridge client",type="bridge",)diff --git a/core/tests/switch_core/gateway/test_oidc_config.py b/core/tests/switch_core/gateway/test_oidc_config.pyindex 1db31590a..eee345aed 100644--- a/core/tests/switch_core/gateway/test_oidc_config.py+++ b/core/tests/switch_core/gateway/test_oidc_config.py@@ -19,7 +19,7 @@ def _kwargs(**overrides: object) -> dict[str, object]:db_user="u",db_password="p",db_name="d",- matrix_server_name="m",+ id_server_name="m",agent_registration_token="t",jwt_secret_key="secret",gateway_admin_email="[email protected]",diff --git a/core/tests/switch_core/gateway/test_oidc_routes.py b/core/tests/switch_core/gateway/test_oidc_routes.pyindex 1ff98a73b..1c8d1e1e9 100644--- a/core/tests/switch_core/gateway/test_oidc_routes.py+++ b/core/tests/switch_core/gateway/test_oidc_routes.py@@ -36,7 +36,7 @@ def _config(**overrides: object) -> SwitchConfig:db_user="u",db_password="p",db_name="d",- matrix_server_name="m",+ id_server_name="m",agent_registration_token="t",jwt_secret_key="secret",gateway_admin_email="[email protected]",diff --git a/core/tests/switch_core/gateway/test_room_access_permission_authz.py b/core/tests/switch_core/gateway/test_room_access_permission_authz.pyindex d1d11dc0e..745d3331c 100644--- a/core/tests/switch_core/gateway/test_room_access_permission_authz.py+++ b/core/tests/switch_core/gateway/test_room_access_permission_authz.py@@ -59,7 +59,7 @@ async def _add_room(write_visibility: str = "private",) -> Room:room = Room(- matrix_room_id=f"!{name}:test",+ transport_room_id=f"!{name}:test",name=name,description=f"{name} desc",owner_id=owner_id,diff --git a/core/tests/switch_core/gateway/test_room_resource_read_authz.py b/core/tests/switch_core/gateway/test_room_resource_read_authz.pyindex d1d32fb20..720fd60b3 100644--- a/core/tests/switch_core/gateway/test_room_resource_read_authz.py+++ b/core/tests/switch_core/gateway/test_room_resource_read_authz.py@@ -61,7 +61,7 @@ async def _add_user(session: AsyncSession, *, name: str, role: str = "user") ->async def _add_private_room(session: AsyncSession, *, owner_id: str) -> Room:room = Room(- matrix_room_id="!r:test",+ transport_room_id="!r:test",name="r",description="d",owner_id=owner_id,diff --git a/core/tests/switch_core/gateway/test_room_write_authz.py b/core/tests/switch_core/gateway/test_room_write_authz.pyindex 0cd97809a..f27bf6d75 100644--- a/core/tests/switch_core/gateway/test_room_write_authz.py+++ b/core/tests/switch_core/gateway/test_room_write_authz.py@@ -70,7 +70,7 @@ async def _add_room(write_visibility: str = "private",) -> Room:room = Room(- matrix_room_id=f"!{name}:test",+ transport_room_id=f"!{name}:test",name=name,description=f"{name} desc",owner_id=owner_id,diff --git a/core/tests/switch_core/gateway/test_shared_bridge_registration.py b/core/tests/switch_core/gateway/test_shared_bridge_registration.pyindex ed89800b8..ddac276d2 100644--- a/core/tests/switch_core/gateway/test_shared_bridge_registration.py+++ b/core/tests/switch_core/gateway/test_shared_bridge_registration.py@@ -56,7 +56,7 @@ def _admin() -> User:async def _shared_bridge(session: AsyncSession) -> str:client = Client(- matrix_user_id=f"@bridge-{uuid.uuid4().hex[:12]}:test",+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:12]}:test",display_name="bridge client",type="bridge",)diff --git a/core/tests/switch_core/gateway/test_template_http.py b/core/tests/switch_core/gateway/test_template_http.pyindex 38038e235..be779fc80 100644--- a/core/tests/switch_core/gateway/test_template_http.py+++ b/core/tests/switch_core/gateway/test_template_http.py@@ -52,7 +52,7 @@ def _config() -> SwitchConfig:db_user="u",db_password="p",db_name="d",- matrix_server_name="test",+ id_server_name="test",agent_registration_token="t",jwt_secret_key="s",gateway_admin_email="admin@test",diff --git a/core/tests/switch_core/gateway/test_tenant_api_routes.py b/core/tests/switch_core/gateway/test_tenant_api_routes.pyindex 6c3155848..ae4da26df 100644--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py@@ -263,7 +263,7 @@ async def _make_agent_with_key(async with session_factory() as session:client = Client(tenant_id=tenant_id,- matrix_user_id=f"@bot-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@bot-{uuid.uuid4().hex[:8]}:test",display_name="test-agent-bot",type="agent",)diff --git a/core/tests/switch_core/messages/test_notify.py b/core/tests/switch_core/messages/test_notify.pyindex 3687a2de7..f6f98f4a6 100644--- a/core/tests/switch_core/messages/test_notify.py+++ b/core/tests/switch_core/messages/test_notify.py@@ -59,7 +59,7 @@ async def listener(postgres_url: str) -> AsyncIterator[MessageListener]:async def _make_room(session: AsyncSession) -> str:room = Room(- matrix_room_id=f"!room-{uuid.uuid4().hex[:8]}:test",+ transport_room_id=f"!room-{uuid.uuid4().hex[:8]}:test",name="a room",description="",)diff --git a/core/tests/switch_core/messages/test_recorded_types.py b/core/tests/switch_core/messages/test_recorded_types.pyindex a4de15364..5bfa978aa 100644--- a/core/tests/switch_core/messages/test_recorded_types.py+++ b/core/tests/switch_core/messages/test_recorded_types.py@@ -1,11 +1,11 @@"""The classification has to keep up with the dispatch table.-A custom event type added to `ClientBase._EVENT_DISPATCH` without a decision+A custom event type added to `Consumer._EVENT_DISPATCH` without a decisionhere is recorded by default, which is the safe direction but not a decision.These tests make the omission visible instead of letting it ride."""-from switch_core.clients.client_base import ClientBase+from switch_core.clients.consumer import Consumerfrom switch_core.messages.recorded_types import (EPHEMERAL,NOT_RECORDED,@@ -21,7 +21,7 @@ RECORDED_CUSTOM_TYPES = frozenset({"com.switch.command"})def test_every_dispatched_type_is_classified():- dispatched = set(ClientBase._EVENT_DISPATCH)+ dispatched = set(Consumer._EVENT_DISPATCH)unclassified = dispatched - NOT_RECORDED - RECORDED_CUSTOM_TYPESassert not unclassified, ("These custom event types are neither recorded nor denied. Decide "@@ -31,7 +31,7 @@ def test_every_dispatched_type_is_classified():def test_classification_names_no_type_that_is_never_dispatched():- dispatched = set(ClientBase._EVENT_DISPATCH)+ dispatched = set(Consumer._EVENT_DISPATCH)stale = (NOT_RECORDED | RECORDED_CUSTOM_TYPES) - dispatched - RETIREDassert not stale, f"Classified but no longer dispatched: {sorted(stale)}"@@ -39,7 +39,7 @@ def test_classification_names_no_type_that_is_never_dispatched():def test_retired_types_are_the_ones_nothing_dispatches():"""The set exists for types the code no longer has. A name that is back inthe dispatch table is a live type and belongs in a live bucket."""- revived = RETIRED & set(ClientBase._EVENT_DISPATCH)+ revived = RETIRED & set(Consumer._EVENT_DISPATCH)assert not revived, f"Retired but dispatched again: {sorted(revived)}"diff --git a/core/tests/switch_core/observability/test_agent_protocol_metrics.py b/core/tests/switch_core/observability/test_agent_protocol_metrics.pyindex 21bbd5e9b..86e449be7 100644--- a/core/tests/switch_core/observability/test_agent_protocol_metrics.py+++ b/core/tests/switch_core/observability/test_agent_protocol_metrics.py@@ -12,11 +12,11 @@ from collections.abc import Iteratorimport pytest-from switch_core.bridges.agent.protocol import connections as conn_module-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol import agent_connections as conn_module+from switch_core.bridges.agent.protocol.agent_connections import (PROTOCOL_VERSION,+ AgentConnectionRegistry,ClientDeclaration,- ConnectionRegistry,)from switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.bridges.agent.protocol.types import AgentEvent, MessagePayload@@ -88,7 +88,7 @@ def test_nothing_is_counted_when_nothing_is_dropped(registry):def test_expired_connections_are_counted(registry, monkeypatch):"""A flat connection count hides agents reconnecting as fast as they lapse."""- connections = ConnectionRegistry()+ connections = AgentConnectionRegistry()connections.open(agent_id="agent-1",connection_id="c1",@@ -113,7 +113,7 @@ def test_expired_connections_are_counted(registry, monkeypatch):def test_a_quiet_sweep_counts_nothing(registry):- connections = ConnectionRegistry()+ connections = AgentConnectionRegistry()connections.open(agent_id="agent-1",connection_id="c1",diff --git a/core/tests/switch_core/observability/test_bootstrap.py b/core/tests/switch_core/observability/test_bootstrap.pyindex 5850c50dc..d384b6f03 100644--- a/core/tests/switch_core/observability/test_bootstrap.py+++ b/core/tests/switch_core/observability/test_bootstrap.py@@ -71,7 +71,7 @@ def _probes(**overrides) -> RuntimeProbes:bridges_running=lambda: 2,bridges_running_by_platform=lambda: {"slack": 1, "mattermost": 1},bridges_configured=lambda: 2,- clients_running=lambda: 5,+ consumers_running=lambda: 5,connectors_running=lambda: 2,connectors_configured=lambda: 2,agents_connected=lambda: 3,@@ -164,7 +164,7 @@ async def test_an_endpoint_installs_the_registry_and_reports_state(monkeypatch):if payload.numbers and not payload.numbers[0].attributes}assert values["switch.agents.connected"] == 3.0- assert values["switch.clients.running"] == 5.0+ assert values["switch.consumers.running"] == 5.0assert values["switch.connectors.running"] == 2.0assert values["switch.db.pool.in_use"] == 4.0assert values["switch.db.pool.size"] == 30.0diff --git a/core/tests/switch_core/observability/test_bridge_timing.py b/core/tests/switch_core/observability/test_bridge_timing.pyindex c7f283772..9ec9ff5d1 100644--- a/core/tests/switch_core/observability/test_bridge_timing.py+++ b/core/tests/switch_core/observability/test_bridge_timing.py@@ -16,7 +16,7 @@ from __future__ import annotationsimport pytest-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.lifecycle_service import (CollaborationBridgeLifecycleService,)@@ -48,15 +48,15 @@ def _calls(registry: MetricsRegistry) -> dict[tuple[str, str], tuple[int, float]class _Bridge:- """The `_counted_outbound` contextmanager, off a real `BridgeCore`.+ """The `_counted_outbound` contextmanager, off a real `CollaborationCore`.Built by `__new__` rather than through the constructor: the manager reads- one attribute, and standing up a whole `BridgeCore` would need a database,+ one attribute, and standing up a whole `CollaborationCore` would need a database,an adapter and six stores to test a `time.perf_counter()` pair."""def __new__(cls, bridge_type: str):- core = object.__new__(BridgeCore)+ core = object.__new__(CollaborationCore)core._bridge_type = bridge_type # type: ignore[attr-defined]return corediff --git a/core/tests/switch_core/observability/test_log_context_bindings.py b/core/tests/switch_core/observability/test_log_context_bindings.pyindex 8a6ebc8f6..7bb79c412 100644--- a/core/tests/switch_core/observability/test_log_context_bindings.py+++ b/core/tests/switch_core/observability/test_log_context_bindings.py@@ -16,15 +16,15 @@ from typing import Anyimport pytest-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (HEARTBEAT_LAPSED,PROTOCOL_VERSION,+ AgentConnectionRegistry,ClientDeclaration,- ConnectionRegistry,)from switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.bridges.agent.protocol.types import AgentEvent, MessagePayload-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.logging_context import LogContextFilter, current_log_contextfrom switch_core.transport.postgres import PostgresTransport@@ -65,6 +65,7 @@ class TestTheDeliveryLoopBindsItsRoom:async def test_a_failing_drain_carries_the_room(self, captured: _Capture) -> None:transport = object.__new__(PostgresTransport)transport.user_id = "@someone:test" # type: ignore[attr-defined]+ transport._actor_role = "agent" # type: ignore[attr-defined]transport._wake = asyncio.Event() # type: ignore[attr-defined]transport._pending = {"room-7"} # type: ignore[attr-defined]transport._delivering = False # type: ignore[attr-defined]@@ -93,6 +94,7 @@ class TestTheDeliveryLoopBindsItsRoom:every later line in the same task."""transport = object.__new__(PostgresTransport)transport.user_id = "@someone:test" # type: ignore[attr-defined]+ transport._actor_role = "agent" # type: ignore[attr-defined]transport._wake = asyncio.Event() # type: ignore[attr-defined]transport._pending = {"room-7"} # type: ignore[attr-defined]transport._delivering = False # type: ignore[attr-defined]@@ -119,7 +121,7 @@ class TestTheProtocolBindsItsAgent:connected or keeps missing events."""def test_a_closing_connection_carries_the_agent(self, captured: _Capture) -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()registry.open(agent_id="agent-42",connection_id="c1",@@ -171,7 +173,7 @@ class TestTheBridgeInboundPathBindsItsRoom:async def test_an_inbound_event_carries_the_room_it_is_for(self, captured: _Capture) -> None:- bridge = _bridge_core("slack", channel_to_room={"C1": ["room-5"]})+ bridge = _collaboration_core("slack", channel_to_room={"C1": ["room-5"]})async def handler(event) -> None:logging.getLogger("switch_core.test").info("handling the event")@@ -190,7 +192,7 @@ class TestTheBridgeInboundPathBindsItsRoom:"""Auto-room-creation, still ahead of the handler. There is no room toname, and inventing one would be worse than the absence — `None` is thehonest reading."""- bridge = _bridge_core("slack", channel_to_room={})+ bridge = _collaboration_core("slack", channel_to_room={})async def handler(event) -> None:logging.getLogger("switch_core.test").info("handling the event")@@ -209,13 +211,13 @@ class _InboundEvent:self.channel_id = channel_id-def _bridge_core(bridge_type: str, *, channel_to_room: dict[str, list[str]]):- """A `BridgeCore` with only what `_traced` reads.+def _collaboration_core(bridge_type: str, *, channel_to_room: dict[str, list[str]]):+ """A `CollaborationCore` with only what `_traced` reads.Through `__new__` for the reason the outbound one is: the real constructorwants an adapter and six stores, none of which this path touches."""- core = object.__new__(BridgeCore)+ core = object.__new__(CollaborationCore)core._bridge_type = bridge_type # type: ignore[attr-defined]core._bridge_tenant_id = "tenant-1" # type: ignore[attr-defined]core._channel_to_room = channel_to_room # type: ignore[attr-defined]diff --git a/core/tests/switch_core/provisioning/test_postgres_provisioning.py b/core/tests/switch_core/provisioning/test_postgres_provisioning.pyindex 4b8102cac..ef92ac2ed 100644--- a/core/tests/switch_core/provisioning/test_postgres_provisioning.py+++ b/core/tests/switch_core/provisioning/test_postgres_provisioning.py@@ -30,7 +30,7 @@ from tests.conftest import RLSHarnessasync def _client(session: AsyncSession, name: str = "someone") -> Client:client = Client(- matrix_user_id=f"@{name}-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@{name}-{uuid.uuid4().hex[:8]}:test",display_name=name,type="agent",)@@ -40,7 +40,7 @@ async def _client(session: AsyncSession, name: str = "someone") -> Client:async def _room(session: AsyncSession) -> Room:- room = Room(matrix_room_id=new_room_id(), name="a room", description="")+ room = Room(transport_room_id=new_room_id(), name="a room", description="")session.add(room)await session.flush()return room@@ -81,7 +81,7 @@ class TestRooms:assert first != secondasync with session_factory() as session:- assert await RoomStore().get_by_matrix_room_id(session, first) is None+ assert await RoomStore().get_by_transport_room_id(session, first) is Noneclass TestMembership:@@ -92,8 +92,8 @@ class TestMembership:room = await _room(session)client = await _client(session, "nova")await session.commit()- room_id, transport_room_id = room.id, room.matrix_room_id- client_id, user_id = client.id, client.matrix_user_id+ room_id, transport_room_id = room.id, room.transport_room_id+ client_id, user_id = client.id, client.transport_user_idawait _provisioning(session_factory).invite_to_room(transport_room_id, user_id)@@ -123,8 +123,8 @@ class TestMembership:room = await _room(session)client = await _client(session)await session.commit()- room_id, transport_room_id = room.id, room.matrix_room_id- client_id, user_id = client.id, client.matrix_user_id+ room_id, transport_room_id = room.id, room.transport_room_id+ client_id, user_id = client.id, client.transport_user_idwoken: list[str] = []@@ -132,7 +132,7 @@ class TestMembership:woken.append(invited_to)# By client id: the bus is keyed on `clients.id`, not on the handle,- # because `matrix_user_id` is unique per tenant and every tenant's+ # because `transport_user_id` is unique per tenant and every tenant's# admin client carries the same one.invites = InviteBus()invites.register(client_id, _handler, _never)@@ -155,7 +155,10 @@ class TestMembership:room = await _room(session)client = await _client(session)await session.commit()- transport_room_id, user_id = room.matrix_room_id, client.matrix_user_id+ transport_room_id, user_id = (+ room.transport_room_id,+ client.transport_user_id,+ )room_id, client_id = room.id, client.idprovisioning = _provisioning(session_factory)@@ -180,7 +183,10 @@ class TestMembership:room = await _room(session)client = await _client(session)await session.commit()- transport_room_id, user_id = room.matrix_room_id, client.matrix_user_id+ transport_room_id, user_id = (+ room.transport_room_id,+ client.transport_user_id,+ )room_id, client_id = room.id, client.idprovisioning = _provisioning(session_factory)@@ -212,7 +218,10 @@ class TestMembership:room = await _room(session)client = await _client(session)await session.commit()- transport_room_id, user_id = room.matrix_room_id, client.matrix_user_id+ transport_room_id, user_id = (+ room.transport_room_id,+ client.transport_user_id,+ )room_id, client_id = room.id, client.idtold: list[str] = []@@ -253,7 +262,10 @@ class TestMembership:room = await _room(session)client = await _client(session)await session.commit()- transport_room_id, user_id = room.matrix_room_id, client.matrix_user_id+ transport_room_id, user_id = (+ room.transport_room_id,+ client.transport_user_id,+ )client_id = client.idtold: list[str] = []@@ -280,7 +292,10 @@ class TestMembership:room = await _room(session)client = await _client(session)await session.commit()- transport_room_id, user_id = room.matrix_room_id, client.matrix_user_id+ transport_room_id, user_id = (+ room.transport_room_id,+ client.transport_user_id,+ )await _provisioning(session_factory).kick_user(transport_room_id, user_id)@@ -290,7 +305,7 @@ class TestMembership:async with session_factory() as session:room = await _room(session)await session.commit()- transport_room_id = room.matrix_room_id+ transport_room_id = room.transport_room_idprovisioning = _provisioning(session_factory)with pytest.raises(ProvisioningError):@@ -312,7 +327,10 @@ class TestMembership:room = await _room(session)client = await _client(session)await session.commit()- transport_room_id, user_id = room.matrix_room_id, client.matrix_user_id+ transport_room_id, user_id = (+ room.transport_room_id,+ client.transport_user_id,+ )woken: list[str] = []@@ -374,20 +392,20 @@ class TestTwoTenantsSharingAHandle:await session.flush()client = Client(tenant_id=tenant_id,- matrix_user_id=handle,+ transport_user_id=handle,display_name="admin",type="admin",)room = Room(tenant_id=tenant_id,- matrix_room_id=new_room_id(),+ transport_room_id=new_room_id(),name="a room",description="",)session.add_all([client, room])await session.commit()clients[tenant_id] = client.id- rooms[tenant_id] = room.matrix_room_id+ rooms[tenant_id] = room.transport_room_idwoken: dict[str, list[str]] = {tenant_id: [] for tenant_id in tenants}diff --git a/core/tests/switch_core/session_activity/bridge_fixtures.py b/core/tests/switch_core/session_activity/bridge_fixtures.pyindex 243023a3a..5b781bb12 100644--- a/core/tests/switch_core/session_activity/bridge_fixtures.py+++ b/core/tests/switch_core/session_activity/bridge_fixtures.py@@ -24,19 +24,22 @@ class BridgedRoom:async def make_bridged_room(db, *, member: str) -> BridgedRoom:suffix = uuid.uuid4().hex[:8]- bridge_client = Client(- matrix_user_id=f"@bridge-{suffix}:test", display_name="bridge", type="bridge"+ workspace_consumer = Client(+ transport_user_id=f"@bridge-{suffix}:test", display_name="bridge", type="bridge")- db.add(bridge_client)+ db.add(workspace_consumer)await db.flush()bridge = CollaborationBridge(- type="slack", display_name="Slack", client_id=bridge_client.id, status="active"+ type="slack",+ display_name="Slack",+ client_id=workspace_consumer.id,+ status="active",)db.add(bridge)await db.flush()channel_id = f"C{suffix}"room = Room(- matrix_room_id=f"!{suffix}:test",+ transport_room_id=f"!{suffix}:test",name=f"room-{suffix}",description="",bridge_id=bridge.id,@@ -59,7 +62,7 @@ class Drawn:@dataclassclass RecordingPlatform:- """Duck-typed `CollaborationAdapter`: only what the publisher calls."""+ """Duck-typed `PlatformAdapter`: only what the publisher calls."""platform_name: str = "Test"draws_session_activity: bool = Truediff --git a/core/tests/switch_core/session_activity/conftest.py b/core/tests/switch_core/session_activity/conftest.pyindex 12a4dd99a..c130d9d97 100644--- a/core/tests/switch_core/session_activity/conftest.py+++ b/core/tests/switch_core/session_activity/conftest.py@@ -22,8 +22,8 @@ from switch_core.db.models import (User,room_agents,)-from switch_core.session_activity.listener import Change, SessionActivityListener-from switch_core.session_activity.service import SessionActivityService+from switch_core.session_activity.listener import AgentSessionActivityListener, Change+from switch_core.session_activity.service import AgentSessionActivityServicefrom switch_core.sessions.contract import ApprovalResultfrom switch_core.tenant_context import current_tenant_id@@ -53,7 +53,9 @@ async def make_agent(type="agent",)client = Client(- matrix_user_id=f"@{agent_id}:example.test", display_name=agent_id, type="agent"+ transport_user_id=f"@{agent_id}:example.test",+ display_name=agent_id,+ type="agent",)db.add_all([key, client])await db.flush()@@ -77,7 +79,9 @@ async def make_agent(async def make_room(db, *, member: str | None) -> str:suffix = uuid.uuid4().hex[:8]- room = Room(matrix_room_id=f"!{suffix}:test", name=f"room-{suffix}", description="")+ room = Room(+ transport_room_id=f"!{suffix}:test", name=f"room-{suffix}", description=""+ )db.add(room)await db.flush()if member is not None:@@ -88,16 +92,19 @@ async def make_room(db, *, member: str | None) -> str:async def make_person(db, *, claimed_by: str | None) -> str:"""A person on a messaging platform; returns the Switch identity they answer as."""suffix = uuid.uuid4().hex[:8]- bridge_client = Client(- matrix_user_id=f"@bridge-{suffix}:test", display_name="bridge", type="bridge"+ workspace_consumer = Client(+ transport_user_id=f"@bridge-{suffix}:test", display_name="bridge", type="bridge")person = Client(- matrix_user_id=f"@person-{suffix}:test", display_name="person", type="user"+ transport_user_id=f"@person-{suffix}:test", display_name="person", type="user")- db.add_all([bridge_client, person])+ db.add_all([workspace_consumer, person])await db.flush()bridge = CollaborationBridge(- type="slack", display_name="Slack", client_id=bridge_client.id, status="active"+ type="slack",+ display_name="Slack",+ client_id=workspace_consumer.id,+ status="active",)db.add(bridge)await db.flush()@@ -112,7 +119,7 @@ async def make_person(db, *, claimed_by: str | None) -> str:if claimed_by is not None:db.add(ExternalUserClaim(external_user_id=account.id, user_id=claimed_by))await db.flush()- return person.matrix_user_id+ return person.transport_user_id@dataclass(frozen=True)@@ -132,8 +139,8 @@ async def people(session_factory) -> People:@pytest.fixture-async def service(session_factory, people) -> SessionActivityService:- return SessionActivityService(session_factory)+async def service(session_factory, people) -> AgentSessionActivityService:+ return AgentSessionActivityService(session_factory)class Recorder:@@ -165,7 +172,7 @@ class Recorder:async def changes(postgres_url) -> AsyncIterator[Recorder]:tenant = current_tenant_id()assert tenant is not None- listener = SessionActivityListener(+ listener = AgentSessionActivityListener(lambda: create_async_engine(postgres_url, poolclass=NullPool))recorder = Recorder()diff --git a/core/tests/switch_core/session_activity/test_command_relay.py b/core/tests/switch_core/session_activity/test_command_relay.pyindex e8f14193f..863272877 100644--- a/core/tests/switch_core/session_activity/test_command_relay.py+++ b/core/tests/switch_core/session_activity/test_command_relay.py@@ -7,10 +7,10 @@ import httpximport pytestfrom fastapi import FastAPI-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (SESSION_COMMAND_PROTOCOL_REVISION,+ AgentConnectionRegistry,ClientDeclaration,- ConnectionRegistry,)from switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.bridges.agent.protocol.stream import event_stream@@ -28,11 +28,11 @@ FRAME = {"sessionId": "session-1", "commandId": "command-1"}class _Protocol:- def __init__(self, registry: ConnectionRegistry) -> None:+ def __init__(self, registry: AgentConnectionRegistry) -> None:self.connections = registry-def _watcher(registry: ConnectionRegistry, *, speaks: int, scope: str = "all"):+def _watcher(registry: AgentConnectionRegistry, *, speaks: int, scope: str = "all"):conn = registry.open(agent_id=AGENT,connection_id=f"conn-{scope}-{speaks}",@@ -70,7 +70,7 @@ async def owner(session_factory, people) -> str:async def test_a_relayed_session_command_reaches_the_watcher_stream() -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()_, stream = _watcher(registry, speaks=SESSION_COMMAND_PROTOCOL_REVISION)try:await anext(stream) # connection_state@@ -92,7 +92,7 @@ async def test_a_relayed_session_command_reaches_the_watcher_stream() -> None:],)async def test_a_command_nobody_can_take_is_not_relayed(speaks, scope) -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn, stream = _watcher(registry, speaks=speaks, scope=scope)conn.stream_attached = Trueassert registry.relay_session_command(AGENT, FRAME) is False@@ -104,7 +104,7 @@ async def test_switch_does_not_answer_where_an_agents_sessions_are(session_factory, owner) -> None:"""The agent's room watcher owns its connection and placements; Console asks it."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()_watcher(registry, speaks=SESSION_COMMAND_PROTOCOL_REVISION)registry.place_session(AGENT, "session-1", "room-1", f"conn-all-{SESSION_COMMAND_PROTOCOL_REVISION}"diff --git a/core/tests/switch_core/session_activity/test_isolation.py b/core/tests/switch_core/session_activity/test_isolation.pyindex 71c486d13..29d5848b7 100644--- a/core/tests/switch_core/session_activity/test_isolation.py+++ b/core/tests/switch_core/session_activity/test_isolation.py@@ -8,17 +8,17 @@ from sqlalchemy import selectfrom switch_core.db.models import (Agent,+ AgentSessionActivityItem,ApiKey,ApprovalRequest,Client,- SessionActivityItem,Tenant,User,)from switch_core.session_activity.service import (+ AgentSessionActivityService,ApprovalOption,PlatformPerson,- SessionActivityService,)from switch_core.sessions.errors import SessionErrorfrom switch_core.tenant_context import tenant_scope@@ -26,7 +26,7 @@ from switch_core.tenant_context import tenant_scopefrom .conftest import pick-async def _seed(harness, tenant: str) -> SessionActivityService:+async def _seed(harness, tenant: str) -> AgentSessionActivityService:async with harness.owner() as db, db.begin():db.add(Tenant(id=tenant, slug=tenant, name=tenant))db.add(@@ -42,7 +42,7 @@ async def _seed(harness, tenant: str) -> SessionActivityService:type="agent",)client = Client(- matrix_user_id=f"@agent-{tenant}:example.test",+ transport_user_id=f"@agent-{tenant}:example.test",display_name="Agent",type="agent",)@@ -61,7 +61,7 @@ async def _seed(harness, tenant: str) -> SessionActivityService:owner_id=tenant,))- return SessionActivityService(harness.restricted)+ return AgentSessionActivityService(harness.restricted)async def test_each_tenant_sees_only_its_own_activity_and_requests(rls_harness):@@ -103,7 +103,7 @@ async def test_each_tenant_sees_only_its_own_activity_and_requests(rls_harness):for tenant in services:with tenant_scope(tenant):async with rls_harness.restricted() as db:- for model in (SessionActivityItem, ApprovalRequest):+ for model in (AgentSessionActivityItem, ApprovalRequest):rows = (await db.scalars(select(model))).all()assert {row.tenant_id for row in rows} == {tenant}diff --git a/core/tests/switch_core/session_activity/test_maintenance.py b/core/tests/switch_core/session_activity/test_maintenance.pyindex 40c5c09a9..36dc2857f 100644--- a/core/tests/switch_core/session_activity/test_maintenance.py+++ b/core/tests/switch_core/session_activity/test_maintenance.py@@ -4,7 +4,7 @@ from datetime import UTC, datetime, timedeltafrom sqlalchemy import update-from switch_core.db.models import ApprovalRequest, SessionActivityItem+from switch_core.db.models import AgentSessionActivityItem, ApprovalRequestfrom switch_core.session_activity.maintenance import maintain_oncefrom switch_core.session_activity.service import ApprovalOption@@ -54,7 +54,7 @@ async def test_a_pass_expires_overdue_requests_and_prunes_only_when_asked()past = datetime.now(UTC) - timedelta(days=30)await _backdate(session_factory, ApprovalRequest, expires_at=past)- await _backdate(session_factory, SessionActivityItem, updated_at=past)+ await _backdate(session_factory, AgentSessionActivityItem, updated_at=past)await maintain_once(session_factory, prune=False)[owed] = await service.undelivered_outcomes(AGENT)diff --git a/core/tests/switch_core/session_activity/test_bridge_publisher.py b/core/tests/switch_core/session_activity/test_publisher.pysimilarity index 98%rename from core/tests/switch_core/session_activity/test_bridge_publisher.pyrename to core/tests/switch_core/session_activity/test_publisher.pyindex c0bf3f5fb..abcc49d96 100644--- a/core/tests/switch_core/session_activity/test_bridge_publisher.py+++ b/core/tests/switch_core/session_activity/test_publisher.py@@ -15,10 +15,10 @@ from switch_core.db.models import (BridgeMessageMap,TurnStatusPost,)-from switch_core.session_activity.bridge_publisher import (- SessionActivityBridgePublisher,+from switch_core.session_activity.listener import AgentSessionActivityListener+from switch_core.session_activity.publisher import (+ AgentSessionActivityPublisher,)-from switch_core.session_activity.listener import SessionActivityListenerfrom switch_core.session_activity.service import (ApprovalOption,PlatformPerson,@@ -64,8 +64,8 @@ async def bridged(session_factory, people) -> BridgedRoom:@pytest.fixture-async def listener(postgres_url) -> AsyncIterator[SessionActivityListener]:- listener = SessionActivityListener(+async def listener(postgres_url) -> AsyncIterator[AgentSessionActivityListener]:+ listener = AgentSessionActivityListener(lambda: create_async_engine(postgres_url, poolclass=NullPool))await listener.start()@@ -89,7 +89,7 @@ def online() -> Online:def _publisher(session_factory, bridged, listener, platform, online):tenant = current_tenant_id()assert tenant is not None- return SessionActivityBridgePublisher(+ return AgentSessionActivityPublisher(adapter=platform, # type: ignore[arg-type]bridge_id=bridged.bridge_id,bridge_type="slack",@@ -104,7 +104,7 @@ def _publisher(session_factory, bridged, listener, platform, online):@pytest.fixtureasync def publisher(session_factory, bridged, listener, platform, online-) -> AsyncIterator[SessionActivityBridgePublisher]:+) -> AsyncIterator[AgentSessionActivityPublisher]:publisher = _publisher(session_factory, bridged, listener, platform, online)publisher.start()try:diff --git a/core/tests/switch_core/session_activity/test_stop_press.py b/core/tests/switch_core/session_activity/test_stop_press.pyindex efb263e49..c2e6a60ad 100644--- a/core/tests/switch_core/session_activity/test_stop_press.py+++ b/core/tests/switch_core/session_activity/test_stop_press.py@@ -6,16 +6,16 @@ import pytestfrom sqlalchemy import updatefrom switch_core.addressing import owner_only_policy-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (SESSION_COMMAND_PROTOCOL_REVISION,+ AgentConnectionRegistry,ClientDeclaration,- ConnectionRegistry,)-from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.models import InboundInteractionfrom switch_core.bridges.collaboration.session.renderers import INTERRUPT_ACTIONfrom switch_core.db.models import Agent-from switch_core.session_activity.bridge_publisher import StopTarget+from switch_core.session_activity.publisher import StopTargetfrom .conftest import AGENT, make_room@@ -39,7 +39,7 @@ class Platform:self.told.append(text)-def _watching(registry: ConnectionRegistry):+def _watching(registry: AgentConnectionRegistry):conn = registry.open(agent_id=AGENT,connection_id="watcher",@@ -60,8 +60,8 @@ async def room(session_factory, people) -> str:return await make_room(db, member=AGENT)-def _bridge(service, registry, target, mxid) -> tuple[BridgeCore, Platform]:- bridge = BridgeCore.__new__(BridgeCore)+def _bridge(service, registry, target, mxid) -> tuple[CollaborationCore, Platform]:+ bridge = CollaborationCore.__new__(CollaborationCore)platform = Platform()bridge._bridge_id = "bridge-1"bridge._bridge_type = "slack"@@ -99,7 +99,7 @@ def _target(room: str, running: str | None = "turn-1") -> StopTarget:async def test_a_press_is_relayed_to_the_session_as_an_interrupt(service, people, room):- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _watching(registry)bridge, platform = _bridge(service, registry, _target(room), people.owner)@@ -124,7 +124,7 @@ async def test_a_press_is_relayed_to_the_session_as_an_interrupt(service, peopleasync def test_a_press_naming_a_turn_that_is_no_longer_running_is_refused(service, people, room):- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _watching(registry)bridge, platform = _bridge(service, registry, _target(room, "turn-2"), people.owner)await bridge._handle_inbound_interaction(_press("turn-1"))@@ -141,7 +141,7 @@ async def test_someone_who_may_not_address_the_agent_cannot_stop_it(.where(Agent.id == AGENT).values(addressing_policy=owner_only_policy([]).model_dump()))- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _watching(registry)bridge, platform = _bridge(service, registry, _target(room), people.stranger)await bridge._handle_inbound_interaction(_press())@@ -157,7 +157,7 @@ async def test_someone_who_may_not_address_the_agent_cannot_stop_it(],)async def test_a_press_nothing_resolves_says_why(service, room, target, mxid, said):- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = _watching(registry)resolved = _target(room) if target == "room" else Nonebridge, platform = _bridge(service, registry, resolved, mxid)@@ -168,7 +168,7 @@ async def test_a_press_nothing_resolves_says_why(service, room, target, mxid, saasync def test_a_press_with_no_controller_attached_says_so(service, people, room):bridge, platform = _bridge(- service, ConnectionRegistry(), _target(room), people.owner+ service, AgentConnectionRegistry(), _target(room), people.owner)await bridge._handle_inbound_interaction(_press())assert "controller is not connected" in platform.told[0]diff --git a/core/tests/switch_core/session_activity/test_stream_outcomes.py b/core/tests/switch_core/session_activity/test_stream_outcomes.pyindex 16c03f019..b9ba763a2 100644--- a/core/tests/switch_core/session_activity/test_stream_outcomes.py+++ b/core/tests/switch_core/session_activity/test_stream_outcomes.py@@ -11,16 +11,16 @@ from sqlalchemy import updatefrom sqlalchemy.ext.asyncio import create_async_enginefrom sqlalchemy.pool import NullPool-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (APPROVAL_OUTCOME_PROTOCOL_REVISION,PROTOCOL_VERSION,+ AgentConnectionRegistry,ClientDeclaration,- ConnectionRegistry,)from switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.bridges.agent.protocol.stream import event_streamfrom switch_core.db.models import ApprovalRequest-from switch_core.session_activity.listener import SessionActivityListener+from switch_core.session_activity.listener import AgentSessionActivityListenerfrom switch_core.session_activity.outcomes import ApprovalOutcomesfrom switch_core.session_activity.service import ApprovalOption, PlatformPerson@@ -35,7 +35,7 @@ OPTIONS = [@pytest.fixtureasync def approvals(service, postgres_url) -> AsyncIterator[ApprovalOutcomes]:- listener = SessionActivityListener(+ listener = AgentSessionActivityListener(lambda: create_async_engine(postgres_url, poolclass=NullPool))await listener.start()@@ -50,7 +50,7 @@ async def approvals(service, postgres_url) -> AsyncIterator[ApprovalOutcomes]:def _open_stream(approvals, *, agent_id=AGENT, scope="all", speaks=PROTOCOL_VERSION):- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()conn = registry.open(agent_id=agent_id,connection_id=f"conn-{agent_id}-{scope}",diff --git a/core/tests/switch_core/telemetry/test_bridge_connect_reporting.py b/core/tests/switch_core/telemetry/test_bridge_connect_reporting.pyindex e93b53b5a..6307b922b 100644--- a/core/tests/switch_core/telemetry/test_bridge_connect_reporting.py+++ b/core/tests/switch_core/telemetry/test_bridge_connect_reporting.py@@ -95,7 +95,7 @@ def _service_with_telemetry(client_store=client_store if client_store is not None else ClientStore(),client_lifecycle=MagicMock(),room_service=MagicMock(),- matrix_admin=MagicMock(),+ provisioning=MagicMock(),session_factory=session_factory,config=config,client_factory=MagicMock(),@@ -157,7 +157,7 @@ class _PortHoldingAdapter(_StubAdapter):class _FailingCore:- """A `bridge_core.start()` that never reaches the platform at all -- the+ """A `collaboration_core.start()` that never reaches the platform at all -- the`_run_bridge` branch that still reports `bridge_connected{failure}`,as opposed to a `bridge_disconnected` for a bridge that connected andthen dropped."""@@ -178,7 +178,7 @@ async def _bridge_row(not cover."""client = Client(tenant_id=tenant_id,- matrix_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",display_name="bridge client",type="bridge",)@@ -218,6 +218,7 @@ class TestEachStartFailurePointReportsAndReraises:events = await _bridge_connected_events(sink)assert events == [{+ "bridge": "collaboration","bridge_platform": "unknown","outcome": "failure","failure_reason": "config_invalid",@@ -245,6 +246,7 @@ class TestEachStartFailurePointReportsAndReraises:events = await _bridge_connected_events(sink)assert events == [{+ "bridge": "collaboration","bridge_platform": "mattermost","outcome": "failure","failure_reason": "config_invalid",@@ -276,6 +278,7 @@ class TestEachStartFailurePointReportsAndReraises:events = await _bridge_connected_events(sink)assert events == [{+ "bridge": "collaboration","bridge_platform": "unknown","outcome": "failure","failure_reason": "config_invalid",@@ -310,6 +313,7 @@ class TestEachStartFailurePointReportsAndReraises:events = await _bridge_connected_events(sink)assert events == [{+ "bridge": "collaboration","bridge_platform": "teams","outcome": "failure","failure_reason": "config_invalid",@@ -339,6 +343,7 @@ class TestEachStartFailurePointReportsAndReraises:events = await _bridge_connected_events(sink)assert events == [{+ "bridge": "collaboration","bridge_platform": "mattermost","outcome": "failure","failure_reason": "config_invalid",@@ -365,6 +370,7 @@ class TestEachStartFailurePointReportsAndReraises:events = await _bridge_connected_events(sink)assert events == [{+ "bridge": "collaboration","bridge_platform": "mattermost","outcome": "failure",# RuntimeError carries no reason any rule recognises -- an@@ -402,6 +408,7 @@ class TestEachStartFailurePointReportsAndReraises:events = await _bridge_connected_events(sink)assert events == [{+ "bridge": "collaboration","bridge_platform": "mattermost","outcome": "failure","failure_reason": "config_invalid",@@ -440,6 +447,7 @@ class TestStartAllsBootPathIsCoveredToo:events = await _bridge_connected_events(sink)assert events == [{+ "bridge": "collaboration","bridge_platform": "teams","outcome": "failure","failure_reason": "config_invalid",@@ -499,10 +507,10 @@ class TestATaskFailureAfterStartSucceedsIsStillReportedExactlyOnce:# What the scheduled task would have done, awaited directly rather# than raced, the same way `test_lifecycle_callback_endpoint.py`'s- # crash test does -- except `bridge_core.start()` itself is what+ # crash test does -- except `collaboration_core.start()` itself is what# fails here (`_FailingCore`), the branch that reports# `bridge_connected{failure}` from inside `_run_bridge`.- # `bridge_client` never gets far enough to have `.start()` called, so+ # `workspace_consumer` never gets far enough to have `.start()` called, so# only its `client_id` attribute (read first, by# `_record_bridge_memberships`) matters.await type(service)._run_bridge(diff --git a/core/tests/switch_core/telemetry/test_emitters_are_live.py b/core/tests/switch_core/telemetry/test_emitters_are_live.pyindex 97d5ba50e..a1ebc645e 100644--- a/core/tests/switch_core/telemetry/test_emitters_are_live.py+++ b/core/tests/switch_core/telemetry/test_emitters_are_live.py@@ -6,7 +6,7 @@ immediately when the service is `None`, which is deliberate — several servicesare built without one in tests and tooling — and it means a call site can bepresent, correct, covered by its own unit test, and dead in production.-That is exactly what happened. The agent bridge built *two* `ProtocolService`+That is exactly what happened. The agent bridge built *two* `AgentCore`instances: one in `create_agent_bridge_app` that got the telemetry service, andone in `init_dependencies` that the HTTP handlers actually resolve through`Depends(get_protocol)` and that got nothing. Every session event and every@@ -72,12 +72,12 @@ def _config() -> Any:oauth_issuer_url = Noneoauth_audience = Noneoauth_verify_issuer = True- matrix_server_name = "test"+ id_server_name = "test"return _Config()-def test_the_protocol_service_a_request_reaches_can_report() -> None:+def test_the_agent_core_a_request_reaches_can_report() -> None:"""`get_protocol()` is what every handler resolves. If its service has notelemetry, every session event and agent registration at the agent bridgeis silently dropped."""@@ -85,13 +85,13 @@ def test_the_protocol_service_a_request_reaches_can_report() -> None:_build(telemetry)assert get_protocol().telemetry is telemetry, (- "The ProtocolService the HTTP handlers resolve has no telemetry "+ "The AgentCore the HTTP handlers resolve has no telemetry ""service, so every event it emits is dropped by emit_safely. The app ""and init_dependencies must be given the same one.")-def test_the_protocol_service_the_app_returns_is_the_one_handlers_use() -> None:+def test_the_agent_core_the_app_returns_is_the_one_handlers_use() -> None:"""Two instances is the shape that caused the drop. They must be one, ora future change will wire telemetry to whichever is convenient and leavethe other dead again."""@@ -99,7 +99,7 @@ def test_the_protocol_service_the_app_returns_is_the_one_handlers_use() -> None:returned = _build(telemetry)assert get_protocol() is returned, (- "create_agent_bridge_app returns a different ProtocolService from the "+ "create_agent_bridge_app returns a different AgentCore from the ""one its handlers use. Anything wired onto one is absent from the ""other — which is how the session events came to be emitted into ""nothing."diff --git a/core/tests/switch_core/telemetry/test_merge_fixes.py b/core/tests/switch_core/telemetry/test_merge_fixes.pyindex c0910a841..312631f56 100644--- a/core/tests/switch_core/telemetry/test_merge_fixes.py+++ b/core/tests/switch_core/telemetry/test_merge_fixes.py@@ -19,11 +19,11 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.agent.api import session_reporterfrom switch_core.bridges.agent.api.session_reporter import SessionReporter-from switch_core.bridges.agent.protocol.connections import (+from switch_core.bridges.agent.protocol.agent_connections import (HEARTBEAT_LAPSED,+ AgentConnectionRegistry,ClientDeclaration,Closure,- ConnectionRegistry,)from switch_core.telemetry.service import TelemetryServicefrom switch_core.telemetry.sink import TelemetryRecord@@ -132,7 +132,7 @@ class TestASessionIsTheAgentNotTheConnection:"""def _reporter(- self, sink: _RecordingSink, registry: ConnectionRegistry+ self, sink: _RecordingSink, registry: AgentConnectionRegistry) -> SessionReporter:service = TelemetryService(sink=sink, # type: ignore[arg-type]@@ -146,7 +146,7 @@ class TestASessionIsTheAgentNotTheConnection:registry.set_close_listener(reporter.on_close)return reporter- def _open(self, registry: ConnectionRegistry, agent: str = "agent-1") -> str:+ def _open(self, registry: AgentConnectionRegistry, agent: str = "agent-1") -> str:connection_id = uuid.uuid4().hexregistry.open(agent_id=agent,@@ -161,7 +161,7 @@ class TestASessionIsTheAgentNotTheConnection:return connection_idasync def _stream(- self, reporter: SessionReporter, registry: ConnectionRegistry, cid: str+ self, reporter: SessionReporter, registry: AgentConnectionRegistry, cid: str) -> None:conn = registry.get(cid)assert conn is not None@@ -175,7 +175,7 @@ class TestASessionIsTheAgentNotTheConnection:async def test_a_rejected_stream_reports_nothing(self) -> None:"""No stream was handed back, so no session began."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()sink = _RecordingSink()self._reporter(sink, registry)@@ -187,7 +187,7 @@ class TestASessionIsTheAgentNotTheConnection:async def test_twenty_rejected_attempts_report_nothing(self) -> None:"""The retry loop, as the dashboard actually saw it."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()sink = _RecordingSink()self._reporter(sink, registry)@@ -203,7 +203,7 @@ class TestASessionIsTheAgentNotTheConnection:) -> None:"""The heartbeat-lapse loop: one session, not one per six seconds."""monkeypatch.setattr(session_reporter, "_RECONNECT_GRACE_SECONDS", 0.05)- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()sink = _RecordingSink()reporter = self._reporter(sink, registry)@@ -220,7 +220,7 @@ class TestASessionIsTheAgentNotTheConnection:self, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(session_reporter, "_RECONNECT_GRACE_SECONDS", 0.05)- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()sink = _RecordingSink()reporter = self._reporter(sink, registry)@@ -239,7 +239,7 @@ class TestASessionIsTheAgentNotTheConnection:"""Not the last connection's lifetime — the span the agent was present,across however many reconnects it took."""monkeypatch.setattr(session_reporter, "_RECONNECT_GRACE_SECONDS", 0.05)- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()sink = _RecordingSink()reporter = self._reporter(sink, registry)@@ -256,7 +256,7 @@ class TestASessionIsTheAgentNotTheConnection:async def test_a_second_connection_does_not_start_a_second_session(self,) -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()sink = _RecordingSink()reporter = self._reporter(sink, registry)@@ -271,7 +271,7 @@ class TestASessionIsTheAgentNotTheConnection:self, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(session_reporter, "_RECONNECT_GRACE_SECONDS", 0.05)- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()sink = _RecordingSink()reporter = self._reporter(sink, registry)@@ -286,7 +286,7 @@ class TestASessionIsTheAgentNotTheConnection:assert self._names(sink) == ["agent_session_started"]async def test_two_agents_are_two_sessions(self) -> None:- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()sink = _RecordingSink()reporter = self._reporter(sink, registry)@@ -303,7 +303,7 @@ class TestASessionIsTheAgentNotTheConnection:async def test_shutdown_reports_no_ends(self) -> None:"""Every agent disconnects at once when the process stops; a burst ofends saying "the server stopped" is noise, not signal."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()sink = _RecordingSink()reporter = self._reporter(sink, registry)@@ -317,7 +317,7 @@ class TestASessionIsTheAgentNotTheConnection:def test_a_listener_that_raises_does_not_break_the_close(self) -> None:"""The registry's contract — the connection is closed and handed back —must not depend on whoever is watching."""- registry = ConnectionRegistry()+ registry = AgentConnectionRegistry()registry.set_close_listener(lambda conn: (_ for _ in ()).throw(RuntimeError()))cid = self._open(registry)diff --git a/core/tests/switch_core/telemetry/test_room_lifecycle_failure_reporting.py b/core/tests/switch_core/telemetry/test_room_lifecycle_failure_reporting.pyindex 024bfebbc..77f394b20 100644--- a/core/tests/switch_core/telemetry/test_room_lifecycle_failure_reporting.py+++ b/core/tests/switch_core/telemetry/test_room_lifecycle_failure_reporting.py@@ -41,7 +41,7 @@ def _room_service() -> RoomService:"""Only `_session_factory` and `_telemetry` are exercised by the methodsunder test; everything else is unreachable once the session fails."""return RoomService(- matrix_admin=None, # type: ignore[arg-type]+ provisioning=None, # type: ignore[arg-type]room_store=None, # type: ignore[arg-type]agent_store=None, # type: ignore[arg-type]client_lifecycle=None, # type: ignore[arg-type]diff --git a/core/tests/switch_core/telemetry/test_snapshot.py b/core/tests/switch_core/telemetry/test_snapshot.pyindex 005f8a035..5ec349c51 100644--- a/core/tests/switch_core/telemetry/test_snapshot.py+++ b/core/tests/switch_core/telemetry/test_snapshot.py@@ -18,7 +18,7 @@ from sqlalchemy import deletefrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.clients.admin_messages import AUTO_REPLY_FLAG-from switch_core.clients.client_base import ClientBase+from switch_core.clients.consumer import Consumerfrom switch_core.db.models import (Agent,ApiKey,@@ -56,7 +56,7 @@ async def _room(channel_type: str = "channel_public",) -> Room:room = Room(- matrix_room_id=f"!{uuid.uuid4().hex[:10]}:test",+ transport_room_id=f"!{uuid.uuid4().hex[:10]}:test",name=f"room-{uuid.uuid4().hex[:6]}",description="a room",channel_type=channel_type,@@ -72,7 +72,7 @@ async def _room(async def _client(session: AsyncSession, client_type: str) -> Client:client = Client(- matrix_user_id=f"@{client_type}-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@{client_type}-{uuid.uuid4().hex[:8]}:test",display_name=f"{client_type} client",type=client_type,)@@ -97,7 +97,7 @@ async def _agent(session: AsyncSession, runtime: str | None) -> Agent:type="agent",)backing = Client(- matrix_user_id=f"@agent-{slug}:test", display_name="agent", type="agent"+ transport_user_id=f"@agent-{slug}:test", display_name="agent", type="agent")session.add_all([key, backing])await session.flush()@@ -145,7 +145,7 @@ async def _say(room_id=room.id,seq=seq,transport_event_id=f"$evt-{uuid.uuid4().hex}",- sender_id=sender.matrix_user_id,+ sender_id=sender.transport_user_id,sender_client_id=sender.id,event_type="m.room.message",msgtype="m.text",@@ -175,7 +175,7 @@ async def _stored(room_id=room.id,seq=seq,transport_event_id=f"$evt-{uuid.uuid4().hex}",- sender_id=sender.matrix_user_id,+ sender_id=sender.transport_user_id,sender_client_id=sender.id,event_type=event_type,msgtype=None,@@ -1191,7 +1191,7 @@ def test_every_event_type_is_decided_spoken_or_not() -> None:"""A new room event type lands in the message log by default. Undecided,it would either inflate the message counts or be silently left out ofthem; this makes whoever adds one say which."""- known = set(ClientBase._EVENT_DISPATCH) | {"m.room.message", MEMBERSHIP_EVENT_TYPE}+ known = set(Consumer._EVENT_DISPATCH) | {"m.room.message", MEMBERSHIP_EVENT_TYPE}spoken = set(SPOKEN_EVENT_TYPES)assert not (known - spoken - NOT_SPOKEN), (diff --git a/core/tests/switch_core/telemetry/test_snapshot_multi_tenant.py b/core/tests/switch_core/telemetry/test_snapshot_multi_tenant.pyindex f0f61e475..6eafa3ae8 100644--- a/core/tests/switch_core/telemetry/test_snapshot_multi_tenant.py+++ b/core/tests/switch_core/telemetry/test_snapshot_multi_tenant.py@@ -81,7 +81,7 @@ async def _room_with_a_conversation("""One room, one human, one agent, one human message."""async with tenant_session(session_factory, tenant_id) as session:room = Room(- matrix_room_id=f"!{uuid.uuid4().hex[:10]}:test",+ transport_room_id=f"!{uuid.uuid4().hex[:10]}:test",name=f"room-{uuid.uuid4().hex[:6]}",description="a room",channel_type="channel_public",@@ -89,12 +89,12 @@ async def _room_with_a_conversation(metadata_={"created_by_kind": "user"},)human = Client(- matrix_user_id=f"@human-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@human-{uuid.uuid4().hex[:8]}:test",display_name="a person",type="user",)agent = Client(- matrix_user_id=f"@agent-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@agent-{uuid.uuid4().hex[:8]}:test",display_name="an agent",type="agent",)@@ -115,7 +115,7 @@ async def _room_with_a_conversation(room_id=room.id,seq=1,transport_event_id=f"$evt-{uuid.uuid4().hex}",- sender_id=human.matrix_user_id,+ sender_id=human.transport_user_id,sender_client_id=human.id,event_type="m.room.message",msgtype="m.text",diff --git a/core/tests/switch_core/test_config_db_ssl.py b/core/tests/switch_core/test_config_db_ssl.pyindex 3e2fb1d34..f5896810a 100644--- a/core/tests/switch_core/test_config_db_ssl.py+++ b/core/tests/switch_core/test_config_db_ssl.py@@ -16,7 +16,7 @@ _BASE_KWARGS = dict(db_user="postgres",db_password="pw",db_name="switch",- matrix_server_name="switch.local",+ id_server_name="switch.local",agent_registration_token="token",jwt_secret_key="jwt",gateway_admin_email="[email protected]",diff --git a/core/tests/switch_core/test_config_db_user.py b/core/tests/switch_core/test_config_db_user.pyindex 47110e53b..0fe2d06f0 100644--- a/core/tests/switch_core/test_config_db_user.py+++ b/core/tests/switch_core/test_config_db_user.py@@ -8,7 +8,7 @@ _BASE_KWARGS = dict(db_user="postgres",db_password="pw",db_name="switch",- matrix_server_name="switch.local",+ id_server_name="switch.local",agent_registration_token="token",jwt_secret_key="jwt",gateway_admin_email="[email protected]",diff --git a/core/tests/switch_core/test_config_discord_app.py b/core/tests/switch_core/test_config_discord_app.pyindex c3b4d77a1..ea86338d7 100644--- a/core/tests/switch_core/test_config_discord_app.py+++ b/core/tests/switch_core/test_config_discord_app.py@@ -18,7 +18,7 @@ _BASE_KWARGS = dict(db_user="postgres",db_password="pw",db_name="switch",- matrix_server_name="switch.local",+ id_server_name="switch.local",agent_registration_token="token",jwt_secret_key="jwt",gateway_admin_email="[email protected]",diff --git a/core/tests/switch_core/test_config_gateway_public_url.py b/core/tests/switch_core/test_config_gateway_public_url.pyindex d751d2039..23b530da1 100644--- a/core/tests/switch_core/test_config_gateway_public_url.py+++ b/core/tests/switch_core/test_config_gateway_public_url.py@@ -8,7 +8,7 @@ _BASE_KWARGS = dict(db_user="postgres",db_password="pw",db_name="switch",- matrix_server_name="switch.local",+ id_server_name="switch.local",agent_registration_token="token",jwt_secret_key="jwt",gateway_admin_email="[email protected]",diff --git a/core/tests/switch_core/test_config_id_server_name.py b/core/tests/switch_core/test_config_id_server_name.pynew file mode 100644index 000000000..0938e2180--- /dev/null+++ b/core/tests/switch_core/test_config_id_server_name.py@@ -0,0 +1,49 @@+"""ID_SERVER_NAME replaced MATRIX_SERVER_NAME; the old name still works for now."""++from __future__ import annotations++import pytest++from switch_core.config import SwitchConfig, deprecated_env_names++_REQUIRED = {+ "DB_HOST": "localhost",+ "DB_PORT": "5432",+ "DB_USER": "switch_app",+ "DB_PASSWORD": "x",+ "DB_NAME": "switch",+ "DB_OWNER_USER": "switch_owner",+ "DB_OWNER_PASSWORD": "x",+ "AGENT_REGISTRATION_TOKEN": "x",+ "JWT_SECRET_KEY": "x",+ "GATEWAY_ADMIN_EMAIL": "[email protected]",+ "GATEWAY_ADMIN_PASSWORD": "x",+}+++def env(monkeypatch: pytest.MonkeyPatch) -> pytest.MonkeyPatch:+ for key, value in _REQUIRED.items():+ monkeypatch.setenv(key, value)+ monkeypatch.delenv("ID_SERVER_NAME", raising=False)+ monkeypatch.delenv("MATRIX_SERVER_NAME", raising=False)+ return monkeypatch+++def test_reads_the_new_name(env: pytest.MonkeyPatch) -> None:+ env.setenv("ID_SERVER_NAME", "switch.example")+ assert SwitchConfig(_env_file=None).id_server_name == "switch.example" # type: ignore[call-arg]+ assert deprecated_env_names() == []+++def test_still_reads_the_old_name_and_says_so(env: pytest.MonkeyPatch) -> None:+ env.setenv("MATRIX_SERVER_NAME", "legacy.example")+ assert SwitchConfig(_env_file=None).id_server_name == "legacy.example" # type: ignore[call-arg]+ assert len(deprecated_env_names()) == 1+++def test_the_new_name_wins_when_both_are_set(env: pytest.MonkeyPatch) -> None:+ env.setenv("ID_SERVER_NAME", "new.example")+ env.setenv("MATRIX_SERVER_NAME", "old.example")+ assert SwitchConfig(_env_file=None).id_server_name == "new.example" # type: ignore[call-arg]+ assert deprecated_env_names() == []diff --git a/core/tests/switch_core/test_config_max_workspaces.py b/core/tests/switch_core/test_config_max_workspaces.pyindex d1362908f..5742d9e58 100644--- a/core/tests/switch_core/test_config_max_workspaces.py+++ b/core/tests/switch_core/test_config_max_workspaces.py@@ -7,7 +7,7 @@ _BASE_KWARGS = dict(db_port="5432",db_user="postgres",db_name="switch",- matrix_server_name="switch.local",+ id_server_name="switch.local",agent_registration_token="token",jwt_secret_key="jwt",gateway_admin_email="[email protected]",diff --git a/core/tests/switch_core/test_config_slack_app.py b/core/tests/switch_core/test_config_slack_app.pyindex 603bd1f45..4711d31f9 100644--- a/core/tests/switch_core/test_config_slack_app.py+++ b/core/tests/switch_core/test_config_slack_app.py@@ -18,7 +18,7 @@ _BASE_KWARGS = dict(db_user="postgres",db_password="pw",db_name="switch",- matrix_server_name="switch.local",+ id_server_name="switch.local",agent_registration_token="token",jwt_secret_key="jwt",gateway_admin_email="[email protected]",diff --git a/core/tests/switch_core/test_config_smtp.py b/core/tests/switch_core/test_config_smtp.pyindex 5494f7480..a96793960 100644--- a/core/tests/switch_core/test_config_smtp.py+++ b/core/tests/switch_core/test_config_smtp.py@@ -8,7 +8,7 @@ _BASE_KWARGS = dict(db_user="postgres",db_password="pw",db_name="switch",- matrix_server_name="switch.local",+ id_server_name="switch.local",agent_registration_token="token",jwt_secret_key="jwt",gateway_admin_email="[email protected]",diff --git a/core/tests/switch_core/test_config_standalone_compose.py b/core/tests/switch_core/test_config_standalone_compose.pyindex e86cfbfa8..9ab2a1bd5 100644--- a/core/tests/switch_core/test_config_standalone_compose.py+++ b/core/tests/switch_core/test_config_standalone_compose.py@@ -26,7 +26,7 @@ _BASE_KWARGS = dict(db_user="postgres",db_password="pw",db_name="switch",- matrix_server_name="switch.local",+ id_server_name="switch.local",agent_registration_token="token",jwt_secret_key="jwt",gateway_admin_email="[email protected]",diff --git a/core/tests/switch_core/test_db_idle_in_transaction_timeout.py b/core/tests/switch_core/test_db_idle_in_transaction_timeout.pyindex 568d8f242..bc25fe24b 100644--- a/core/tests/switch_core/test_db_idle_in_transaction_timeout.py+++ b/core/tests/switch_core/test_db_idle_in_transaction_timeout.py@@ -19,7 +19,7 @@ _BASE_KWARGS = dict(db_user="postgres",db_password="pw",db_name="switch",- matrix_server_name="switch.local",+ id_server_name="switch.local",agent_registration_token="token",jwt_secret_key="jwt",gateway_admin_email="[email protected]",diff --git a/core/tests/switch_core/test_db_migration_lock_timeout.py b/core/tests/switch_core/test_db_migration_lock_timeout.pyindex 83a8d0e93..7abd5ec56 100644--- a/core/tests/switch_core/test_db_migration_lock_timeout.py+++ b/core/tests/switch_core/test_db_migration_lock_timeout.py@@ -22,7 +22,7 @@ _BASE_KWARGS = dict(db_user="postgres",db_password="pw",db_name="switch",- matrix_server_name="switch.local",+ id_server_name="switch.local",agent_registration_token="token",jwt_secret_key="jwt",gateway_admin_email="[email protected]",diff --git a/core/tests/switch_core/test_dm_rooms.py b/core/tests/switch_core/test_dm_rooms.pyindex 619861ee6..d130d88c5 100644--- a/core/tests/switch_core/test_dm_rooms.py+++ b/core/tests/switch_core/test_dm_rooms.py@@ -5,7 +5,7 @@ from typing import Anyimport pytest-from switch_core.bridges.collaboration.adapter import CollaborationAdapter+from switch_core.bridges.collaboration.adapter import PlatformAdapterfrom switch_core.bridges.collaboration.models import ChannelCreationUnsupportedfrom switch_core.room_service import RoomCreateConfig, RoomService@@ -170,7 +170,7 @@ async def test_base_adapter_rejects_dm_channel_creation() -> None:with pytest.raises(ChannelCreationUnsupported, match="Mattermost cannot create DM channels"):- await CollaborationAdapter.create_dm_channel(+ await PlatformAdapter.create_dm_channel(SimpleNamespace(platform_name="Mattermost"),agent_name="a",user_name="u",diff --git a/core/tests/switch_core/test_logging_config.py b/core/tests/switch_core/test_logging_config.pyindex 9f01440ec..eacdad6b9 100644--- a/core/tests/switch_core/test_logging_config.py+++ b/core/tests/switch_core/test_logging_config.py@@ -251,22 +251,25 @@ def test_filter_stamps_every_field(monkeypatch: pytest.MonkeyPatch) -> None:record = logging.LogRecord("x", logging.INFO, __file__, 1, "m", args=(), exc_info=None)+ fields = {name: f"{name}-value" for name in CONTEXT_FIELDS if name != "tenant_id"}- with log_context(- request_id="r",- agent_id="a",- user_id="u",- console_id="c",- console_name="alice@laptop",- ):+ with log_context(**fields):LogContextFilter("acme").filter(record)assert record.tenant_id == "acme"- assert record.request_id == "r"- assert record.agent_id == "a"- assert record.user_id == "u"- assert record.console_id == "c"- assert record.console_name == "alice@laptop"+ for name, value in fields.items():+ assert getattr(record, name) == value, name+++def test_the_bridge_side_reaches_a_json_line(json_lines) -> None:+ logger, lines = json_lines++ with log_context(bridge="collaboration", platform="slack"):+ logger.info("[BRIDGE-IN] message")++ entry = _one(lines)+ assert entry["bridge"] == "collaboration"+ assert entry["platform"] == "slack"def test_the_console_rides_alongside_the_user_in_json(json_lines) -> None:diff --git a/core/tests/switch_core/test_main.py b/core/tests/switch_core/test_main.pyindex 58baf3e19..8890bffd0 100644--- a/core/tests/switch_core/test_main.py+++ b/core/tests/switch_core/test_main.py@@ -60,7 +60,7 @@ def _config(token: str, *, admin_email: str = ADMIN_EMAIL) -> SwitchConfig:db_user="unused",db_password="unused",db_name="unused",- matrix_server_name="test",+ id_server_name="test",agent_registration_token=token,jwt_secret_key="test-jwt-secret",gateway_admin_email=admin_email,@@ -83,7 +83,7 @@ def _config_for(postgres_url: str) -> SwitchConfig:db_user=url.username,db_password=url.password,db_name=url.database,- matrix_server_name="test",+ id_server_name="test",agent_registration_token="unused",jwt_secret_key="test-jwt-secret",gateway_admin_email=ADMIN_EMAIL,@@ -113,7 +113,9 @@ async def _make_agent_owned_by(session_factory: async_sessionmaker[AsyncSession], *, owner_id: str, name: str) -> None:async with session_factory() as session:- client = Client(matrix_user_id=f"@{name}:test", display_name=name, type="agent")+ client = Client(+ transport_user_id=f"@{name}:test", display_name=name, type="agent"+ )session.add(client)await session.flush()key = ApiKey(diff --git a/core/tests/switch_core/test_room_service_add_users.py b/core/tests/switch_core/test_room_service_add_users.pyindex 7c7fc4790..e83e95a37 100644--- a/core/tests/switch_core/test_room_service_add_users.py+++ b/core/tests/switch_core/test_room_service_add_users.py@@ -30,7 +30,7 @@ class _FakeAdapter:return [i for i in user_external_ids if i in self._failing_ids]-class _FakeBridgeCore:+class _FakeCollaborationCore:def __init__(self, *, known: dict[str, str], failing_ids: list[str]) -> None:self._known = knownself.adapter = _FakeAdapter(failing_ids=failing_ids)@@ -43,8 +43,8 @@ class _FakeBridgeCore:async def _add(*, known: dict[str, str], failing_ids: list[str], asked_for: list[str]-) -> tuple[list[dict[str, Any]], _FakeBridgeCore]:- bridge = _FakeBridgeCore(known=known, failing_ids=failing_ids)+) -> tuple[list[dict[str, Any]], _FakeCollaborationCore]:+ bridge = _FakeCollaborationCore(known=known, failing_ids=failing_ids)failures = await RoomService._add_users_to_channel(bridge, # type: ignore[arg-type]"chan-1",@@ -115,7 +115,7 @@ async def test_both_kinds_of_miss_are_reported_together() -> None:async def test_an_unmappable_failure_id_still_gets_reported() -> None:# An adapter returning something we did not hand it is a bug, but losing# the failure entirely would be worse than reporting it raw.- bridge = _FakeBridgeCore(known={"alice": "ext-a"}, failing_ids=[])+ bridge = _FakeCollaborationCore(known={"alice": "ext-a"}, failing_ids=[])async def _add_users(channel_id: str, user_names: list[str], user_external_ids: list[str]diff --git a/core/tests/switch_core/test_room_service_change_bridge.py b/core/tests/switch_core/test_room_service_change_bridge.pyindex f2733f8c9..d4f941ab8 100644--- a/core/tests/switch_core/test_room_service_change_bridge.py+++ b/core/tests/switch_core/test_room_service_change_bridge.py@@ -94,28 +94,28 @@ class _FakeAdapter:self._events.append(("ensure_capture", list(channels)))-class _FakeBridgeCore:+class _FakeCollaborationCore:def __init__(self,events: list[Any],*,- matrix_user_id: str,+ transport_user_id: str,new_channel_id: str = "",) -> None:self._events = events- self._bridge_client_matrix_user_id = matrix_user_id+ self._workspace_consumer_transport_user_id = transport_user_idself.adapter = _FakeAdapter(events, new_channel_id)def add_room_mapping(self,room_id: str,- matrix_room_id: str,+ transport_room_id: str,external_channel_id: str,tenant_id: str,) -> None:self._events.append(("add_room_mapping", room_id, external_channel_id))- def remove_room_mapping(self, room_id: str, matrix_room_id: str) -> None:+ def remove_room_mapping(self, room_id: str, transport_room_id: str) -> None:self._events.append(("remove_room_mapping", room_id))def begin_provisioning(self, external_channel_id: str) -> None:@@ -133,15 +133,17 @@ class _FakeLifecycle:return self._bridges.get(bridge_id)-class _FakeMatrix:+class _FakeProvisioning:def __init__(self, events: list[Any]) -> None:self._events = events- async def invite_to_room(self, matrix_room_id: str, matrix_user_id: str) -> None:- self._events.append(("invite", matrix_user_id))+ async def invite_to_room(+ self, transport_room_id: str, transport_user_id: str+ ) -> None:+ self._events.append(("invite", transport_user_id))- async def kick_user(self, matrix_room_id: str, matrix_user_id: str) -> None:- self._events.append(("kick", matrix_user_id))+ async def kick_user(self, transport_room_id: str, transport_user_id: str) -> None:+ self._events.append(("kick", transport_user_id))class _FakeBridgeStore:@@ -176,7 +178,7 @@ def _build_service(svc._room_store = room_store # type: ignore[assignment]svc._agent_store = _FakeAgentStore(agent_names) # type: ignore[assignment]svc._collab_lifecycle = _FakeLifecycle(bridges) # type: ignore[assignment]- svc._matrix_admin = _FakeMatrix(events) # type: ignore[assignment]+ svc._provisioning = _FakeProvisioning(events) # type: ignore[assignment]svc._collab_bridge_store = _FakeBridgeStore( # type: ignore[assignment]channel_creation_enabled=channel_creation_enabled)@@ -191,15 +193,17 @@ class TestChangeBridge:tenant_id="room-tenant",name="Work",description="A room",- matrix_room_id="!mx:switch.local",+ transport_room_id="!mx:switch.local",bridge_id="bridge-old",channel_type="channel_public",external_channel_id="chan-old",)- new_bridge = _FakeBridgeCore(- events, matrix_user_id="@bot-new:switch.local", new_channel_id="chan-new"+ new_bridge = _FakeCollaborationCore(+ events, transport_user_id="@bot-new:switch.local", new_channel_id="chan-new"+ )+ old_bridge = _FakeCollaborationCore(+ events, transport_user_id="@bot-old:switch.local")- old_bridge = _FakeBridgeCore(events, matrix_user_id="@bot-old:switch.local")svc, room_store = _build_service(room=room,agent_ids=["a1", "a2"],@@ -248,15 +252,17 @@ class TestChangeBridge:tenant_id="room-tenant",name="Secret",description="d",- matrix_room_id="!mx:switch.local",+ transport_room_id="!mx:switch.local",bridge_id="bridge-old",channel_type="channel_private",external_channel_id="chan-old",)- new_bridge = _FakeBridgeCore(- events, matrix_user_id="@bot-new:switch.local", new_channel_id="chan-new"+ new_bridge = _FakeCollaborationCore(+ events, transport_user_id="@bot-new:switch.local", new_channel_id="chan-new"+ )+ old_bridge = _FakeCollaborationCore(+ events, transport_user_id="@bot-old:switch.local")- old_bridge = _FakeBridgeCore(events, matrix_user_id="@bot-old:switch.local")svc, room_store = _build_service(room=room,agent_ids=[],@@ -277,13 +283,13 @@ class TestChangeBridge:tenant_id="room-tenant",name="Internal",description="d",- matrix_room_id="!mx:switch.local",+ transport_room_id="!mx:switch.local",bridge_id=None,channel_type=None,external_channel_id=None,)- new_bridge = _FakeBridgeCore(- events, matrix_user_id="@bot-new:switch.local", new_channel_id="chan-new"+ new_bridge = _FakeCollaborationCore(+ events, transport_user_id="@bot-new:switch.local", new_channel_id="chan-new")svc, _ = _build_service(room=room,@@ -308,15 +314,17 @@ class TestChangeBridge:tenant_id="room-tenant",name="Work",description="A room",- matrix_room_id="!mx:switch.local",+ transport_room_id="!mx:switch.local",bridge_id="bridge-old",channel_type="channel_public",external_channel_id="chan-old",)- new_bridge = _FakeBridgeCore(- events, matrix_user_id="@bot-new:switch.local", new_channel_id="chan-new"+ new_bridge = _FakeCollaborationCore(+ events, transport_user_id="@bot-new:switch.local", new_channel_id="chan-new"+ )+ old_bridge = _FakeCollaborationCore(+ events, transport_user_id="@bot-old:switch.local")- old_bridge = _FakeBridgeCore(events, matrix_user_id="@bot-old:switch.local")svc, room_store = _build_service(room=room,agent_ids=["a1"],@@ -353,14 +361,18 @@ class TestChangeBridge:tenant_id="room-tenant",name="Work",description="A room",- matrix_room_id="!mx:switch.local",+ transport_room_id="!mx:switch.local",bridge_id="bridge-old",channel_type="channel_public",external_channel_id="chan-old",)- new_bridge = _FakeBridgeCore(events, matrix_user_id="@bot-new:switch.local")+ new_bridge = _FakeCollaborationCore(+ events, transport_user_id="@bot-new:switch.local"+ )new_bridge.adapter.not_bindable.add("chan-elsewhere")- old_bridge = _FakeBridgeCore(events, matrix_user_id="@bot-old:switch.local")+ old_bridge = _FakeCollaborationCore(+ events, transport_user_id="@bot-old:switch.local"+ )svc, room_store = _build_service(room=room,agent_ids=["a1"],@@ -389,13 +401,13 @@ class TestChangeBridge:tenant_id="room-tenant",name="Work",description="d",- matrix_room_id="!mx:switch.local",+ transport_room_id="!mx:switch.local",bridge_id=None,channel_type=None,external_channel_id=None,)- new_bridge = _FakeBridgeCore(- events, matrix_user_id="@bot-new:switch.local", new_channel_id="chan-new"+ new_bridge = _FakeCollaborationCore(+ events, transport_user_id="@bot-new:switch.local", new_channel_id="chan-new")svc, _ = _build_service(room=room,@@ -416,7 +428,7 @@ class TestChangeBridge:tenant_id="room-tenant",name="Work",description="d",- matrix_room_id="!mx:switch.local",+ transport_room_id="!mx:switch.local",bridge_id="bridge-old",channel_type="channel_public",external_channel_id="chan-old",@@ -439,7 +451,7 @@ class TestChangeBridge:tenant_id="room-tenant",name="Work",description="d",- matrix_room_id="!mx:switch.local",+ transport_room_id="!mx:switch.local",bridge_id="bridge-x",channel_type="channel_public",external_channel_id="chan-x",@@ -448,7 +460,9 @@ class TestChangeBridge:room=room,agent_ids=[],agent_names={},- bridges={"bridge-x": _FakeBridgeCore(events, matrix_user_id="@b:s")},+ bridges={+ "bridge-x": _FakeCollaborationCore(events, transport_user_id="@b:s")+ },events=events,)@@ -465,13 +479,13 @@ class TestChangeBridge:tenant_id="room-tenant",name="Work",description="d",- matrix_room_id="!mx:switch.local",+ transport_room_id="!mx:switch.local",bridge_id="bridge-old",channel_type="channel_public",external_channel_id="chan-old",)- new_bridge = _FakeBridgeCore(- events, matrix_user_id="@bot-new:switch.local", new_channel_id="chan-new"+ new_bridge = _FakeCollaborationCore(+ events, transport_user_id="@bot-new:switch.local", new_channel_id="chan-new")svc, room_store = _build_service(room=room,@@ -479,7 +493,9 @@ class TestChangeBridge:agent_names={},bridges={"bridge-new": new_bridge,- "bridge-old": _FakeBridgeCore(events, matrix_user_id="@bot-old:s"),+ "bridge-old": _FakeCollaborationCore(+ events, transport_user_id="@bot-old:s"+ ),},events=events,channel_creation_enabled=False,@@ -504,7 +520,7 @@ class TestLinkBridgeToRoom:tenant_id="room-tenant",name="Work",description="d",- matrix_room_id="!mx:switch.local",+ transport_room_id="!mx:switch.local",bridge_id=None,channel_type=None,external_channel_id=None,@@ -512,7 +528,7 @@ class TestLinkBridgeToRoom:async def test_binding_an_existing_channel_establishes_capture(self) -> None:events: list[Any] = []- bridge = _FakeBridgeCore(events, matrix_user_id="@bot:switch.local")+ bridge = _FakeCollaborationCore(events, transport_user_id="@bot:switch.local")svc, room_store = _build_service(room=self._room(),agent_ids=[],@@ -538,7 +554,7 @@ class TestLinkBridgeToRoom:# Capture must not be established before the room↔channel mapping is# registered: a notification arriving in the gap has nowhere to land.events: list[Any] = []- bridge = _FakeBridgeCore(events, matrix_user_id="@bot:switch.local")+ bridge = _FakeCollaborationCore(events, transport_user_id="@bot:switch.local")svc, _ = _build_service(room=self._room(),agent_ids=[],diff --git a/core/tests/switch_core/test_room_service_channel_binding.py b/core/tests/switch_core/test_room_service_channel_binding.pyindex 14a8872ef..531e7eb8f 100644--- a/core/tests/switch_core/test_room_service_channel_binding.py+++ b/core/tests/switch_core/test_room_service_channel_binding.py@@ -20,7 +20,7 @@ from switch_core.bridges.collaboration.adapter import ChannelNotBindablefrom switch_core.room_service import RoomCreateConfigfrom tests.switch_core.test_room_service_change_bridge import (_build_service,- _FakeBridgeCore,+ _FakeCollaborationCore,)@@ -28,8 +28,8 @@ class _Reached(Exception):"""Raised by the first step after the check, to show it was passed."""-def _service(events: list[Any]) -> tuple[Any, _FakeBridgeCore]:- bridge = _FakeBridgeCore(events, matrix_user_id="@bot:switch.local")+def _service(events: list[Any]) -> tuple[Any, _FakeCollaborationCore]:+ bridge = _FakeCollaborationCore(events, transport_user_id="@bot:switch.local")bridge.adapter.not_bindable.add("chan-elsewhere")svc, _ = _build_service(room=SimpleNamespace(),@@ -42,7 +42,7 @@ def _service(events: list[Any]) -> tuple[Any, _FakeBridgeCore]:async def create_matrix_room(*_: Any, **__: Any) -> str:raise _Reached- svc._matrix_admin.create_room = create_matrix_room+ svc._provisioning.create_room = create_matrix_roomreturn svc, bridgediff --git a/core/tests/switch_core/test_room_service_default_bridge_multi_tenant.py b/core/tests/switch_core/test_room_service_default_bridge_multi_tenant.pyindex b08381252..dd1fb393f 100644--- a/core/tests/switch_core/test_room_service_default_bridge_multi_tenant.py+++ b/core/tests/switch_core/test_room_service_default_bridge_multi_tenant.py@@ -41,7 +41,7 @@ from switch_core.tenant_context import tenant_scopepytestmark = pytest.mark.no_ambient_tenant-class _FakeMatrix:+class _FakeProvisioning:"""Provisioning, which room_service calls with no session open."""def __init__(self) -> None:@@ -73,12 +73,12 @@ class _FakeAdapter:return None-class _FakeBridgeCore:+class _FakeCollaborationCore:"""The running half of a bridge — `create_room` never opens a session on- this, so it does not need to be the real `BridgeCore`."""+ this, so it does not need to be the real `CollaborationCore`."""- def __init__(self, matrix_user_id: str) -> None:- self._bridge_client_matrix_user_id = matrix_user_id+ def __init__(self, transport_user_id: str) -> None:+ self._workspace_consumer_transport_user_id = transport_user_idself.adapter = _FakeAdapter()self.mappings: list[tuple[str, str, str, str]] = []@@ -91,15 +91,17 @@ class _FakeBridgeCore:def add_room_mapping(self,room_id: str,- matrix_room_id: str,+ transport_room_id: str,external_channel_id: str,tenant_id: str,) -> None:- self.mappings.append((room_id, matrix_room_id, external_channel_id, tenant_id))+ self.mappings.append(+ (room_id, transport_room_id, external_channel_id, tenant_id)+ )class _FakeLifecycle:- def __init__(self, bridges: dict[str, _FakeBridgeCore]) -> None:+ def __init__(self, bridges: dict[str, _FakeCollaborationCore]) -> None:self._bridges = bridgesdef get(self, bridge_id: str) -> Any:@@ -134,7 +136,7 @@ async def _make_default_bridge("""async with tenant_session(session_factory, tenant_id) as session:client = Client(- matrix_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:switch.local",+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:switch.local",display_name="bridge client",type="bridge",)@@ -156,8 +158,8 @@ async def _make_default_bridge(def _service(session_factory: async_sessionmaker[AsyncSession],*,- bridges: dict[str, _FakeBridgeCore],- matrix: _FakeMatrix,+ bridges: dict[str, _FakeCollaborationCore],+ provisioning: _FakeProvisioning,) -> RoomService:svc = object.__new__(RoomService)svc._session_factory = session_factory # type: ignore[assignment]@@ -166,7 +168,7 @@ def _service(svc._client_lifecycle = _NoRunningClients() # type: ignore[assignment]svc._collab_lifecycle = _FakeLifecycle(bridges) # type: ignore[assignment]svc._collab_bridge_store = CollaborationBridgeStore() # type: ignore[assignment]- svc._matrix_admin = matrix # type: ignore[assignment]+ svc._provisioning = provisioning # type: ignore[assignment]return svc@@ -188,14 +190,14 @@ async def test_create_room_succeeds_for_each_tenants_own_default_bridge(bridge_a = await _make_default_bridge(session_factory, tenant_id=tenant_a)bridge_b = await _make_default_bridge(session_factory, tenant_id=tenant_b)- matrix = _FakeMatrix()+ provisioning = _FakeProvisioning()svc = _service(session_factory,bridges={- bridge_a: _FakeBridgeCore("@bot-a:switch.local"),- bridge_b: _FakeBridgeCore("@bot-b:switch.local"),+ bridge_a: _FakeCollaborationCore("@bot-a:switch.local"),+ bridge_b: _FakeCollaborationCore("@bot-b:switch.local"),},- matrix=matrix,+ provisioning=provisioning,)# Before the fix this raised MultipleResultsFound out ofdiff --git a/core/tests/switch_core/test_room_service_delete_room.py b/core/tests/switch_core/test_room_service_delete_room.pyindex 87e6d94dc..7c8a02674 100644--- a/core/tests/switch_core/test_room_service_delete_room.py+++ b/core/tests/switch_core/test_room_service_delete_room.py@@ -35,12 +35,12 @@ class _FakeRoomStore:self.deleted.append(room_id)-class _FakeBridgeCore:+class _FakeCollaborationCore:def __init__(self, events: list[Any]) -> None:self._events = events- def remove_room_mapping(self, room_id: str, matrix_room_id: str) -> None:- self._events.append(("remove_room_mapping", room_id, matrix_room_id))+ def remove_room_mapping(self, room_id: str, transport_room_id: str) -> None:+ self._events.append(("remove_room_mapping", room_id, transport_room_id))class _FakeLifecycle:@@ -59,15 +59,15 @@ class _FakeClientLifecycle:return self._clients.get(client_id)-class _FakeMatrix:+class _FakeProvisioning:def __init__(self, events: list[Any]) -> None:self._events = events- async def kick_user(self, matrix_room_id: str, matrix_user_id: str) -> None:- self._events.append(("kick", matrix_user_id))+ async def kick_user(self, transport_room_id: str, transport_user_id: str) -> None:+ self._events.append(("kick", transport_user_id))- async def delete_room(self, matrix_room_id: str) -> None:- self._events.append(("delete_room", matrix_room_id))+ async def delete_room(self, transport_room_id: str) -> None:+ self._events.append(("delete_room", transport_room_id))def _build_service(@@ -84,21 +84,21 @@ def _build_service(svc._room_store = room_store # type: ignore[assignment]svc._collab_lifecycle = _FakeLifecycle(bridges) # type: ignore[assignment]svc._client_lifecycle = _FakeClientLifecycle(clients) # type: ignore[assignment]- svc._matrix_admin = _FakeMatrix(events) # type: ignore[assignment]+ svc._provisioning = _FakeProvisioning(events) # type: ignore[assignment]return svc, room_storeclass TestDeleteRoom:- async def test_evicts_bridged_room_from_bridge_core(self) -> None:+ async def test_evicts_bridged_room_from_collaboration_core(self) -> None:events: list[Any] = []room = SimpleNamespace(id="room-1",tenant_id="room-tenant",- matrix_room_id="!mx:switch.local",+ transport_room_id="!mx:switch.local",bridge_id="bridge-x",external_channel_id="chan-x",)- bridge = _FakeBridgeCore(events)+ bridge = _FakeCollaborationCore(events)svc, room_store = _build_service(room=room,client_ids=[],@@ -113,12 +113,12 @@ class TestDeleteRoom:assert ("delete_room", "!mx:switch.local") in eventsassert ("remove_room_mapping", "room-1", "!mx:switch.local") in events- async def test_non_bridged_room_does_not_touch_bridge_core(self) -> None:+ async def test_non_bridged_room_does_not_touch_collaboration_core(self) -> None:events: list[Any] = []room = SimpleNamespace(id="room-1",tenant_id="room-tenant",- matrix_room_id="!mx:switch.local",+ transport_room_id="!mx:switch.local",bridge_id=None,external_channel_id=None,)@@ -135,12 +135,12 @@ class TestDeleteRoom:assert room_store.deleted == ["room-1"]assert not any(e[0] == "remove_room_mapping" for e in events)- async def test_missing_bridge_core_is_tolerated(self) -> None:+ async def test_missing_collaboration_core_is_tolerated(self) -> None:events: list[Any] = []room = SimpleNamespace(id="room-1",tenant_id="room-tenant",- matrix_room_id="!mx:switch.local",+ transport_room_id="!mx:switch.local",bridge_id="bridge-gone",external_channel_id="chan-x",)@@ -162,13 +162,13 @@ class TestDeleteRoom:room = SimpleNamespace(id="room-1",tenant_id="room-tenant",- matrix_room_id="!mx:switch.local",+ transport_room_id="!mx:switch.local",bridge_id=None,external_channel_id=None,)clients = {- "c1": SimpleNamespace(matrix_user_id="@a:switch.local"),- "c2": SimpleNamespace(matrix_user_id="@b:switch.local"),+ "c1": SimpleNamespace(transport_user_id="@a:switch.local"),+ "c2": SimpleNamespace(transport_user_id="@b:switch.local"),}svc, _ = _build_service(room=room,diff --git a/core/tests/switch_core/test_room_service_foreign_bridge.py b/core/tests/switch_core/test_room_service_foreign_bridge.pyindex 853e33f25..fe6b88a59 100644--- a/core/tests/switch_core/test_room_service_foreign_bridge.py+++ b/core/tests/switch_core/test_room_service_foreign_bridge.py@@ -33,7 +33,7 @@ from tests.conftest import RLSHarnesspytestmark = pytest.mark.no_ambient_tenant-class _FakeMatrix:+class _FakeProvisioning:def __init__(self) -> None:self._n = 0@@ -77,11 +77,11 @@ class _RecordingAdapter:self._calls.append("ensure_channel_subscriptions")-class _RecordingBridgeCore:+class _RecordingCollaborationCore:def __init__(self, tenant_id: str) -> None:self.calls: list[str] = []self.tenant_id = tenant_id- self._bridge_client_matrix_user_id = "@bot:switch.local"+ self._workspace_consumer_transport_user_id = "@bot:switch.local"self.adapter = _RecordingAdapter(self.calls)async def resolve_external_user_id_map(self, names: list[str]) -> dict[str, str]:@@ -102,7 +102,7 @@ class _RecordingBridgeCore:class _FakeLifecycle:- def __init__(self, bridges: dict[str, _RecordingBridgeCore]) -> None:+ def __init__(self, bridges: dict[str, _RecordingCollaborationCore]) -> None:self._bridges = bridgesdef get(self, bridge_id: str) -> Any:@@ -133,7 +133,7 @@ async def _make_bridge() -> str:async with tenant_session(session_factory, tenant_id) as session:client = Client(- matrix_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:switch.local",+ transport_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:switch.local",display_name="bridge client",type="bridge",)@@ -154,7 +154,7 @@ async def _make_bridge(def _service(session_factory: async_sessionmaker[AsyncSession],- bridges: dict[str, _RecordingBridgeCore],+ bridges: dict[str, _RecordingCollaborationCore],) -> RoomService:svc = object.__new__(RoomService)svc._session_factory = session_factory # type: ignore[assignment]@@ -163,20 +163,20 @@ def _service(svc._client_lifecycle = _NoRunningClients() # type: ignore[assignment]svc._collab_lifecycle = _FakeLifecycle(bridges) # type: ignore[assignment]svc._collab_bridge_store = CollaborationBridgeStore() # type: ignore[assignment]- svc._matrix_admin = _FakeMatrix() # type: ignore[assignment]+ svc._provisioning = _FakeProvisioning() # type: ignore[assignment]return svc@pytest.fixtureasync def setup(rls_harness: RLSHarness,-) -> tuple[RoomService, str, str, _RecordingBridgeCore]:+) -> tuple[RoomService, str, str, _RecordingCollaborationCore]:"""Tenant A owns a running bridge; returns a service, tenant B, A's bridgeid, and A's bridge so a test can check nothing ran on it."""tenant_a = await _make_tenant(rls_harness.owner)tenant_b = await _make_tenant(rls_harness.owner)bridge_a = await _make_bridge(rls_harness.owner, tenant_id=tenant_a)- core_a = _RecordingBridgeCore(tenant_a)+ core_a = _RecordingCollaborationCore(tenant_a)svc = _service(rls_harness.restricted, {bridge_a: core_a})return svc, tenant_b, bridge_a, core_adiff --git a/core/tests/switch_core/test_room_service_pool_holds.py b/core/tests/switch_core/test_room_service_pool_holds.pyindex 8b46e1f43..4275d80b3 100644--- a/core/tests/switch_core/test_room_service_pool_holds.py+++ b/core/tests/switch_core/test_room_service_pool_holds.py@@ -54,21 +54,23 @@ class _TrackedSession:return await self._inner.__aexit__(*exc) # type: ignore[no-any-return]-class _RecordingMatrix:+class _RecordingProvisioning:"""Records each Matrix call together with the sessions open at the time."""def __init__(self, tracker: _TrackingSessionFactory) -> None:self._tracker = trackerself.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 invite_to_room(+ self, transport_room_id: str, transport_user_id: str+ ) -> None:+ self.calls.append(("invite", transport_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 kick_user(self, transport_room_id: str, transport_user_id: str) -> None:+ self.calls.append(("kick", transport_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))+ async def delete_room(self, transport_room_id: str) -> None:+ self.calls.append(("delete_room", transport_room_id, self._tracker.live))class _RunningClients:@@ -87,9 +89,9 @@ class _RunningClients:class _RunningClient:- def __init__(self, client_id: str, matrix_user_id: str) -> None:+ def __init__(self, client_id: str, transport_user_id: str) -> None:self.client_id = client_id- self.matrix_user_id = matrix_user_id+ self.transport_user_id = transport_user_idasync def _seed(@@ -111,7 +113,7 @@ async def _seed(type="agent",)client = Client(- matrix_user_id=f"@a{i}:test",+ transport_user_id=f"@a{i}:test",display_name=f"a{i}",type="agent",)@@ -130,8 +132,8 @@ async def _seed(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")+ running[agent.id] = _RunningClient(client.id, client.transport_user_id)+ room = Room(transport_room_id="!r:test", name="room", description="d")session.add(room)await session.flush()await session.commit()@@ -140,16 +142,16 @@ async def _seed(def _service(tracker: _TrackingSessionFactory, running: dict[str, Any]-) -> tuple[RoomService, _RecordingMatrix]:- matrix = _RecordingMatrix(tracker)+) -> tuple[RoomService, _RecordingProvisioning]:+ provisioning = _RecordingProvisioning(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._provisioning = provisioning # type: ignore[assignment]svc._client_lifecycle = _RunningClients(running) # type: ignore[assignment]svc._collab_lifecycle = _RunningClients({}) # type: ignore[assignment]- return svc, matrix+ return svc, provisioningclass TestAddAgentsToRoom:@@ -158,12 +160,12 @@ class TestAddAgentsToRoom:) -> None:room_id, agent_ids, running = await _seed(session_factory, agents=3)tracker = _TrackingSessionFactory(session_factory)- svc, matrix = _service(tracker, running)+ svc, provisioning = _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]+ assert len(provisioning.calls) == 3+ assert [live for _kind, _who, live in provisioning.calls] == [0, 0, 0]async def test_membership_is_recorded_before_the_invite(self, session_factory: async_sessionmaker[AsyncSession]@@ -173,14 +175,14 @@ class TestAddAgentsToRoom:# 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)+ svc, provisioning = _service(tracker, running)seen_at_invite: list[list[str]] = []- async def _invite(matrix_room_id: str, matrix_user_id: str) -> None:+ async def _invite(transport_room_id: str, transport_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]+ provisioning.invite_to_room = _invite # type: ignore[method-assign]await svc.add_agents_to_room(room_id, agent_ids=agent_ids)@@ -194,16 +196,16 @@ class TestAddAgentsToRoom:# 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)+ svc, provisioning = _service(tracker, running)seen_at_invite: list[list[str]] = []- async def _invite(matrix_room_id: str, matrix_user_id: str) -> None:+ async def _invite(transport_room_id: str, transport_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]+ provisioning.invite_to_room = _invite # type: ignore[method-assign]await svc.add_agents_to_room(room_id, agent_ids=agent_ids)@@ -213,17 +215,17 @@ class TestAddAgentsToRoom:running[agent_ids[0]].client_id]- async def test_a_missing_room_still_raises_before_any_matrix_call(+ async def test_a_missing_room_still_raises_before_any_provisioning_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)+ svc, provisioning = _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 == []+ assert provisioning.calls == []class TestRemoveAgentsFromRoom:@@ -232,14 +234,14 @@ class TestRemoveAgentsFromRoom:) -> None:room_id, agent_ids, running = await _seed(session_factory, agents=3)tracker = _TrackingSessionFactory(session_factory)- svc, matrix = _service(tracker, running)+ svc, provisioning = _service(tracker, running)await svc.add_agents_to_room(room_id, agent_ids=agent_ids)- matrix.calls.clear()+ provisioning.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]+ assert [kind for kind, _who, _live in provisioning.calls] == ["kick"] * 3+ assert [live for _kind, _who, live in provisioning.calls] == [0, 0, 0]async def test_the_rows_are_gone_before_the_kick_lands(self, session_factory: async_sessionmaker[AsyncSession]@@ -263,15 +265,15 @@ class TestRemoveAgentsFromRoom:"""room_id, agent_ids, running = await _seed(session_factory, agents=1)tracker = _TrackingSessionFactory(session_factory)- svc, matrix = _service(tracker, running)+ svc, provisioning = _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 def _kick(transport_room_id: str, transport_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]+ provisioning.kick_user = _kick # type: ignore[method-assign]await svc.remove_agents_from_room(room_id, agent_ids)@@ -303,7 +305,7 @@ class TestRemoveAgentsFromRoom:"""room_id, agent_ids, running = await _seed(session_factory, agents=2)tracker = _TrackingSessionFactory(session_factory)- svc, matrix = _service(tracker, running)+ svc, provisioning = _service(tracker, running)await svc.add_agents_to_room(room_id, agent_ids=agent_ids)# Every state the rows are seen in, sampled from a separate connection@@ -316,10 +318,10 @@ class TestRemoveAgentsFromRoom:clients = await RoomStore().get_client_ids(probe, room_id)seen.append((len(agents), len(clients)))- async def _kick(matrix_room_id: str, matrix_user_id: str) -> None:+ async def _kick(transport_room_id: str, transport_user_id: str) -> None:await _sample()- matrix.kick_user = _kick # type: ignore[method-assign]+ provisioning.kick_user = _kick # type: ignore[method-assign]await svc.remove_agents_from_room(room_id, agent_ids)await _sample()@@ -336,18 +338,18 @@ class TestDeleteRoom:) -> None:room_id, agent_ids, running = await _seed(session_factory, agents=2)tracker = _TrackingSessionFactory(session_factory)- svc, matrix = _service(tracker, running)+ svc, provisioning = _service(tracker, running)await svc.add_agents_to_room(room_id, agent_ids=agent_ids)- matrix.calls.clear()+ provisioning.calls.clear()await svc.delete_room(room_id)- assert [kind for kind, _who, _live in matrix.calls] == [+ assert [kind for kind, _who, _live in provisioning.calls] == ["kick","kick","delete_room",]- assert [live for _kind, _who, live in matrix.calls] == [0, 0, 0]+ assert [live for _kind, _who, live in provisioning.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 a288d52fe..e5d12ef9d 100644--- a/core/tests/switch_core/test_room_service_reconcile.py+++ b/core/tests/switch_core/test_room_service_reconcile.py@@ -70,18 +70,20 @@ class _FakeClientLifecycle:]-class _FakeMatrix:+class _FakeProvisioning:def __init__(self) -> None:self.invited: list[tuple[str, str]] = []- async def invite_to_room(self, matrix_room_id: str, matrix_user_id: str) -> None:- self.invited.append((matrix_room_id, matrix_user_id))+ async def invite_to_room(+ self, transport_room_id: str, transport_user_id: str+ ) -> None:+ self.invited.append((transport_room_id, transport_user_id))def _admin(tenant_id: str = "tenant-1") -> SimpleNamespace:return SimpleNamespace(client_id="admin-client",- matrix_user_id="@switch-admin:switch.local",+ transport_user_id="@switch-admin:switch.local",tenant_id=tenant_id,)@@ -93,9 +95,9 @@ def _build_service(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]:+) -> tuple[RoomService, _FakeRoomStore, _FakeProvisioning]:room_store = _FakeRoomStore(rooms, client_ids_by_room, agent_clients_by_room or {})- matrix = _FakeMatrix()+ matrix = _FakeProvisioning()# `reconcile_room_clients` now finds its tenants through `all_tenant_ids`,# a real query against `tenants` (`db/tenant_lookup.py`) that the fake@@ -114,7 +116,7 @@ def _build_service(svc._session_factory = lambda: _FakeSessionCM() # type: ignore[assignment]svc._room_store = room_store # type: ignore[assignment]svc._client_lifecycle = _FakeClientLifecycle(by_type) # type: ignore[assignment]- svc._matrix_admin = matrix # type: ignore[assignment]+ svc._provisioning = matrix # type: ignore[assignment]return svc, room_store, matrix@@ -125,7 +127,7 @@ class TestReconcileRoomClients:# A room created before the admin client existed: it has the other# system clients but not the admin. Reconcile invites + records it.room = SimpleNamespace(- id="room-1", tenant_id="tenant-1", matrix_room_id="!mx:switch.local"+ id="room-1", tenant_id="tenant-1", transport_room_id="!mx:switch.local")svc, room_store, matrix = _build_service(monkeypatch,@@ -143,7 +145,7 @@ class TestReconcileRoomClients:self, monkeypatch: pytest.MonkeyPatch) -> None:room = SimpleNamespace(- id="room-1", tenant_id="tenant-1", matrix_room_id="!mx:switch.local"+ id="room-1", tenant_id="tenant-1", transport_room_id="!mx:switch.local")svc, room_store, matrix = _build_service(monkeypatch,@@ -161,7 +163,7 @@ class TestReconcileRoomClients:self, monkeypatch: pytest.MonkeyPatch) -> None:room = SimpleNamespace(- id="room-1", tenant_id="tenant-1", matrix_room_id="!mx:switch.local"+ id="room-1", tenant_id="tenant-1", transport_room_id="!mx:switch.local")svc, room_store, matrix = _build_service(monkeypatch,@@ -180,12 +182,12 @@ class TestReconcileRoomClients:) -> None:rooms = [SimpleNamespace(- id="live", tenant_id="tenant-1", matrix_room_id="!live:switch.local"+ id="live", tenant_id="tenant-1", transport_room_id="!live:switch.local"),SimpleNamespace(id="archived",tenant_id="tenant-1",- matrix_room_id="!arch:switch.local",+ transport_room_id="!arch:switch.local",),]svc, room_store, matrix = _build_service(@@ -206,7 +208,7 @@ class TestReconcileRoomClients:self, monkeypatch: pytest.MonkeyPatch) -> None:room = SimpleNamespace(- id="room-1", tenant_id="tenant-1", matrix_room_id="!mx:switch.local"+ id="room-1", tenant_id="tenant-1", transport_room_id="!mx:switch.local")svc, room_store, matrix = _build_service(monkeypatch,@@ -227,7 +229,7 @@ class TestReconcileRoomClients:# `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", tenant_id="tenant-1", matrix_room_id="!mx:switch.local"+ id="room-1", tenant_id="tenant-1", transport_room_id="!mx:switch.local")svc, room_store, matrix = _build_service(monkeypatch,@@ -246,7 +248,7 @@ class TestReconcileRoomClients:self, monkeypatch: pytest.MonkeyPatch) -> None:room = SimpleNamespace(- id="room-1", tenant_id="tenant-1", matrix_room_id="!mx:switch.local"+ id="room-1", tenant_id="tenant-1", transport_room_id="!mx:switch.local")svc, room_store, matrix = _build_service(monkeypatch,diff --git a/core/tests/switch_core/test_room_service_tenant_bindings.py b/core/tests/switch_core/test_room_service_tenant_bindings.pyindex 4675d5733..e4a1c6ef6 100644--- a/core/tests/switch_core/test_room_service_tenant_bindings.py+++ b/core/tests/switch_core/test_room_service_tenant_bindings.py@@ -135,23 +135,25 @@ class _TenantRecordingRoomStore(RoomStore):await super().set_archived(session, room_id, archived)-class _FakeMatrix:+class _FakeProvisioning:"""Provisioning, which room_service calls with no session open."""def __init__(self, *, fail_for: set[str] | None = None) -> None:self.invited: list[tuple[str, str]] = []self._fail_for = fail_for or set()- async def invite_to_room(self, matrix_room_id: str, matrix_user_id: str) -> None:- if matrix_room_id in self._fail_for:- raise RuntimeError(f"platform refused the invite to {matrix_room_id}")- self.invited.append((matrix_room_id, matrix_user_id))+ async def invite_to_room(+ self, transport_room_id: str, transport_user_id: str+ ) -> None:+ if transport_room_id in self._fail_for:+ raise RuntimeError(f"platform refused the invite to {transport_room_id}")+ self.invited.append((transport_room_id, transport_user_id))class _RunningClient:- def __init__(self, client_id: str, matrix_user_id: str) -> None:+ def __init__(self, client_id: str, transport_user_id: str) -> None:self.client_id = client_id- self.matrix_user_id = matrix_user_id+ self.transport_user_id = transport_user_idclass _AgentRegistry:@@ -161,7 +163,7 @@ class _AgentRegistry:that lookup is where the cross-tenant bug lived and a stand-in would havereimplemented the fix rather than exercised it. Resolving an agent to itsrunning client is not tenant-sensitive — an agent id is unique across the- deployment — and building real `AgentClient`s to say so would add a+ deployment — and building real `AgentConsumer`s to say so would add atransport and a sync loop to a test about bindings."""@@ -188,7 +190,7 @@ class _StubClient:def __init__(self, record: Client) -> None:self.client_id = record.id- self.matrix_user_id = record.matrix_user_id+ self.transport_user_id = record.transport_user_idself.display_name = record.display_nameself._stopped = asyncio.Event()@@ -201,33 +203,35 @@ class _StubClient:class _StubFactory:def create(self, record: Client) -> Any:- return _StubClient(record)+ # The stub reads for itself: it is the actor and its own consumer.+ client = _StubClient(record)+ return client, clientdef _registry(session_factory: async_sessionmaker[AsyncSession],running: list[tuple[str, str, str]],) -> ClientLifecycleService:- """The real registry, holding `(tenant_id, client_id, matrix_user_id)`.+ """The real registry, holding `(tenant_id, client_id, transport_user_id)`.The real one on purpose: `reconcile_room_clients` asks it which systemclients belong to a room's tenant, and getting that answer from the wholedeployment instead of from one tenant is the defect these tests exist for."""service = ClientLifecycleService(- matrix_admin=MagicMock(),+ provisioning=MagicMock(),client_store=ClientStore(),tenant_store=TenantStore(),client_factory=_StubFactory(), # type: ignore[arg-type]session_factory=session_factory,- config=SimpleNamespace(matrix_server_name="switch.local"), # type: ignore[arg-type]+ config=SimpleNamespace(id_server_name="switch.local"), # type: ignore[arg-type])- for tenant_id, client_id, matrix_user_id in running:+ for tenant_id, client_id, transport_user_id in running:service.start_client(Client(id=client_id,tenant_id=tenant_id,- matrix_user_id=matrix_user_id,+ transport_user_id=transport_user_id,display_name="admin",type="admin",)@@ -240,13 +244,13 @@ def _service(*,store: _TenantRecordingRoomStore,clients: Any,- matrix: _FakeMatrix,+ matrix: _FakeProvisioning,) -> RoomService:svc = object.__new__(RoomService)svc._session_factory = session_factory # type: ignore[assignment]svc._room_store = store # type: ignore[assignment]svc._client_lifecycle = clients # type: ignore[assignment]- svc._matrix_admin = matrix # type: ignore[assignment]+ svc._provisioning = matrix # type: ignore[assignment]svc._collab_lifecycle = None # type: ignore[assignment]return svc@@ -257,7 +261,7 @@ async def _seed_tenant_b(session: AsyncSession) -> None:async def _seed_room(- session: AsyncSession, *, tenant_id: str, room_id: str, matrix_room_id: str+ session: AsyncSession, *, tenant_id: str, room_id: str, transport_room_id: str) -> None:"""Insert a room directly, naming its tenant.@@ -271,7 +275,7 @@ async def _seed_room(tenant_id=tenant_id,name=room_id,description="d",- matrix_room_id=matrix_room_id,+ matrix_room_id=transport_room_id,))@@ -281,14 +285,14 @@ async def _seed_client(*,tenant_id: str,client_id: str,- matrix_user_id: str,+ transport_user_id: str,client_type: str = "admin",) -> None:await session.execute(insert(Client.__table__).values(id=client_id,tenant_id=tenant_id,- matrix_user_id=matrix_user_id,+ matrix_user_id=transport_user_id,display_name=client_type,type=client_type,)@@ -320,7 +324,7 @@ async def _seed_agent(session,tenant_id=tenant_id,client_id=client_id,- matrix_user_id=f"@{agent_id}:switch.local",+ transport_user_id=f"@{agent_id}:switch.local",client_type="agent",)await session.execute(@@ -376,25 +380,25 @@ class TestReconcileRoomClients:session,tenant_id=TENANT_ZERO_ID,room_id="room-zero",- matrix_room_id="!zero:switch.local",+ transport_room_id="!zero:switch.local",)await _seed_room(session,tenant_id=TENANT_B,room_id="room-b",- matrix_room_id="!b:switch.local",+ transport_room_id="!b:switch.local",)await _seed_client(session,tenant_id=TENANT_ZERO_ID,client_id="admin-zero",- matrix_user_id="@switch-admin:switch.local",+ transport_user_id="@switch-admin:switch.local",)await _seed_client(session,tenant_id=TENANT_B,client_id="admin-b",- matrix_user_id="@switch-admin:switch.local",+ transport_user_id="@switch-admin:switch.local",)await session.commit()@@ -410,7 +414,7 @@ class TestReconcileRoomClients:session_factory,store=store,clients=registry,- matrix=_FakeMatrix(),+ matrix=_FakeProvisioning(),)try:@@ -461,13 +465,13 @@ class TestReconcileRoomClients:session,tenant_id=TENANT_B,room_id="room-b",- matrix_room_id="!b:switch.local",+ transport_room_id="!b:switch.local",)await _seed_client(session,tenant_id=TENANT_B,client_id="admin-b",- matrix_user_id="@switch-admin:switch.local",+ transport_user_id="@switch-admin:switch.local",)await session.commit()@@ -479,7 +483,7 @@ class TestReconcileRoomClients:session_factory,store=store,clients=registry,- matrix=_FakeMatrix(),+ matrix=_FakeProvisioning(),)try:@@ -515,25 +519,25 @@ class TestReconcileRoomClients:session,tenant_id=TENANT_ZERO_ID,room_id="room-broken",- matrix_room_id="!broken:switch.local",+ transport_room_id="!broken:switch.local",)await _seed_room(session,tenant_id=TENANT_B,room_id="room-b",- matrix_room_id="!b:switch.local",+ transport_room_id="!b:switch.local",)await _seed_client(session,tenant_id=TENANT_ZERO_ID,client_id="admin-zero",- matrix_user_id="@switch-admin:switch.local",+ transport_user_id="@switch-admin:switch.local",)await _seed_client(session,tenant_id=TENANT_B,client_id="admin-b",- matrix_user_id="@switch-admin:switch.local",+ transport_user_id="@switch-admin:switch.local",)await session.commit()@@ -548,7 +552,7 @@ class TestReconcileRoomClients:session_factory,store=_TenantRecordingRoomStore(),clients=registry,- matrix=_FakeMatrix(fail_for={"!broken:switch.local"}),+ matrix=_FakeProvisioning(fail_for={"!broken:switch.local"}),)try:@@ -572,13 +576,13 @@ class TestReconcileRoomClients:session,tenant_id=TENANT_ZERO_ID,room_id="room-broken",- matrix_room_id="!broken:switch.local",+ transport_room_id="!broken:switch.local",)await _seed_client(session,tenant_id=TENANT_ZERO_ID,client_id="admin-zero",- matrix_user_id="@switch-admin:switch.local",+ transport_user_id="@switch-admin:switch.local",)await session.commit()@@ -590,7 +594,7 @@ class TestReconcileRoomClients:session_factory,store=_TenantRecordingRoomStore(),clients=registry,- matrix=_FakeMatrix(fail_for={"!broken:switch.local"}),+ matrix=_FakeProvisioning(fail_for={"!broken:switch.local"}),)try:@@ -631,7 +635,7 @@ class TestBindingsOnTheRoomsOwnTenant:session,tenant_id=TENANT_B,room_id="room-b",- matrix_room_id="!b:switch.local",+ transport_room_id="!b:switch.local",)await _seed_agent(session,@@ -648,7 +652,7 @@ class TestBindingsOnTheRoomsOwnTenant:clients=_AgentRegistry({"agent-b": _RunningClient("client-b", "@agent-b:switch.local")}),- matrix=_FakeMatrix(),+ matrix=_FakeProvisioning(),)assert current_tenant_id() is None@@ -682,7 +686,7 @@ class TestBindingsOnTheRoomsOwnTenant:session,tenant_id=TENANT_B,room_id="room-b",- matrix_room_id="!b:switch.local",+ transport_room_id="!b:switch.local",)await session.commit()@@ -691,7 +695,7 @@ class TestBindingsOnTheRoomsOwnTenant:session_factory,store=store,clients=_AgentRegistry({}),- matrix=_FakeMatrix(),+ matrix=_FakeProvisioning(),)await svc.set_room_archived("room-b", True)@@ -723,7 +727,7 @@ class TestBindingsOnTheRoomsOwnTenant:session,tenant_id=TENANT_ZERO_ID,room_id="room-zero",- matrix_room_id="!zero:switch.local",+ transport_room_id="!zero:switch.local",)await session.commit()diff --git a/core/tests/switch_core/test_room_wide_mention.py b/core/tests/switch_core/test_room_wide_mention.pyindex 92c3d7e8d..fca4f91c7 100644--- a/core/tests/switch_core/test_room_wide_mention.py+++ b/core/tests/switch_core/test_room_wide_mention.py@@ -148,7 +148,7 @@ async def test_define_role_refuses_a_reserved_name(session_factory: async_sessionmaker[AsyncSession],) -> None:async with session_factory() as session:- room = Room(matrix_room_id="!r:test", name="r", description="r")+ room = Room(transport_room_id="!r:test", name="r", description="r")session.add(room)await session.flush()with pytest.raises(ValueError, match="reserved"):diff --git a/core/tests/switch_core/test_room_wide_mention_wakes_no_agent.py b/core/tests/switch_core/test_room_wide_mention_wakes_no_agent.pyindex 2ba7ac778..3898f61ef 100644--- a/core/tests/switch_core/test_room_wide_mention_wakes_no_agent.py+++ b/core/tests/switch_core/test_room_wide_mention_wakes_no_agent.py@@ -2,7 +2,7 @@This is the promise the feature exists to keep, so it is tested end to endagainst a real database rather than stubbed stores: the message is produced by-`ProtocolService.send_targeted_message`, carried in the content the transport+`AgentCore.send_targeted_message`, carried in the content the transportwould store, and judged by `AddressingResolver.addresses` — the one decisionthe agent client turns into `MessagePayload.addressed`, which is what the eventbuffer's `is_notifiable` delivers on. Every way an agent can be addressed is@@ -22,8 +22,8 @@ from typing import Anyimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.bridges.agent.protocol.connections import ConnectionRegistry-from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.types import (AgentStatus,RoomWideMentionStatus,@@ -56,7 +56,7 @@ async def _make_agent(session: AsyncSession, name: str) -> Agent:label=name,type="agent",)- client = Client(matrix_user_id=f"@{name}:test", display_name=name, type="agent")+ client = Client(transport_user_id=f"@{name}:test", display_name=name, type="agent")session.add_all([api_key, client])await session.flush()agent = Agent(@@ -95,7 +95,7 @@ class _Room:async def room(session_factory: async_sessionmaker[AsyncSession]) -> _Room:room_store, role_store = RoomStore(), RoomRoleStore()async with session_factory() as session:- row = Room(matrix_room_id="!wide:test", name="wide", description="wide")+ row = Room(transport_room_id="!wide:test", name="wide", description="wide")session.add(row)await session.flush()agents = [@@ -119,7 +119,7 @@ class _Sent:def _service(session_factory: async_sessionmaker[AsyncSession], room: _Room-) -> tuple[ProtocolService, list[_Sent]]:+) -> tuple[AgentCore, list[_Sent]]:"""The real `send_targeted_message`, over real stores.Only the two edges that leave the process are replaced: the participant@@ -127,8 +127,8 @@ def _service(what would have gone onto the bus."""sent: list[_Sent] = []- svc = object.__new__(ProtocolService)- svc.connections = ConnectionRegistry()+ svc = object.__new__(AgentCore)+ svc.connections = AgentConnectionRegistry()svc.session_factory = session_factorysvc.room_store = RoomStore()svc.room_role_store = RoomRoleStore()@@ -186,7 +186,7 @@ async def _woken(if await resolver.addresses(session,agent=agent,- agent_matrix_id=f"@{agent.name}:test",+ agent_user_id=f"@{agent.name}:test",room_id=room.id,channel_type="channel_public",message=message,diff --git a/core/tests/switch_core/test_rooms_yaml.py b/core/tests/switch_core/test_rooms_yaml.pyindex 7816272a3..9cb6273eb 100644--- a/core/tests/switch_core/test_rooms_yaml.py+++ b/core/tests/switch_core/test_rooms_yaml.py@@ -20,7 +20,7 @@ from sqlalchemy import insert, selectfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.resource.service import ResourceService-from switch_core.clients.admin_client import AdminClient+from switch_core.clients.actor import SystemActorfrom switch_core.clients.admin_messages import OnBehalfOffrom switch_core.db.models import (Agent,@@ -110,7 +110,7 @@ class FakeRoomService:agent_ids = [name_to_id[n] for n in config.agent_names]room = Room(- matrix_room_id=f"!{uuid.uuid4().hex}:test.local",+ transport_room_id=f"!{uuid.uuid4().hex}:test.local",name=config.name,description=config.description,channel_type=config.channel_type or "channel_public",@@ -154,7 +154,7 @@ async def _make_agent(session: AsyncSession, name: str, user_id: str) -> Agent:type="agent",)client = Client(- matrix_user_id=f"@{name}:test.local",+ transport_user_id=f"@{name}:test.local",display_name=name,type="agent",)@@ -685,22 +685,22 @@ async def test_export_includes_users_from_bridge(env):"""A bridged room with an external user in it exports that user by name."""sf = env["session_factory"]async with sf() as session:- bridge_client = Client(- matrix_user_id="@bridge:test.local",+ workspace_consumer = Client(+ transport_user_id="@bridge:test.local",display_name="bridge",type="collaboration_bridge",)user_client = Client(- matrix_user_id="@bob:test.local",+ transport_user_id="@bob:test.local",display_name="bob",type="external_user",)- session.add_all([bridge_client, user_client])+ session.add_all([workspace_consumer, user_client])await session.flush()bridge = CollaborationBridge(type="mattermost",display_name="Mattermost",- client_id=bridge_client.id,+ client_id=workspace_consumer.id,status="active",)session.add(bridge)@@ -714,7 +714,7 @@ async def test_export_includes_users_from_bridge(env):))room = Room(- matrix_room_id="!bridged:test.local",+ transport_room_id="!bridged:test.local",name="Mattermost: Bridged",description="d",channel_type="channel_public",@@ -1170,7 +1170,7 @@ async def test_endpoint_json_body(env):# ── kickoff ─────────────────────────────────────────────────────────────────-class FakeAdminClient(AdminClient):+class FakeSystemActor(SystemActor):"""Records platform sends; never touches a transport."""def __init__(self) -> None: # noqa: D107 - test double, no super().__init__@@ -1214,7 +1214,7 @@ class FakeAgentClient:class FakeLifecycle:- def __init__(self, admin: AdminClient | None) -> None:+ def __init__(self, admin: SystemActor | None) -> None:self.admin = adminself.agent_clients: dict[str, FakeAgentClient] = {}@@ -1228,7 +1228,7 @@ class FakeLifecycle:def _with_kickoff(- env, admin: AdminClient | None+ env, admin: SystemActor | None) -> tuple[RoomYamlService, FakeLifecycle]:lifecycle = FakeLifecycle(admin)svc = _svc(env)@@ -1253,7 +1253,7 @@ kickoff: |async def test_provision_kickoff_posts_as_platform_on_behalf_of_creator(env):"""The kickoff goes out through the admin client with the creator namedin the marker, after interpolation, and the room reports no failure."""- admin = FakeAdminClient()+ admin = FakeSystemActor()svc, _ = _with_kickoff(env, admin)spec, kickoff = svc.parse(KICKOFF_TEMPLATE, inputs={"coder": "claude-code.alice"})result = await svc.provision(@@ -1285,7 +1285,7 @@ async def test_provision_kickoff_posts_as_platform_on_behalf_of_creator(env):@pytest.mark.asyncioasync def test_provision_kickoff_send_failure_is_reported_not_fatal(env):- admin = FakeAdminClient()+ admin = FakeSystemActor()admin.send_error = RuntimeError("transport down")svc, _ = _with_kickoff(env, admin)spec, kickoff = svc.parse(KICKOFF_TEMPLATE, inputs={"coder": "claude-code.alice"})@@ -1302,7 +1302,7 @@ async def test_provision_kickoff_send_failure_is_reported_not_fatal(env):async def test_provision_kickoff_none_event_id_is_a_failure(env):"""The admin client answers None when the send did not happen; that is afailure, not a silent success."""- admin = FakeAdminClient()+ admin = FakeSystemActor()admin.send_returns = Nonesvc, _ = _with_kickoff(env, admin)spec, kickoff = svc.parse(KICKOFF_TEMPLATE, inputs={"coder": "claude-code.alice"})@@ -1318,7 +1318,7 @@ async def test_provision_kickoff_none_event_id_is_a_failure(env):async def test_provision_kickoff_waits_for_agents_and_reports_the_late(env):"""An agent whose client has not joined by the timeout is named in thefailure; the kickoff is still posted for the ones that did."""- admin = FakeAdminClient()+ admin = FakeSystemActor()svc, lifecycle = _with_kickoff(env, admin)async with env["session_factory"]() as session:agent = await AgentStore().get_by_name(session, "claude-code.alice")@@ -1335,7 +1335,7 @@ async def test_provision_kickoff_waits_for_agents_and_reports_the_late(env):@pytest.mark.asyncioasync def test_provision_kickoff_not_posted_when_platform_never_joins(env):- admin = FakeAdminClient()+ admin = FakeSystemActor()admin.joined = Falsesvc, _ = _with_kickoff(env, admin)spec, kickoff = svc.parse(KICKOFF_TEMPLATE, inputs={"coder": "claude-code.alice"})@@ -1364,7 +1364,7 @@ async def test_provision_kickoff_without_admin_client_is_reported(env):@pytest.mark.asyncioasync def test_provision_without_kickoff_posts_nothing(env):- admin = FakeAdminClient()+ admin = FakeSystemActor()svc, _ = _with_kickoff(env, admin)spec, kickoff = svc.parse("room:\n name: quiet\n description: d\n")assert kickoff is None@@ -1386,22 +1386,22 @@ async def _seed_bridge_with_claim("""A bridge, an external user on it, and optionally a claim. Returns thebridge id."""async with session_factory() as session:- bridge_client = Client(- matrix_user_id=f"@bridge-{display_name.lower()}:test.local",+ workspace_consumer = Client(+ transport_user_id=f"@bridge-{display_name.lower()}:test.local",display_name=display_name,type="collaboration_bridge",)user_client = Client(- matrix_user_id=f"@{external_username}-{display_name.lower()}:test.local",+ transport_user_id=f"@{external_username}-{display_name.lower()}:test.local",display_name=external_username,type="external_user",)- session.add_all([bridge_client, user_client])+ session.add_all([workspace_consumer, user_client])await session.flush()bridge = CollaborationBridge(type="slack",display_name=display_name,- client_id=bridge_client.id,+ client_id=workspace_consumer.id,status="active",is_default=is_default,)diff --git a/core/tests/switch_core/test_seed_admin_membership.py b/core/tests/switch_core/test_seed_admin_membership.pyindex d71f0adaa..ea9dd3770 100644--- a/core/tests/switch_core/test_seed_admin_membership.py+++ b/core/tests/switch_core/test_seed_admin_membership.py@@ -53,7 +53,7 @@ def _config() -> SwitchConfig:db_user="unused",db_password="unused",db_name="unused",- matrix_server_name="test",+ id_server_name="test",agent_registration_token="unused",jwt_secret_key="test-jwt-secret",gateway_admin_email=ADMIN_EMAIL,diff --git a/core/tests/switch_core/transport/test_postgres_transport.py b/core/tests/switch_core/transport/test_postgres_transport.pyindex 5bdea7b80..ac14d89aa 100644--- a/core/tests/switch_core/transport/test_postgres_transport.py+++ b/core/tests/switch_core/transport/test_postgres_transport.py@@ -61,28 +61,28 @@ async def _make_room(session: AsyncSession) -> tuple[str, str, str, str]:"""suffix = uuid.uuid4().hex[:8]client = Client(- matrix_user_id=f"@agent-{suffix}:test",+ transport_user_id=f"@agent-{suffix}:test",display_name="agent one",type="agent",)session.add(client)await session.flush()- room = Room(matrix_room_id=f"!room-{suffix}:test", name="a room", description="")+ room = Room(transport_room_id=f"!room-{suffix}:test", name="a room", description="")session.add(room)await session.flush()- return room.id, room.matrix_room_id, client.id, client.matrix_user_id+ return room.id, room.transport_room_id, client.id, client.transport_user_idasync def _make_client(session: AsyncSession, label: str) -> tuple[str, str]:"""Insert one more Client. Returns (client id, client mxid)."""client = Client(- matrix_user_id=f"@{label}-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@{label}-{uuid.uuid4().hex[:8]}:test",display_name=label,type="agent",)session.add(client)await session.flush()- return client.id, client.matrix_user_id+ return client.id, client.transport_user_idasync def _watched_room(transport: PostgresTransport) -> str:@@ -176,6 +176,7 @@ def _transport(listener: _FakeListener | None = None,ephemeral: EphemeralBus | None = None,invites: InviteBus | None = None,+ actor_role: str = "agent",) -> PostgresTransport:"""A transport for `client_id`, acting in `tenant_id`.@@ -192,6 +193,7 @@ def _transport(client_id=client_id,tenant_id=tenant_id,display_name="agent one",+ actor_role=actor_role,session_factory=session_factory,room_store=RoomStore(),message_store=MessageStore(),@@ -581,6 +583,7 @@ class TestMedia:user_id="@a:test",client_id="ghost",display_name="agent one",+ actor_role="agent",session_factory=session_factory,room_store=RoomStore(),message_store=MessageStore(),@@ -741,13 +744,13 @@ class TestReceiving:async with session_factory() as session:newcomer = Client(- matrix_user_id=f"@later-{uuid.uuid4().hex[:8]}:test",+ transport_user_id=f"@later-{uuid.uuid4().hex[:8]}:test",display_name="the newcomer",type="agent",)session.add(newcomer)await session.commit()- newcomer_id, newcomer_mxid = newcomer.id, newcomer.matrix_user_id+ newcomer_id, newcomer_mxid = newcomer.id, newcomer.transport_user_idjoiner = _transport(session_factory, client_id=newcomer_id, user_id=newcomer_mxid@@ -1104,21 +1107,21 @@ class TestDeliveryBindsTheRoomsTenant:suffix = uuid.uuid4().hex[:8]client = Client(tenant_id=tenant_id,- matrix_user_id=f"@agent-{suffix}:test",+ transport_user_id=f"@agent-{suffix}:test",display_name="agent one",type="agent",)session.add(client)room = Room(tenant_id=tenant_id,- matrix_room_id=f"!room-{suffix}:test",+ transport_room_id=f"!room-{suffix}:test",name="a room",description="",)session.add(room)await session.commit()- transport_room_id = room.matrix_room_id- client_id, user_id = client.id, client.matrix_user_id+ transport_room_id = room.transport_room_id+ client_id, user_id = client.id, client.transport_user_idseen: list[str | None] = []original = MessageStore.list_for_room@@ -1164,7 +1167,7 @@ class TestATransportActsInItsClientsTenant:Its task binds nothing: `ClientLifecycleService` unbinds before running aclient, so anything the transport did under an *inherited* tenant would bedoing it under the tenant of whoever happened to create the task — boot, a- gateway request, or the inbound bridge message that minted a puppet+ gateway request, or the inbound bridge message that minted a human actormid-conversation. That is still the failure this class exists to prevent.What changed with the restricted runtime role is where the right answercomes from.@@ -1221,14 +1224,14 @@ class TestATransportActsInItsClientsTenant:suffix = uuid.uuid4().hex[:8]client = Client(tenant_id=tenant_id,- matrix_user_id=f"@sys-{suffix}:test",+ transport_user_id=f"@sys-{suffix}:test",display_name="admin",type="admin",)session.add(client)room = Room(tenant_id=tenant_id,- matrix_room_id=f"!room-{suffix}:test",+ transport_room_id=f"!room-{suffix}:test",name="a room",description="",)@@ -1238,8 +1241,8 @@ class TestATransportActsInItsClientsTenant:ClientRoom(tenant_id=tenant_id, client_id=client.id, room_id=room.id))await session.commit()- client_id, user_id = client.id, client.matrix_user_id- transport_room_id = room.matrix_room_id+ client_id, user_id = client.id, client.transport_user_id+ transport_room_id = room.transport_room_idseen: list[str | None] = []original = RoomStore.get_for_client@@ -1257,7 +1260,7 @@ class TestATransportActsInItsClientsTenant:tenant_id=tenant_id,)# Stands in for a task that inherited a tenant it has no business- # acting under — a bridge restart, a puppet minted mid-conversation.+ # acting under — a bridge restart, a human actor minted mid-conversation.with tenant_scope("some-other-tenant"):rooms = await transport.joined_rooms()@@ -1287,14 +1290,14 @@ class TestATransportActsInItsClientsTenant:suffix = uuid.uuid4().hex[:8]client = Client(tenant_id=tenant_id,- matrix_user_id=f"@sys-{suffix}:test",+ transport_user_id=f"@sys-{suffix}:test",display_name="admin",type="admin",)session.add(client)room = Room(tenant_id=tenant_id,- matrix_room_id=f"!room-{suffix}:test",+ transport_room_id=f"!room-{suffix}:test",name="a room",description="",)@@ -1324,7 +1327,7 @@ class TestATransportActsInItsClientsTenant:client's tenant — with nothing bound around the loop that drives them.This test used to arrange the two rooms in *different* tenants, on the- reading that a reused puppet could speak in both and that the+ reading that a reused human actor could speak in both and that thetransport's own tenant must therefore never decide how a room is read.That shape is not reachable: `client_rooms` and `messages` both key to`rooms` and to `clients` through `tenant_id`, so a client can be@@ -1339,30 +1342,30 @@ class TestATransportActsInItsClientsTenant:async with session_factory() as session:session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))await session.flush()- puppet = Client(+ human_actor = Client(tenant_id=tenant_id,- matrix_user_id=f"@puppet-{suffix}:test",- display_name="puppet",+ transport_user_id=f"@human-actor-{suffix}:test",+ display_name="human actor",type="user",)- session.add(puppet)+ session.add(human_actor)first = Room(tenant_id=tenant_id,- matrix_room_id=f"!a-{suffix}:test",+ transport_room_id=f"!a-{suffix}:test",name="room a",description="",)second = Room(tenant_id=tenant_id,- matrix_room_id=f"!b-{suffix}:test",+ transport_room_id=f"!b-{suffix}:test",name="room b",description="",)session.add_all([first, second])await session.commit()room_ids = {first.id: tenant_id, second.id: tenant_id}- mxid_a, mxid_b = first.matrix_room_id, second.matrix_room_id- client_id, user_id = puppet.id, puppet.matrix_user_id+ mxid_a, mxid_b = first.transport_room_id, second.transport_room_id+ client_id, user_id = human_actor.id, human_actor.transport_user_idseen: dict[str, list[str | None]] = {}original = MessageStore.list_for_room@@ -1388,8 +1391,12 @@ class TestATransportActsInItsClientsTenant:self._tasks.append(asyncio.create_task(transport.receive_forever()))await _watched_room(transport)- await transport.send_message(mxid_a, "in a", sender_name="puppet", metered=True)- await transport.send_message(mxid_b, "in b", sender_name="puppet", metered=True)+ await transport.send_message(+ mxid_a, "in a", sender_name="human actor", metered=True+ )+ await transport.send_message(+ mxid_b, "in b", sender_name="human actor", metered=True+ )for room_id in room_ids:await listener.announce(room_id)@@ -1423,21 +1430,21 @@ class TestATransportActsInItsClientsTenant:await session.flush()client = Client(tenant_id=tenant_id,- matrix_user_id=f"@sys-{suffix}:test",+ transport_user_id=f"@sys-{suffix}:test",display_name="admin",type="admin",)session.add(client)elsewhere = Room(tenant_id=other_tenant,- matrix_room_id=f"!elsewhere-{suffix}:test",+ transport_room_id=f"!elsewhere-{suffix}:test",name="somebody else's room",description="",)session.add(elsewhere)await session.commit()- client_id, user_id = client.id, client.matrix_user_id- elsewhere_mxid = elsewhere.matrix_room_id+ client_id, user_id = client.id, client.transport_user_id+ elsewhere_mxid = elsewhere.transport_room_idtransport = _transport(rls_harness.restricted,@@ -1472,14 +1479,14 @@ async def test_the_schema_forbids_a_client_row_in_another_tenants_room(await session.flush()client = Client(tenant_id=tenant_a,- matrix_user_id=f"@sys-{suffix}:test",+ transport_user_id=f"@sys-{suffix}:test",display_name="admin",type="admin",)session.add(client)room = Room(tenant_id=tenant_b,- matrix_room_id=f"!b-{suffix}:test",+ transport_room_id=f"!b-{suffix}:test",name="room b",description="",)@@ -1514,6 +1521,7 @@ class TestWhatIsMeasured:self,session_factory: async_sessionmaker[AsyncSession],handlers: TransportHandlers | None = None,+ actor_role: str = "agent",) -> tuple[PostgresTransport, _FakeListener, str]:async with session_factory() as session:_, transport_room_id, client_id, user_id = await _make_room(session)@@ -1521,7 +1529,11 @@ class TestWhatIsMeasured:listener = _FakeListener()transport = _transport(- session_factory, client_id=client_id, user_id=user_id, listener=listener+ session_factory,+ client_id=client_id,+ user_id=user_id,+ listener=listener,+ actor_role=actor_role,)transport.register_handlers(handlers or _Received().handlers())await transport.join_room(transport_room_id)@@ -1550,6 +1562,24 @@ class TestWhatIsMeasured:assert self._kinds(payloads, "switch.messages.sent") == {"message": 1.0}assert self._kinds(payloads, "switch.messages.delivered") == {"message": 1.0}+ async def test_writes_and_reads_say_which_actor_did_them(+ self, session_factory: async_sessionmaker[AsyncSession], _registry+ ) -> None:+ # The same tag on both sides, so a dashboard can put who writes next+ # to who reads.+ transport, listener, room = await self._receiving(+ session_factory, actor_role="system"+ )++ await transport.send_message(room, "hello", sender_name="Switch", metered=False)+ await listener.announce(await _watched_room(transport))++ payloads = {p.name: p for p in _registry.collect()}+ for name in ("switch.messages.sent", "switch.messages.delivered"):+ assert [dict(point.attributes) for point in payloads[name].numbers] == [+ {"kind": "message", "actor": "system"}+ ], name+async def test_media_is_counted_apart_from_text(self, session_factory: async_sessionmaker[AsyncSession], _registry) -> None:@@ -1588,7 +1618,7 @@ class TestWhatIsMeasured:)point = payload.histograms[0]assert point.count == 1- assert point.attributes == {"kind": "message"}+ assert point.attributes == {"kind": "message", "actor": "agent"}# Never negative: the row's timestamp comes from the database's clock# and the subtraction happens on this process's, so skew is ordinary.assert 0.0 <= point.total < 60_000.0diff --git a/deploy/local/standalone-docker-compose.yml b/deploy/local/standalone-docker-compose.ymlindex 195966b2d..5f144c6bc 100644--- a/deploy/local/standalone-docker-compose.yml+++ b/deploy/local/standalone-docker-compose.yml@@ -206,6 +206,10 @@ services:DB_OWNER_USER: ${DB_OWNER_USER}DB_OWNER_PASSWORD: ${DB_OWNER_PASSWORD}DB_NAME: ${DB_NAME}+ ID_SERVER_NAME: localhost+ # The same setting under its old name, for a SWITCH_VERSION released+ # before the rename, which reads only this one. Drop it once the oldest+ # supported release reads ID_SERVER_NAME.MATRIX_SERVER_NAME: localhostAGENT_REGISTRATION_TOKEN: ${AGENT_REGISTRATION_TOKEN}JWT_SECRET_KEY: ${JWT_SECRET_KEY}diff --git a/deploy/observability/README.md b/deploy/observability/README.mdindex 60dc1b961..c53391e6c 100644--- a/deploy/observability/README.md+++ b/deploy/observability/README.md@@ -56,7 +56,7 @@ side rather than the collector's: **percentile aggregations are off by defaulton a distribution metric and are billed separately.** Enable them per metric inMetrics Summary, and add the tag each panel groups by to that metric'sconfigured tag set — `route` for requests, `operation` for database queries,-`platform` for bridge calls — or `p95: … by {…}` returns nothing on a fresh+`bridge` and `platform` for bridge calls — or `p95: … by {…}` returns nothing on a freshaccount. Empty is the honest outcome either way; a panel is never silentlyswitched to a different statistic.diff --git a/deploy/observability/dashboard.json b/deploy/observability/dashboard.jsonindex b1f93633c..51d5ed459 100644--- a/deploy/observability/dashboard.json+++ b/deploy/observability/dashboard.json@@ -108,10 +108,10 @@{"definition": {"type": "query_value",- "title": "Room clients running",+ "title": "Consumers running (read loops)","requests": [{- "q": "avg:switch.clients.running{$env,$service}",+ "q": "avg:switch.consumers.running{$env,$service}","aggregator": "last"}],@@ -269,11 +269,11 @@"show_legend": true,"requests": [{- "q": "sum:switch.messages.sent{$env,$service}.as_rate()",+ "q": "sum:switch.messages.sent{$env,$service} by {actor}.as_rate()","display_type": "line"},{- "q": "sum:switch.messages.delivered{$env,$service}.as_rate()",+ "q": "sum:switch.messages.delivered{$env,$service} by {actor}.as_rate()","display_type": "line"}]@@ -333,7 +333,7 @@{"definition": {"type": "note",- "content": "**Bridges.** Inbound is counted where every platform event already funnels through; outbound at the relay, so a puppet's own echo and a room with no channel are not counted as traffic nobody sent.",+ "content": "**Bridges.** Inbound is counted where every platform event already funnels through; outbound at the relay, so a human actor's own echo and a room with no channel are not counted as traffic nobody sent.","background_color": "gray","font_size": "14","text_align": "left",@@ -353,11 +353,11 @@{"definition": {"type": "timeseries",- "title": "Inbound platform events per second, by platform",+ "title": "Bridge events in per second, by bridge and platform","show_legend": true,"requests": [{- "q": "sum:switch.bridge.events_in{$env,$service} by {platform}.as_rate()",+ "q": "sum:switch.bridge.events_in{$env,$service} by {bridge,platform}.as_rate()","display_type": "area"}]@@ -372,11 +372,11 @@{"definition": {"type": "timeseries",- "title": "Outbound relays per second, by platform",+ "title": "Bridge events out per second, by bridge and platform","show_legend": true,"requests": [{- "q": "sum:switch.bridge.events_out{$env,$service} by {platform}.as_rate()",+ "q": "sum:switch.bridge.events_out{$env,$service} by {bridge,platform}.as_rate()","display_type": "area"}]@@ -391,11 +391,11 @@{"definition": {"type": "timeseries",- "title": "Bridge errors per second, by platform and direction",+ "title": "Bridge errors per second, by bridge, platform and direction","show_legend": true,"requests": [{- "q": "sum:switch.bridge.errors{$env,$service} by {platform,direction}.as_rate()",+ "q": "sum:switch.bridge.errors{$env,$service} by {bridge,platform,direction}.as_rate()","display_type": "bars","style": {"palette": "warm"@@ -661,11 +661,11 @@{"definition": {"type": "timeseries",- "title": "Collaboration platform call duration p95 (ms) by platform \u2014 needs distribution mapping, see README",+ "title": "Bridge call duration p95 (ms) by bridge and platform \u2014 needs distribution mapping, see README","show_legend": true,"requests": [{- "q": "p95:switch.bridge.call.duration{$env,$service} by {platform}",+ "q": "p95:switch.bridge.call.duration{$env,$service} by {bridge,platform}","display_type": "line"}]diff --git a/deploy/observability/monitors.json b/deploy/observability/monitors.jsonindex 86c172cab..2092da7c2 100644--- a/deploy/observability/monitors.json+++ b/deploy/observability/monitors.json@@ -207,7 +207,7 @@{"name": "[Switch] a bridge is failing to relay","type": "metric alert",- "query": "sum(last_15m):sum:switch.bridge.errors{service:switch-core} by {platform,direction}.as_count() > 10",+ "query": "sum(last_15m):sum:switch.bridge.errors{service:switch-core,bridge:collaboration} by {platform,direction}.as_count() > 10","message": "{{platform.name}} has failed {{value}} time(s) {{direction.name}} in fifteen minutes.\n\nInbound failures are messages a person sent that nobody received; from the platform's side that is indistinguishable from being ignored. Outbound failures are Switch's replies not arriving.\n\nThe bridge is still running \u2014 a crashed one is a different alert. This is usually the platform rate-limiting, an expired token, or a channel the app was removed from.\n\n@REPLACE-WITH-NOTIFICATION-HANDLE","tags": ["service:switch-core",diff --git a/deploy/remote/helm/switch/README.md b/deploy/remote/helm/switch/README.mdindex fdd164ae4..16b846299 100644--- a/deploy/remote/helm/switch/README.md+++ b/deploy/remote/helm/switch/README.md@@ -156,9 +156,11 @@ example), leave `tls.enabled` false and annotate.## Constraints you cannot configure away-**switch-core runs exactly one replica.** It holds live Matrix sync sessions and-bridge connections in memory; a second replica would duplicate every client and-split session state. `switchCore.replicaCount` other than 1 fails the render,+**switch-core runs exactly one replica.** Four things live in the process+rather than the database: the per-agent event buffer, the invite bus, the+presence bus, and the message listener's subscriber registry. A second replica+would hold its own copy of each, so a signal raised in one would never reach a+client attached to the other. Bridge connections live in memory too. `switchCore.replicaCount` other than 1 fails the render,and the deployment strategy is `Recreate`, so upgrades have a brief outagerather than two pods fighting.diff --git a/deploy/remote/helm/switch/templates/_helpers.tpl b/deploy/remote/helm/switch/templates/_helpers.tplindex b8b66116a..45d0b99a5 100644--- a/deploy/remote/helm/switch/templates/_helpers.tpl+++ b/deploy/remote/helm/switch/templates/_helpers.tpl@@ -564,6 +564,10 @@ Include with `nindent 12`.value: {{ .Values.postgresql.migrationLockTimeout | quote }}- name: AGENT_AUTH_CACHE_TTL_SECONDSvalue: {{ .Values.switchCore.authCache.ttlSeconds | quote }}+- name: ID_SERVER_NAME+ value: {{ .Values.clientIdentity.serverName | quote }}+{{- /* The old name, for an image released before the rename, which reads only+this one. Drop it once the oldest supported image reads ID_SERVER_NAME. */}}- name: MATRIX_SERVER_NAMEvalue: {{ .Values.clientIdentity.serverName | quote }}- name: AGENT_REGISTRATION_TOKENdiff --git a/deploy/remote/helm/switch/templates/switch-core/deployment.yaml b/deploy/remote/helm/switch/templates/switch-core/deployment.yamlindex 08433fc0b..e00cb4fce 100644--- a/deploy/remote/helm/switch/templates/switch-core/deployment.yaml+++ b/deploy/remote/helm/switch/templates/switch-core/deployment.yaml@@ -1,5 +1,5 @@{{- if ne (int .Values.switchCore.replicaCount) 1 }}-{{- fail "switchCore.replicaCount must be 1: switch-core keeps live Matrix sync sessions in memory and cannot be horizontally scaled (a second replica would duplicate every client and split session state)." }}+{{- fail "switchCore.replicaCount must be 1: switch-core keeps the per-agent event buffer, the invite bus, the presence bus and the message listener's subscriber registry in memory, so a second replica would never hear signals raised in the first." }}{{- end }}{{- include "switch.validateDbTls" . }}{{- include "switch.validateLogging" . }}@@ -13,8 +13,8 @@ metadata:{{- include "switch.selectorLabels" (dict "Release" .Release "component" "switch-core") | nindent 4 }}spec:replicas: {{ .Values.switchCore.replicaCount }}- # switch-core is a singleton (live Matrix sync + collaboration-bridge sessions- # in memory). A rolling update would briefly run two pods whose bridge/client+ # switch-core is a singleton (in-process delivery state + collaboration-bridge+ # sessions in memory). A rolling update would briefly run two pods whose bridge/client# sessions collide and leave bridges stuck; Recreate tears the old pod down# before starting the new one.strategy:diff --git a/deploy/remote/helm/switch/values.yaml b/deploy/remote/helm/switch/values.yamlindex 8f1f4de1e..f54661d03 100644--- a/deploy/remote/helm/switch/values.yaml+++ b/deploy/remote/helm/switch/values.yaml@@ -583,9 +583,9 @@ postgresql:# transaction without executing anything for longer than this (e.g. "15s"),# so a leaked checkout becomes a loud, attributable error instead of a slot# that never comes back. Empty (the default) leaves it off, and it must stay- # off until switch-core stops holding transactions across Matrix round trips- # on the room-membership paths — until then this trades request latency for- # membership drift: agents invited on Matrix with no row recording it. Set it+ # off until switch-core stops holding transactions open across the invite and+ # kick calls on the room-membership paths. Until then this trades request+ # latency for membership drift: agents invited with no row recording it. Set it# in staging first. Migrations are unaffected; Alembic does not read it.idleInTransactionSessionTimeout: ""diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.mdindex c1407d88e..bca3096ba 100644--- a/docs/TELEMETRY.md+++ b/docs/TELEMETRY.md@@ -162,8 +162,8 @@ sign-in records `invalid_credentials` — not the username tried, not the server| Event | Fields, with example values ||---|---|-| `bridge_connected` | `bridge_platform`: `slack` · `outcome`: `failure` · `failure_reason`: `none` / `unauthenticated` / `forbidden` / `invalid` / `error` |-| `bridge_disconnected` | `bridge_platform`: `mattermost` · `outcome` |+| `bridge_connected` | `bridge`: `collaboration` · `bridge_platform`: `slack` · `outcome`: `failure` · `failure_reason`: `none` / `unauthenticated` / `forbidden` / `invalid` / `error` |+| `bridge_disconnected` | `bridge`: `collaboration` · `bridge_platform`: `mattermost` · `outcome` || `bridge_identity_claimed` | `bridge_platform` · `outcome` || `room_created` | `server_kind`: `local` · `bridge_platform`: `slack` · `agent_count`: `3` · `has_instructions`: `true` · `outcome` · `failure_reason`: `none` / `unauthenticated` / `bridge_unavailable` / `invalid` / `unreachable` / `error` || `room_deleted` | `server_kind` · `outcome` |diff --git a/docs/session-activity-handoff.md b/docs/session-activity-handoff.mdindex 014c4e9d3..3958c1673 100644--- a/docs/session-activity-handoff.md+++ b/docs/session-activity-handoff.md@@ -29,7 +29,7 @@ storm. The database itself stays mostly idle.`NOTIFY` triggers carrying the row, fanned out in-process to subscribers(agent stream, bridges). Same mechanism as room messages.- **Every messaging platform** renders the same neutral model through- `CollaborationAdapter` (`post_rich` / `update_rich` / `find_request_card`).+ `PlatformAdapter` (`post_rich` / `update_rich` / `find_request_card`).- **Who may answer an approval = who may address the agent** (the agent'saddressing policy, judged in the request's room; owner only when no room).@@ -78,7 +78,7 @@ The session status line reuses the existing `agent_runtime_states` table`SnapshotRequest`/`RequestCard`, so every platform draws it unchanged(answerer shown as `DecidedBy`, with the platform handle when theyanswered on this bridge).- - `session_activity/bridge_publisher.py` (`SessionActivityBridgePublisher`):+ - `session_activity/publisher.py` (`AgentSessionActivityPublisher`):one per bridge whose adapter `publishes_sdk_sessions`, subscribed to thelistener for the bridge's tenant, with its own queue and task. Keys arecoalesced while queued and handled by reading the rows as they are now.@@ -94,13 +94,13 @@ The session status line reuses the existing `agent_runtime_states` table- `session_activity/bridge_answers.py` (`ApprovalAnswers`): a press (token+ option id or position) or typed answer (`A3 yes`, `A3 2`, bare yes/noas the first reply to the card) → `answer_approval(PlatformPerson(mxid))`;- refusals reach the person via `tell_actor`. `BridgeCore` asks it first+ refusals reach the person via `tell_actor`. `CollaborationCore` asks it firstand falls through to the old path when it returns None. The typed-handlegrammar accepts `A` as well as `R`.- Transition: `SessionPublisher.publish_pending` skips any session thathas rows in `approval_requests` or `session_activity_events`, so a hostreporting both ways does not get every card twice.- - Wiring: `main.py` → `CollaborationBridgeLifecycleService` → `BridgeCore`+ - Wiring: `main.py` → `CollaborationBridgeLifecycleService` → `CollaborationCore`(`session_activity_listener`, `session_activity_service`).- Not done: taking answered cards off the platform(`removes_answered_cards`), and the unconfirmed-card notice the old path@@ -180,7 +180,7 @@ Compatibility with deployed Consoles is waived (owner's call).here, else the latest assignment in its journal). The host builds roomprompts itself (`room-prompt.ts`), fetches room attachments, reportsactivity and applies approval outcomes. Switch keeps session placement in- memory only (`ConnectionRegistry.place_session` / `session_room` /+ memory only (`AgentConnectionRegistry.place_session` / `session_room` /`session_in_room` / `placements`), set by `connect_to_room`, and tagsdelivered events with the placed session's id.4. `990fe3c9`: presence and occupancy from the registry only; room controls@@ -480,7 +480,7 @@ declares 5 until it takes `room_released`):- `stream.py` no longer tags events. `connect_to_room` still calls`place_session`, now with the caller's connection id (or transport session)as the placement's owner, and still claims the room with takeover.-- `ConnectionRegistry.replace_placements(conn, placements)` records each+- `AgentConnectionRegistry.replace_placements(conn, placements)` records eachplacement against the connection, unplaces the connection's sessions itomits and releases their rooms, claims every named room with takeover, andreturns the `Released(connection_id, room_id, session_id)` entries for otherdiff --git a/scripts/sync_docs.py b/scripts/sync_docs.pyindex a1419ad66..5fe2ab55e 100644--- a/scripts/sync_docs.py+++ b/scripts/sync_docs.py@@ -20,8 +20,8 @@ import tempfilefrom pathlib import PathDOCS_REPO_URL = "https://github.com/sandbox-quantum/docs"-PRODUCT = "Switch"-SOURCE_PREFIX = "flintai/switch/"+PRODUCT = "Switch Rooms"+SOURCE_PREFIX = "switch-rooms/"SITE_BASE = "https://docs.flintai.dev"# Components whose body is kept and whose wrapper is dropped.