Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat(agents): let agents discover references across the instance

raullopez-sandbox6314f7e8c6f7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b16b11d21..6b96116a3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -56,6 +56,14 @@ version of their own to them without also giving them a release of their own.
and `origin` (`builtin` or `user`). A type's visibility gates who may *pick*
it, never delivery of its instructions for a reference already attached to a
room — the attachment is the grant.
+- **`list_all_references` lets an agent discover references across the whole
+ instance.** Until now an agent only saw the references attached to its
+ current room. The result is scoped to what the agent's owner may read.
+ Three optional filters narrow it — `name_contains`, `type` and `owner_name`
+ — and they are ANDed. Each row carries the reference's metadata but never
+ its `value`. When the caller is connected to exactly one room, each row also
+ reports `attached_to_current_room`. An agent can therefore find a reference
+ and attach it in the same turn.
#### Changed
- **A reference value must now carry at least one URL.** An empty `urls` list
diff --git a/CLAUDE.md b/CLAUDE.md
index c67311c24..3614396f0 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -171,8 +171,9 @@ commands, room workflow, or anything an agent-facing client needs to know:
`connectors/codex-plugin/skills/switch/SKILL.md` *and*
`connectors/opencode-plugin/skills/switch/SKILL.md` so the documented workflow
matches actual behavior on every host.
- `core/tests/switch_core/bridges/agent/test_mcp_tool_surface.py` asserts the
- count, so it fails rather than letting a host quietly go undocumented.
+ `core/tests/switch_core/bridges/agent/test_mcp_tool_surface.py` compares the
+ three `## Tool index` sections against each other and against the tools the
+ server actually registers, so a host left undocumented fails there.
- **Diff the skills against each other after editing.** They are deliberately not identical
(host-specific wording for tool namespacing, event delivery, attachments, and
MCP registration), so diff them to confirm
diff --git a/connectors/claude-code-plugin/skills/switch/SKILL.md b/connectors/claude-code-plugin/skills/switch/SKILL.md
index 9f0e65b14..f249e2be1 100644
--- a/connectors/claude-code-plugin/skills/switch/SKILL.md
+++ b/connectors/claude-code-plugin/skills/switch/SKILL.md
@@ -547,6 +547,18 @@ it was set in.
`read_visibility` is `"private"`). The reference is owned by your agent's
user. Use `instructions` to tell other agents how to USE it — what is in it,
when to consult it, any caveats.
+- **`list_all_references`** — every Reference on this instance your agent's
+ owner can read: their own, plus every reference with `read_visibility`
+ `"public"` (an admin owner sees all of them). This is how you find the
+ `reference_id` to hand to `attach_reference_to_room`. Optional
+ `name_contains` (case-insensitive substring of the name), `type` and
+ `owner_name` (exact) filters are ANDed together; omit one and it is ignored.
+ It needs no room connection. It does NOT return `value` — this is discovery,
+ so attach the reference and call `list_references` to read its `value`. When
+ the session has exactly one current room, each entry also carries
+ `attached_to_current_room`: false means you still need to attach it. That key
+ is absent when the session has no current room or spans several, so a missing
+ key never means "not attached".
- **`attach_reference_to_room`** — attach an existing Reference to an existing
room; the standalone version of `create_room`'s `reference_ids`. Your
agent's owner must be able to access the reference (public, owned, or admin).
@@ -746,6 +758,7 @@ failure-mode tools are covered in the sections just above.
- `update_room` — change an existing room, including its aliases.
- `invite_agent_to_room` — add an agent to an existing room by name.
- `list_references` — re-fetch the room's references, documents and packages.
+- `list_all_references` — every reference your owner can read, instance-wide.
- `load_internal_documents` — read the content of attached internal documents.
- `create_room_document` — author a document scoped to the connected room.
- `update_room_document` — change a document you created.
diff --git a/connectors/codex-plugin/skills/switch/SKILL.md b/connectors/codex-plugin/skills/switch/SKILL.md
index dada7356a..64ffa6809 100644
--- a/connectors/codex-plugin/skills/switch/SKILL.md
+++ b/connectors/codex-plugin/skills/switch/SKILL.md
@@ -545,6 +545,18 @@ it was set in.
`read_visibility` is `"private"`). The reference is owned by your agent's
user. Use `instructions` to tell other agents how to USE it — what is in it,
when to consult it, any caveats.
+- **`list_all_references`** — every Reference on this instance your agent's
+ owner can read: their own, plus every reference with `read_visibility`
+ `"public"` (an admin owner sees all of them). This is how you find the
+ `reference_id` to hand to `attach_reference_to_room`. Optional
+ `name_contains` (case-insensitive substring of the name), `type` and
+ `owner_name` (exact) filters are ANDed together; omit one and it is ignored.
+ It needs no room connection. It does NOT return `value` — this is discovery,
+ so attach the reference and call `list_references` to read its `value`. When
+ the session has exactly one current room, each entry also carries
+ `attached_to_current_room`: false means you still need to attach it. That key
+ is absent when the session has no current room or spans several, so a missing
+ key never means "not attached".
- **`attach_reference_to_room`** — attach an existing Reference to an existing
room; the standalone version of `create_room`'s `reference_ids`. Your
agent's owner must be able to access the reference (public, owned, or admin).
@@ -743,6 +755,7 @@ failure-mode tools are covered in the sections just above.
- `update_room` — change an existing room, including its aliases.
- `invite_agent_to_room` — add an agent to an existing room by name.
- `list_references` — re-fetch the room's references, documents and packages.
+- `list_all_references` — every reference your owner can read, instance-wide.
- `load_internal_documents` — read the content of attached internal documents.
- `create_room_document` — author a document scoped to the connected room.
- `update_room_document` — change a document you created.
diff --git a/connectors/opencode-plugin/skills/switch/SKILL.md b/connectors/opencode-plugin/skills/switch/SKILL.md
index 8a31a11e8..6ba058eae 100644
--- a/connectors/opencode-plugin/skills/switch/SKILL.md
+++ b/connectors/opencode-plugin/skills/switch/SKILL.md
@@ -553,6 +553,18 @@ it was set in.
`read_visibility` is `"private"`). The reference is owned by your agent's
user. Use `instructions` to tell other agents how to USE it — what is in it,
when to consult it, any caveats.
+- **`list_all_references`** — every Reference on this instance your agent's
+ owner can read: their own, plus every reference with `read_visibility`
+ `"public"` (an admin owner sees all of them). This is how you find the
+ `reference_id` to hand to `attach_reference_to_room`. Optional
+ `name_contains` (case-insensitive substring of the name), `type` and
+ `owner_name` (exact) filters are ANDed together; omit one and it is ignored.
+ It needs no room connection. It does NOT return `value` — this is discovery,
+ so attach the reference and call `list_references` to read its `value`. When
+ the session has exactly one current room, each entry also carries
+ `attached_to_current_room`: false means you still need to attach it. That key
+ is absent when the session has no current room or spans several, so a missing
+ key never means "not attached".
- **`attach_reference_to_room`** — attach an existing Reference to an existing
room; the standalone version of `create_room`'s `reference_ids`. Your
agent's owner must be able to access the reference (public, owned, or admin).
@@ -746,6 +758,7 @@ failure-mode tools are covered in the sections just above.
- `update_room` — change an existing room, including its aliases.
- `invite_agent_to_room` — add an agent to an existing room by name.
- `list_references` — re-fetch the room's references, documents and packages.
+- `list_all_references` — every reference your owner can read, instance-wide.
- `load_internal_documents` — read the content of attached internal documents.
- `create_room_document` — author a document scoped to the connected room.
- `update_room_document` — change a document you created.
diff --git a/console/packages/plugins/src/agents/impl/opencode/skill-file.ts b/console/packages/plugins/src/agents/impl/opencode/skill-file.ts
index 6ddf9dd9c..09dbfc2f1 100644
--- a/console/packages/plugins/src/agents/impl/opencode/skill-file.ts
+++ b/console/packages/plugins/src/agents/impl/opencode/skill-file.ts
@@ -561,6 +561,18 @@ it was set in.
\`read_visibility\` is \`"private"\`). The reference is owned by your agent's
user. Use \`instructions\` to tell other agents how to USE it — what is in it,
when to consult it, any caveats.
+- **\`list_all_references\`** — every Reference on this instance your agent's
+ owner can read: their own, plus every reference with \`read_visibility\`
+ \`"public"\` (an admin owner sees all of them). This is how you find the
+ \`reference_id\` to hand to \`attach_reference_to_room\`. Optional
+ \`name_contains\` (case-insensitive substring of the name), \`type\` and
+ \`owner_name\` (exact) filters are ANDed together; omit one and it is ignored.
+ It needs no room connection. It does NOT return \`value\` — this is discovery,
+ so attach the reference and call \`list_references\` to read its \`value\`. When
+ the session has exactly one current room, each entry also carries
+ \`attached_to_current_room\`: false means you still need to attach it. That key
+ is absent when the session has no current room or spans several, so a missing
+ key never means "not attached".
- **\`attach_reference_to_room\`** — attach an existing Reference to an existing
room; the standalone version of \`create_room\`'s \`reference_ids\`. Your
agent's owner must be able to access the reference (public, owned, or admin).
@@ -754,6 +766,7 @@ failure-mode tools are covered in the sections just above.
- \`update_room\` — change an existing room, including its aliases.
- \`invite_agent_to_room\` — add an agent to an existing room by name.
- \`list_references\` — re-fetch the room's references, documents and packages.
+- \`list_all_references\` — every reference your owner can read, instance-wide.
- \`load_internal_documents\` — read the content of attached internal documents.
- \`create_room_document\` — author a document scoped to the connected room.
- \`update_room_document\` — change a document you created.
diff --git a/core/switch_core/bridges/agent/operations/context.py b/core/switch_core/bridges/agent/operations/context.py
index c0fded0f0..9488046e2 100644
--- a/core/switch_core/bridges/agent/operations/context.py
+++ b/core/switch_core/bridges/agent/operations/context.py
@@ -58,8 +58,8 @@ def session_key() -> str | None:
return bound.session_key if bound is not None else None
-async def require_connected_room() -> str:
- """The room this caller is bound to, or a clear error saying it is not.
+async def _bound_rooms() -> set[str]:
+ """The rooms this caller is bound to, empty when it is bound to none.
The live connection is asked first: a connection that has claimed a room is
in it, whether or not anything was ever written to a table. The table is
@@ -68,21 +68,39 @@ async def require_connected_room() -> str:
"""
key = session_key()
if not key:
- raise ValueError("Not connected to a room. Call connect_to_room first.")
+ return set()
protocol = get_protocol()
connection = protocol.connections.get(key)
if connection is not None and connection.rooms:
- if len(connection.rooms) > 1:
- raise ValueError(
- "This connection covers several rooms; the operation needs one "
- "— pass the room explicitly or use a single-room connection."
- )
- return next(iter(connection.rooms))
+ return set(connection.rooms)
async with protocol.session_factory() as db:
result = await protocol.agent_session_store.get_connected_room(db, key)
if result is None:
- raise ValueError("Not connected to a room. Call connect_to_room first.")
+ return set()
_, room_id = result
- return room_id
+ return {room_id}
+
+
+async def require_connected_room() -> str:
+ """The room this caller is bound to, or a clear error saying it is not."""
+ rooms = await _bound_rooms()
+ if not rooms:
+ raise ValueError("Not connected to a room. Call connect_to_room first.")
+ if len(rooms) > 1:
+ raise ValueError(
+ "This connection covers several rooms; the operation needs one "
+ "— pass the room explicitly or use a single-room connection."
+ )
+ return next(iter(rooms))
+
+
+async def connected_room() -> str | None:
+ """The room this caller is bound to, or None when there is not exactly one.
+
+ The non-raising counterpart of `require_connected_room`, for operations
+ that work without a room but say something extra when there is one.
+ """
+ rooms = await _bound_rooms()
+ return next(iter(rooms)) if len(rooms) == 1 else None
diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.py
index 3119936d0..b4301588b 100644
--- a/core/switch_core/bridges/agent/operations/definitions.py
+++ b/core/switch_core/bridges/agent/operations/definitions.py
@@ -16,6 +16,7 @@ from typing import Any
from switch_core.bridges.agent.api.handlers import parse_timestamp_ms
from switch_core.bridges.agent.operations.context import (
+ connected_room,
get_agent_id,
get_protocol,
require_connected_room,
@@ -156,20 +157,7 @@ async def list_rooms(include_archived: bool = False) -> list[dict[str, Any]]:
agent_id = get_agent_id()
protocol = get_protocol()
- connected_room_id: str | None = None
- key = session_key()
- if key:
- # Ask the live connection first and the binding row only for callers
- # that have none, matching how require_connected_room resolves it — a
- # connection carries its own rooms and no row is written for it.
- connection = protocol.connections.get(key)
- if connection is not None and len(connection.rooms) == 1:
- connected_room_id = next(iter(connection.rooms))
- elif connection is None:
- async with protocol.session_factory() as db:
- row = await protocol.agent_session_store.get_connected_room(db, key)
- if row is not None:
- _, connected_room_id = row
+ connected_room_id = await connected_room()
rooms = await protocol.list_rooms(agent_id, include_archived=include_archived)
return [
@@ -1308,6 +1296,50 @@ async def attach_reference_to_room(room_id: str, reference_id: str) -> dict[str,
return {"ok": True}
+@operation
+async def list_all_references(
+ name_contains: str | None = None,
+ type: str | None = None,
+ owner_name: str | None = None,
+) -> list[dict[str, Any]]:
+ """List every reference on this Switch instance your owner can read.
+
+ Unlike `list_references` (which is scoped to the connected room and shows
+ what is already attached there), this searches the whole instance, so it is
+ how you find the `reference_id` to pass to `attach_reference_to_room`. It
+ needs no room connection. Use the optional filters to narrow the result;
+ they are ANDed together, and omitting one ignores it.
+
+ Args:
+ name_contains: Case-insensitive substring to match against reference
+ names.
+ type: Return only references of this exact type slug (e.g. "github").
+ See `list_reference_types` for the types in use.
+ owner_name: Return only references owned by the user with this exact
+ name.
+
+ Returns:
+ A list of {id, type, name, description, owner_name, read_visibility,
+ write_visibility, created_at} dicts, newest first. When this session has
+ exactly one current room, each entry also carries
+ `attached_to_current_room` — false means you still need to attach it;
+ the key is absent when the session has no current room or spans several,
+ so a missing key never means "not attached".
+ `value` (the URLs / ids a reference points at) is deliberately omitted:
+ this is discovery. Attach the reference and call `list_references` to
+ get its `value`.
+ """
+ agent_id = get_agent_id()
+ protocol = get_protocol()
+ return await protocol.list_all_references(
+ agent_id,
+ name_contains=name_contains,
+ type=type,
+ owner_name=owner_name,
+ current_room_id=await connected_room(),
+ )
+
+
@operation
async def link_rooms(
source_room_id: str, target_room_id: str, label: str
diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.py
index 476e47b19..07ef64945 100644
--- a/core/switch_core/bridges/agent/protocol/service.py
+++ b/core/switch_core/bridges/agent/protocol/service.py
@@ -2750,6 +2750,57 @@ class ProtocolService:
)
await session.commit()
+ async def list_all_references(
+ self,
+ agent_id: str,
+ name_contains: str | None,
+ type: str | None,
+ owner_name: str | None,
+ current_room_id: str | None,
+ ) -> list[dict[str, Any]]:
+ """List the references the agent's owner may read, across the instance.
+
+ Filters are ANDed; a None filter is ignored. `owner_name` is matched
+ against the resolved owner name exactly, like `list_agents`, so a name
+ no user carries yields an empty list. Rows carry no `value`: this is
+ discovery, and the value arrives via `list_references` once attached.
+
+ When `current_room_id` is given, each row reports whether it is already
+ attached to that room; when it is None the key is left out entirely, so
+ an absent key never reads as "not attached".
+ """
+ async with self.session_factory() as session:
+ _agent, owner_id, owner_is_admin = await self._resolve_acting_identity(
+ session, agent_id
+ )
+ if owner_id is None:
+ raise ValueError(
+ f"Agent {agent_id} has no owner_id and cannot list references"
+ )
+ pairs = await self.resource_service.list_references_with_owner_names(
+ session,
+ owner_id,
+ is_admin=owner_is_admin,
+ name_contains=name_contains,
+ type=type,
+ owner_name=owner_name,
+ )
+ attached_ids: set[str] | None = None
+ if current_room_id is not None:
+ attached_ids = await self.resource_service.list_room_reference_ids(
+ session, current_room_id
+ )
+ return [
+ self.resource_service.reference_to_summary(
+ ref,
+ name,
+ attached_to_current_room=None
+ if attached_ids is None
+ else ref.id in attached_ids,
+ )
+ for ref, name in pairs
+ ]
+
async def link_rooms(
self,
agent_id: str,
diff --git a/core/switch_core/bridges/resource/service.py b/core/switch_core/bridges/resource/service.py
index d5f5bac38..3b685466f 100644
--- a/core/switch_core/bridges/resource/service.py
+++ b/core/switch_core/bridges/resource/service.py
@@ -112,6 +112,36 @@ class ResourceService:
"value": ref.value,
}
+ @staticmethod
+ def reference_to_summary(
+ ref: Reference, owner_name: str, *, attached_to_current_room: bool | None
+ ) -> dict[str, Any]:
+ """Discovery shape: identity and visibility, with neither the `value`
+ nor the `instructions` for using it — enough to decide whether to attach
+ a reference, not enough to use one.
+
+ Deliberately not `_reference_to_payload`, which exists so an agent can
+ *use* a reference it already has attached and therefore carries the
+ URLs/ids inline.
+
+ `attached_to_current_room` is emitted only when the caller passes a
+ value; None omits the key entirely, so an absent key never reads as
+ "not attached".
+ """
+ summary: dict[str, Any] = {
+ "id": ref.id,
+ "type": ref.type,
+ "name": ref.name,
+ "description": ref.description,
+ "owner_name": owner_name,
+ "read_visibility": ref.read_visibility,
+ "write_visibility": ref.write_visibility,
+ "created_at": str(ref.created_at),
+ }
+ if attached_to_current_room is not None:
+ summary["attached_to_current_room"] = attached_to_current_room
+ return summary
+
@staticmethod
def _document_metadata(doc: Document) -> dict[str, Any]:
return {
@@ -498,8 +528,34 @@ class ResourceService:
async def list_references_for_user(
self, session: AsyncSession, user_id: str
) -> list[Reference]:
+ """The user's own references plus the public ones, with their `value`.
+
+ Owner+public with no admin bypass, deliberately: every row carries the
+ reference's `value`, so an admin bypass here would hand out other
+ users' secrets. The single-resource read keeps the bypass.
+ """
return await self._references.list_for_user(session, user_id)
+ async def list_references_with_owner_names(
+ self,
+ session: AsyncSession,
+ user_id: str,
+ *,
+ is_admin: bool,
+ name_contains: str | None = None,
+ type: str | None = None,
+ owner_name: str | None = None,
+ ) -> list[tuple[Reference, str]]:
+ """Readable references paired with their owner's name, for discovery."""
+ return await self._references.list_readable_with_owner_names(
+ session,
+ user_id,
+ is_admin=is_admin,
+ name_contains=name_contains,
+ type=type,
+ owner_name=owner_name,
+ )
+
async def update_reference(
self,
session: AsyncSession,
@@ -577,6 +633,11 @@ class ResourceService:
) -> list[Reference]:
return await self._references.list_for_room(session, room_id)
+ async def list_room_reference_ids(
+ self, session: AsyncSession, room_id: str
+ ) -> set[str]:
+ return await self._references.list_ids_for_room(session, room_id)
+
async def get_reference_attached_counts(
self, session: AsyncSession, reference_ids: list[str]
) -> dict[str, int]:
diff --git a/core/switch_core/db/stores/reference_store.py b/core/switch_core/db/stores/reference_store.py
index a4a487387..a2a891a68 100644
--- a/core/switch_core/db/stores/reference_store.py
+++ b/core/switch_core/db/stores/reference_store.py
@@ -1,7 +1,19 @@
-from sqlalchemy import delete, func, insert, or_, select
+from sqlalchemy import delete, func, or_, select
+from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.ext.asyncio import AsyncSession
-from switch_core.db.models import Reference, Room, room_references
+from switch_core.db.models import Reference, Room, User, room_references
+
+_LIKE_ESCAPE = "\\"
+
+
+def _like_needle(text: str) -> str:
+ escaped = (
+ text.replace(_LIKE_ESCAPE, _LIKE_ESCAPE * 2)
+ .replace("%", f"{_LIKE_ESCAPE}%")
+ .replace("_", f"{_LIKE_ESCAPE}_")
+ )
+ return f"%{escaped}%"
class ReferenceStore:
@@ -27,6 +39,44 @@ class ReferenceStore:
)
return list(result.scalars().all())
+ async def list_readable_with_owner_names(
+ self,
+ session: AsyncSession,
+ user_id: str,
+ *,
+ is_admin: bool,
+ name_contains: str | None = None,
+ type: str | None = None,
+ owner_name: str | None = None,
+ ) -> list[tuple[Reference, str]]:
+ """Return (reference, owner_name) pairs the user may read, newest first.
+
+ An admin reads every reference; anyone else reads the ones they own
+ plus the publicly readable ones. The optional filters are ANDed on top
+ of that; a None filter is ignored. `name_contains` is a
+ case-insensitive substring match, `type` and `owner_name` are exact.
+ """
+ query = select(Reference, User.name).join(User, Reference.owner_id == User.id)
+ if not is_admin:
+ query = query.where(
+ or_(
+ Reference.owner_id == user_id,
+ Reference.read_visibility == "public",
+ )
+ )
+ if name_contains is not None:
+ query = query.where(
+ Reference.name.ilike(_like_needle(name_contains), escape=_LIKE_ESCAPE)
+ )
+ if type is not None:
+ query = query.where(Reference.type == type)
+ if owner_name is not None:
+ query = query.where(User.name == owner_name)
+ result = await session.execute(
+ query.order_by(Reference.created_at.desc(), Reference.id.asc())
+ )
+ return [(ref, name) for ref, name in result.all()]
+
async def update_fields(
self,
session: AsyncSession,
@@ -79,8 +129,17 @@ class ReferenceStore:
async def attach_to_room(
self, session: AsyncSession, room_id: str, reference_id: str
) -> None:
+ """Attach a reference to a room. Idempotent: attaching one that is
+ already attached is a no-op, not a primary-key violation."""
await session.execute(
- insert(room_references).values(room_id=room_id, reference_id=reference_id)
+ pg_insert(room_references)
+ .values(room_id=room_id, reference_id=reference_id)
+ .on_conflict_do_nothing(
+ index_elements=[
+ room_references.c.room_id,
+ room_references.c.reference_id,
+ ]
+ )
)
await session.flush()
@@ -108,6 +167,15 @@ class ReferenceStore:
)
return list(result.scalars().all())
+ async def list_ids_for_room(self, session: AsyncSession, room_id: str) -> set[str]:
+ """Return the ids of the references attached to a room."""
+ result = await session.execute(
+ select(room_references.c.reference_id).where(
+ room_references.c.room_id == room_id
+ )
+ )
+ return set(result.scalars().all())
+
async def is_attached_to_room(
self, session: AsyncSession, room_id: str, reference_id: str
) -> bool:
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.py
new file mode 100644
index 000000000..592a1a080
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/protocol/test_list_all_references.py
@@ -0,0 +1,274 @@
+"""`ProtocolService.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
+reference) and the shape of the rows it hands an agent, so this runs the real
+`ResourceService`/`ReferenceStore` against real PostgreSQL. Only the agent
+lookup is faked: building an `Agent` row means dragging in a Client and an
+ApiKey, and none of that participates in the behaviour under test.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from 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.resource.service import ResourceService
+from switch_core.db.models import Reference, Room, User
+from switch_core.db.stores.document_store import DocumentStore
+from switch_core.db.stores.package_store import PackageStore
+from switch_core.db.stores.reference_store import ReferenceStore
+from switch_core.db.stores.reference_type_store import ReferenceTypeStore
+from switch_core.db.stores.room_link_store import RoomLinkStore
+
+T_OLD = datetime(2024, 1, 1, 12, 0, tzinfo=UTC)
+
+
+class _FakeAgentStore:
+ """Maps agent_id -> owner_id without needing the Client/ApiKey rows."""
+
+ def __init__(self, owners: dict[str, str | None]) -> None:
+ self._owners = owners
+
+ async def get(self, _session: Any, agent_id: str) -> Any:
+ if agent_id not in self._owners:
+ return None
+ return SimpleNamespace(id=agent_id, owner_id=self._owners[agent_id])
+
+
+def _build_service(
+ session_factory: async_sessionmaker[AsyncSession],
+ owners: dict[str, str | None],
+) -> ProtocolService:
+ svc = object.__new__(ProtocolService)
+ svc.connections = ConnectionRegistry()
+ svc.session_factory = session_factory # type: ignore[assignment]
+ svc.agent_store = _FakeAgentStore(owners) # type: ignore[assignment]
+ svc.resource_service = ResourceService(
+ reference_store=ReferenceStore(),
+ reference_type_store=ReferenceTypeStore(),
+ document_store=DocumentStore(),
+ package_store=PackageStore(),
+ room_link_store=RoomLinkStore(),
+ session_factory=session_factory,
+ )
+ return svc
+
+
+async def _make_user(session: AsyncSession, *, name: str, role: str = "user") -> User:
+ user = User(name=name, email=f"{name}@example.invalid", role=role)
+ session.add(user)
+ await session.flush()
+ return user
+
+
+async def _make_reference(
+ session: AsyncSession,
+ *,
+ owner: User,
+ name: str,
+ type: str = "github",
+ read_visibility: str = "private",
+ created_at: datetime = T_OLD,
+) -> Reference:
+ ref = Reference(
+ owner_id=owner.id,
+ read_visibility=read_visibility,
+ write_visibility="private" if read_visibility == "private" else "public",
+ type=type,
+ name=name,
+ description=f"{name} description",
+ instructions=f"use {name}",
+ value={"token": "placeholder"},
+ created_at=created_at,
+ )
+ session.add(ref)
+ await session.flush()
+ return ref
+
+
+class TestListAllReferencesAuthz:
+ async def test_non_admin_owner_never_sees_a_strangers_private_reference(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ alice = await _make_user(session, name="alice")
+ bob = await _make_user(session, name="bob")
+ own = await _make_reference(session, owner=alice, name="alice-private")
+ shared = await _make_reference(
+ session, owner=bob, name="bob-public", read_visibility="public"
+ )
+ await _make_reference(session, owner=bob, name="bob-private")
+ await session.commit()
+
+ svc = _build_service(session_factory, {"agent-1": alice.id})
+
+ rows = await svc.list_all_references("agent-1", None, None, None, None)
+
+ assert {r["id"] for r in rows} == {own.id, shared.id}
+
+ async def test_admin_owner_sees_a_strangers_private_reference(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ alice = await _make_user(session, name="alice")
+ root = await _make_user(session, name="root", role="admin")
+ secret = await _make_reference(session, owner=alice, name="alice-private")
+ await session.commit()
+
+ svc = _build_service(session_factory, {"agent-root": root.id})
+
+ rows = await svc.list_all_references("agent-root", None, None, None, None)
+
+ assert [r["id"] for r in rows] == [secret.id]
+ assert rows[0]["owner_name"] == "alice"
+
+ @pytest.mark.parametrize(
+ ("owners", "agent_id", "match"),
+ [
+ ({"agent-orphan": None}, "agent-orphan", "has no owner_id"),
+ ({}, "nope", "Unknown agent"),
+ ],
+ ids=["ownerless-agent", "unknown-agent"],
+ )
+ async def test_an_agent_without_a_principal_raises(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ owners: dict[str, str | None],
+ agent_id: str,
+ match: str,
+ ) -> None:
+ """An agent that resolves to no owner has no principal to read as, so
+ the search must fail loud.
+
+ Returning `[]` would read as "there are no references", which is the
+ silent-degradation the project rules forbid.
+ """
+ svc = _build_service(session_factory, owners)
+
+ with pytest.raises(ValueError, match=match):
+ await svc.list_all_references(agent_id, None, None, None, None)
+
+
+class TestListAllReferencesShape:
+ async def test_row_carries_the_metadata_but_never_the_value(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """`value` holds the secrets/urls; discovery must not leak it."""
+ async with session_factory() as session:
+ alice = await _make_user(session, name="alice")
+ ref = await _make_reference(session, owner=alice, name="deploy-key")
+ await session.commit()
+
+ svc = _build_service(session_factory, {"agent-1": alice.id})
+
+ rows = await svc.list_all_references("agent-1", None, None, None, None)
+
+ assert len(rows) == 1
+ assert set(rows[0]) == {
+ "id",
+ "type",
+ "name",
+ "description",
+ "owner_name",
+ "read_visibility",
+ "write_visibility",
+ "created_at",
+ }
+ assert rows[0]["id"] == ref.id
+ assert rows[0]["name"] == "deploy-key"
+ assert rows[0]["owner_name"] == "alice"
+ assert rows[0]["read_visibility"] == "private"
+
+ async def test_filters_narrow_the_result(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ alice = await _make_user(session, name="alice")
+ wanted = await _make_reference(
+ session, owner=alice, name="prod-repo", type="github"
+ )
+ await _make_reference(session, owner=alice, name="prod-board", type="jira")
+ await _make_reference(
+ session, owner=alice, name="staging-repo", type="github"
+ )
+ await session.commit()
+
+ svc = _build_service(session_factory, {"agent-1": alice.id})
+
+ rows = await svc.list_all_references("agent-1", "PROD", "github", None, None)
+
+ assert [r["id"] for r in rows] == [wanted.id]
+
+ async def test_owner_name_filter_is_exact_and_unknown_names_yield_nothing(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ alice = await _make_user(session, name="alice")
+ bob = await _make_user(session, name="bob")
+ bobs = await _make_reference(
+ session, owner=bob, name="bob-public", read_visibility="public"
+ )
+ await _make_reference(session, owner=alice, name="alice-private")
+ await session.commit()
+
+ svc = _build_service(session_factory, {"agent-1": alice.id})
+
+ assert [
+ r["id"]
+ for r in await svc.list_all_references("agent-1", None, None, "bob", None)
+ ] == [bobs.id]
+ assert (
+ await svc.list_all_references("agent-1", None, None, "nobody", None) == []
+ )
+
+
+class TestAttachedToCurrentRoom:
+ async def test_key_is_absent_when_there_is_no_current_room(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """An absent key must never be readable as "not attached"."""
+ async with session_factory() as session:
+ alice = await _make_user(session, name="alice")
+ await _make_reference(session, owner=alice, name="ref")
+ await session.commit()
+
+ svc = _build_service(session_factory, {"agent-1": alice.id})
+
+ rows = await svc.list_all_references("agent-1", None, None, None, None)
+
+ assert "attached_to_current_room" not in rows[0]
+
+ async def test_reports_true_only_for_the_references_in_that_room(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ alice = await _make_user(session, name="alice")
+ 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"
+ )
+ other = Room(matrix_room_id="!other:test", name="Other", description="room")
+ session.add_all([room, other])
+ await session.flush()
+ store = ReferenceStore()
+ await store.attach_to_room(session, room.id, attached.id)
+ # Attached elsewhere: must still read as false for the current room.
+ await store.attach_to_room(session, other.id, loose.id)
+ await session.commit()
+ room_id = room.id
+
+ svc = _build_service(session_factory, {"agent-1": alice.id})
+
+ rows = await svc.list_all_references("agent-1", None, None, None, room_id)
+
+ by_id = {r["id"]: r for r in rows}
+ assert by_id[attached.id]["attached_to_current_room"] is True
+ assert by_id[loose.id]["attached_to_current_room"] is False
diff --git a/core/tests/switch_core/bridges/agent/test_mcp_tool_surface.py b/core/tests/switch_core/bridges/agent/test_mcp_tool_surface.py
index e72182bec..797749bad 100644
--- a/core/tests/switch_core/bridges/agent/test_mcp_tool_surface.py
+++ b/core/tests/switch_core/bridges/agent/test_mcp_tool_surface.py
@@ -71,6 +71,7 @@ async def test_documented_tools_exist(tool_names: set[str]) -> None:
"list_reference_types",
"create_reference",
"attach_reference_to_room",
+ "list_all_references",
"link_rooms",
"unlink_rooms",
"list_room_groups",
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.py
new file mode 100644
index 000000000..37c536a99
--- /dev/null
+++ b/core/tests/switch_core/db/stores/test_reference_store_listing.py
@@ -0,0 +1,437 @@
+"""`ReferenceStore.list_readable_with_owner_names` filtering/visibility/ordering,
+and the idempotent room attach that backs re-attaching an already-attached
+reference.
+
+Real PostgreSQL (per the project rule): `ilike ... escape`, the `created_at
+DESC, id ASC` tiebreak and `ON CONFLICT DO NOTHING` on the composite primary
+key are all database behaviours, and none of them would be exercised by a mock.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+
+import pytest
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import Reference, Room, User, room_references
+from switch_core.db.stores.reference_store import ReferenceStore
+
+# Fixed instants so ordering assertions do not depend on insertion timing.
+T_OLD = datetime(2024, 1, 1, 12, 0, tzinfo=UTC)
+T_MID = datetime(2024, 6, 1, 12, 0, tzinfo=UTC)
+T_NEW = datetime(2024, 9, 1, 12, 0, tzinfo=UTC)
+
+
+def store() -> ReferenceStore:
+ return ReferenceStore()
+
+
+async def _make_user(session: AsyncSession, *, name: str, role: str = "user") -> User:
+ user = User(name=name, email=f"{name}@example.invalid", role=role)
+ session.add(user)
+ await session.flush()
+ return user
+
+
+async def _make_reference(
+ session: AsyncSession,
+ *,
+ owner: User,
+ name: str,
+ type: str = "github",
+ read_visibility: str = "private",
+ created_at: datetime = T_MID,
+ reference_id: str | None = None,
+) -> Reference:
+ ref = Reference(
+ owner_id=owner.id,
+ read_visibility=read_visibility,
+ write_visibility="private" if read_visibility == "private" else "public",
+ type=type,
+ name=name,
+ description=f"{name} description",
+ instructions=f"use {name}",
+ value={"url": f"https://example.invalid/{name}"},
+ created_at=created_at,
+ )
+ if reference_id is not None:
+ ref.id = reference_id
+ session.add(ref)
+ await session.flush()
+ 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")
+ session.add(room)
+ await session.flush()
+ return room
+
+
+class TestListReadableFilters:
+ async def test_no_filters_returns_everything_readable(
+ self, store: ReferenceStore, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ alice = await _make_user(session, name="alice")
+ bob = await _make_user(session, name="bob")
+ mine = await _make_reference(session, owner=alice, name="mine")
+ shared = await _make_reference(
+ session, owner=bob, name="shared", read_visibility="public"
+ )
+ await _make_reference(session, owner=bob, name="bobs-secret")
+ await session.commit()
+
+ found = await store.list_readable_with_owner_names(
+ session, alice.id, is_admin=False
+ )
+
+ assert {ref.id for ref, _ in found} == {mine.id, shared.id}
+ assert {ref.id: owner for ref, owner in found} == {
+ mine.id: "alice",
+ shared.id: "bob",
+ }
+
+ async def test_name_contains_is_a_case_insensitive_literal_substring(
+ self, store: ReferenceStore, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """The needle is matched as text: folded for case, wrapped in `%…%`, and
+ with every LIKE metacharacter in it escaped to a literal.
+ """
+ names = [
+ "PROD Deploy Key",
+ "prod runbook",
+ "staging runbook",
+ "switch-payments-api",
+ "switch-rooms-api",
+ "100%-coverage",
+ "100 coverage",
+ "ci_token",
+ "ciXtoken",
+ "domain\\account",
+ "domain-account",
+ ]
+ cases: list[tuple[str, set[str]]] = [
+ # Case is folded on both sides of the comparison.
+ ("prod", {"PROD Deploy Key", "prod runbook"}),
+ ("PROD", {"PROD Deploy Key", "prod runbook"}),
+ # `%…%` wrapping: the needle is not anchored to the start of a name.
+ ("payment", {"switch-payments-api"}),
+ # `%` is a literal, not "any run of characters".
+ ("100%-", {"100%-coverage"}),
+ # `_` is a literal, not "any single character".
+ ("ci_token", {"ci_token"}),
+ # A `\` in the needle is a literal, not an escape of what follows.
+ ("domain\\account", {"domain\\account"}),
+ # An empty needle is a substring of every name, not an error.
+ ("", set(names)),
+ # An all-metacharacter needle is a search for those characters.
+ ("%", {"100%-coverage"}),
+ ("_", {"ci_token"}),
+ ("%%", set()),
+ ]
+ async with session_factory() as session:
+ alice = await _make_user(session, name="alice")
+ for name in names:
+ await _make_reference(session, owner=alice, name=name)
+ await session.commit()
+
+ for needle, expected in cases:
+ found = await store.list_readable_with_owner_names(
+ session, alice.id, is_admin=False, name_contains=needle
+ )
+ assert {ref.name for ref, _ in found} == expected, (
+ f"name_contains={needle!r}"
+ )
+
+ async def test_type_filter_is_an_exact_slug(
+ self, store: ReferenceStore, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ alice = await _make_user(session, name="alice")
+ gh = await _make_reference(session, owner=alice, name="repo", type="github")
+ await _make_reference(session, owner=alice, name="board", type="jira")
+ # Exact, not a substring: "git" must not match "github".
+ await session.commit()
+
+ found = await store.list_readable_with_owner_names(
+ session, alice.id, is_admin=False, type="github"
+ )
+ prefix = await store.list_readable_with_owner_names(
+ session, alice.id, is_admin=False, type="git"
+ )
+
+ assert [ref.id for ref, _ in found] == [gh.id]
+ assert prefix == []
+
+ async def test_owner_name_filter_is_exact_and_unknown_names_yield_nothing(
+ self, store: ReferenceStore, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ alice = await _make_user(session, name="alice")
+ bob = await _make_user(session, name="bob")
+ bobs = await _make_reference(
+ session, owner=bob, name="bob-public", read_visibility="public"
+ )
+ await _make_reference(session, owner=alice, name="alice-private")
+ await session.commit()
+
+ found = await store.list_readable_with_owner_names(
+ session, alice.id, is_admin=False, owner_name="bob"
+ )
+ prefix = await store.list_readable_with_owner_names(
+ session, alice.id, is_admin=False, owner_name="bo"
+ )
+ unknown = await store.list_readable_with_owner_names(
+ session, alice.id, is_admin=False, owner_name="nobody"
+ )
+
+ assert found == [(bobs, "bob")]
+ assert prefix == []
+ assert unknown == []
+
+ async def test_filters_are_anded(
+ self, store: ReferenceStore, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """A row matching one filter but not the other is excluded."""
+ async with session_factory() as session:
+ alice = await _make_user(session, name="alice")
+ both = await _make_reference(
+ session, owner=alice, name="deploy-key", type="github"
+ )
+ # Right name, wrong type.
+ await _make_reference(
+ session, owner=alice, name="deploy-key-jira", type="jira"
+ )
+ # Right type, wrong name.
+ await _make_reference(
+ session, owner=alice, name="read-token", type="github"
+ )
+ await session.commit()
+
+ found = await store.list_readable_with_owner_names(
+ session,
+ alice.id,
+ is_admin=False,
+ name_contains="deploy",
+ type="github",
+ )
+
+ assert [ref.id for ref, _ in found] == [both.id]
+
+
+class TestListReadableVisibility:
+ async def test_owner_sees_their_private_row_and_a_stranger_does_not(
+ self, store: ReferenceStore, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ alice = await _make_user(session, name="alice")
+ bob = await _make_user(session, name="bob")
+ secret = await _make_reference(
+ session, owner=alice, name="secret", read_visibility="private"
+ )
+ await session.commit()
+
+ mine = await store.list_readable_with_owner_names(
+ session, alice.id, is_admin=False
+ )
+ theirs = await store.list_readable_with_owner_names(
+ session, bob.id, is_admin=False
+ )
+
+ assert mine == [(secret, "alice")]
+ assert theirs == []
+
+ async def test_public_row_is_visible_to_everyone_paired_with_its_owner(
+ self, store: ReferenceStore, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """A reader who does not own the row still gets the owner's name."""
+ async with session_factory() as session:
+ alice = await _make_user(session, name="alice")
+ bob = await _make_user(session, name="bob")
+ shared = await _make_reference(
+ session, owner=bob, name="shared", read_visibility="public"
+ )
+ await session.commit()
+
+ for viewer in (alice, bob):
+ found = await store.list_readable_with_owner_names(
+ session, viewer.id, is_admin=False
+ )
+ assert found == [(shared, "bob")]
+
+ async def test_admin_sees_another_users_private_row(
+ self, store: ReferenceStore, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """`is_admin=True` drops the owner/visibility clause entirely."""
+ async with session_factory() as session:
+ alice = await _make_user(session, name="alice")
+ root = await _make_user(session, name="root", role="admin")
+ secret = await _make_reference(
+ session, owner=alice, name="secret", read_visibility="private"
+ )
+ await session.commit()
+
+ as_user = await store.list_readable_with_owner_names(
+ session, root.id, is_admin=False
+ )
+ as_admin = await store.list_readable_with_owner_names(
+ session, root.id, is_admin=True
+ )
+
+ assert as_user == []
+ assert as_admin == [(secret, "alice")]
+
+ async def test_admin_bypass_still_honours_the_other_filters(
+ self, store: ReferenceStore, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ alice = await _make_user(session, name="alice")
+ root = await _make_user(session, name="root", role="admin")
+ wanted = await _make_reference(
+ session, owner=alice, name="prod-key", type="github"
+ )
+ await _make_reference(session, owner=alice, name="prod-board", type="jira")
+ await session.commit()
+
+ found = await store.list_readable_with_owner_names(
+ session,
+ root.id,
+ is_admin=True,
+ name_contains="prod",
+ type="github",
+ )
+
+ assert [ref.id for ref, _ in found] == [wanted.id]
+
+
+class TestListReadableOrdering:
+ async def test_newest_first(
+ self, store: ReferenceStore, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ alice = await _make_user(session, name="alice")
+ # Inserted oldest-last so insertion order cannot pass by accident.
+ mid = await _make_reference(
+ session, owner=alice, name="mid", created_at=T_MID
+ )
+ new = await _make_reference(
+ session, owner=alice, name="new", created_at=T_NEW
+ )
+ old = await _make_reference(
+ session, owner=alice, name="old", created_at=T_OLD
+ )
+ await session.commit()
+
+ found = await store.list_readable_with_owner_names(
+ session, alice.id, is_admin=False
+ )
+
+ assert [ref.id for ref, _ in found] == [new.id, mid.id, old.id]
+
+ async def test_identical_created_at_breaks_the_tie_on_id_ascending(
+ self, store: ReferenceStore, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """Rows sharing an instant come back in a stable, defined order.
+
+ Without the `id ASC` tiebreak Postgres may return the group in any
+ order, which would make a caller's paging or diffing flap.
+ """
+ async with session_factory() as session:
+ alice = await _make_user(session, name="alice")
+ # Ids chosen so ascending-id disagrees with insertion order.
+ await _make_reference(
+ session,
+ owner=alice,
+ name="tie-c",
+ created_at=T_MID,
+ reference_id="ref-c",
+ )
+ await _make_reference(
+ session,
+ owner=alice,
+ name="tie-a",
+ created_at=T_MID,
+ reference_id="ref-a",
+ )
+ await _make_reference(
+ session,
+ owner=alice,
+ name="tie-b",
+ created_at=T_MID,
+ reference_id="ref-b",
+ )
+ # A newer row still sorts ahead of the whole tied group.
+ await _make_reference(
+ session,
+ owner=alice,
+ name="newer",
+ created_at=T_NEW,
+ reference_id="ref-z",
+ )
+ await session.commit()
+
+ found = await store.list_readable_with_owner_names(
+ session, alice.id, is_admin=False
+ )
+
+ assert [ref.id for ref, _ in found] == ["ref-z", "ref-a", "ref-b", "ref-c"]
+
+
+class TestAttachToRoomIsIdempotent:
+ async def test_attaching_twice_leaves_exactly_one_link(
+ self, store: ReferenceStore, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """Attaching a reference already attached to the room is a no-op.
+
+ `room_references` is keyed on (room_id, reference_id): the second
+ attach must neither add a row nor abort the surrounding transaction.
+ """
+ async with session_factory() as session:
+ 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"
+ )
+ await session.commit()
+
+ await store.attach_to_room(session, room.id, ref.id)
+ await store.attach_to_room(session, room.id, ref.id)
+ await session.commit()
+
+ count = await session.scalar(
+ select(func.count())
+ .select_from(room_references)
+ .where(
+ room_references.c.room_id == room.id,
+ room_references.c.reference_id == ref.id,
+ )
+ )
+ assert count == 1
+ # The transaction is still usable — an aborted one would raise here.
+ assert await store.is_attached_to_room(session, room.id, ref.id) is True
+ assert [r.id for r in await store.list_for_room(session, room.id)] == [
+ ref.id
+ ]
+
+ async def test_detach_after_a_double_attach_removes_the_link(
+ self, store: ReferenceStore, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """The no-op must not have written a second, invisible row."""
+ async with session_factory() as session:
+ 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"
+ )
+ await session.commit()
+
+ await store.attach_to_room(session, room.id, ref.id)
+ await store.attach_to_room(session, room.id, ref.id)
+ await store.detach_from_room(session, room.id, ref.id)
+ await session.commit()
+
+ assert await store.is_attached_to_room(session, room.id, ref.id) is False
diff --git a/docs/old/api/AGENT_PROTOCOL.md b/docs/old/api/AGENT_PROTOCOL.md
index 507e6917e..9256d90ef 100644
--- a/docs/old/api/AGENT_PROTOCOL.md
+++ b/docs/old/api/AGENT_PROTOCOL.md
@@ -601,9 +601,10 @@ without being told what the room is about.
**Roles** — `list_roles`, `get_role_detail`, `define_role`, `edit_role`,
`delete_role`, `assume_role`, `release_role`.
-**Resources** — `list_references`, `list_reference_types`, `create_reference`,
-`attach_reference_to_room`, `load_internal_documents`, `create_room_document`,
-`update_room_document`, `delete_room_document`.
+**Resources** — `list_references`, `list_all_references`,
+`list_reference_types`, `create_reference`, `attach_reference_to_room`,
+`load_internal_documents`, `create_room_document`, `update_room_document`,
+`delete_room_document`.
**Agents and bridges** — `list_agents`, `get_agent_detail`,
`update_agent_detail`, `list_bridges`.