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(db): reference_types migration and store

raullopez-sandbox75ea15c2205f
diff --git a/core/switch_core/db/stores/__init__.py b/core/switch_core/db/stores/__init__.py
index ceac5301a..7d23337ff 100644
--- a/core/switch_core/db/stores/__init__.py
+++ b/core/switch_core/db/stores/__init__.py
@@ -6,6 +6,7 @@ from switch_core.db.stores.collaboration_bridge_store import CollaborationBridge
from switch_core.db.stores.document_store import DocumentStore
from switch_core.db.stores.external_user_store import ExternalUserStore
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_group_store import RoomGroupStore
from switch_core.db.stores.room_link_store import RoomLinkStore
from switch_core.db.stores.room_store import RoomStore
@@ -22,6 +23,7 @@ __all__ = [
"DocumentStore",
"ExternalUserStore",
"ReferenceStore",
+ "ReferenceTypeStore",
"RoomGroupStore",
"RoomLinkStore",
"RoomStore",
diff --git a/core/switch_core/db/stores/reference_type_store.py b/core/switch_core/db/stores/reference_type_store.py
new file mode 100644
index 000000000..a86d3c81c
--- /dev/null
+++ b/core/switch_core/db/stores/reference_type_store.py
@@ -0,0 +1,105 @@
+from sqlalchemy import ColumnElement, func, or_, select
+from sqlalchemy.exc import IntegrityError
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from switch_core.db.models import Reference, ReferenceType
+
+
+class ReferenceTypeStore:
+ async def create(
+ self, session: AsyncSession, reference_type: ReferenceType
+ ) -> ReferenceType:
+ try:
+ # Savepoint: a duplicate slug must not poison the caller's transaction.
+ async with session.begin_nested():
+ session.add(reference_type)
+ await session.flush()
+ except IntegrityError as exc:
+ clash = await session.execute(
+ select(ReferenceType.type).where(
+ ReferenceType.type == reference_type.type
+ )
+ )
+ if clash.scalar_one_or_none() is not None:
+ raise ValueError(
+ f"Reference type '{reference_type.type}' already exists"
+ ) from exc
+ raise
+ return reference_type
+
+ async def get(self, session: AsyncSession, type_: str) -> ReferenceType | None:
+ return await session.get(ReferenceType, type_)
+
+ async def get_many(
+ self, session: AsyncSession, types: list[str]
+ ) -> list[ReferenceType]:
+ if not types:
+ return []
+ result = await session.execute(
+ select(ReferenceType).where(ReferenceType.type.in_(types))
+ )
+ return list(result.scalars().all())
+
+ async def list_for_user(
+ self, session: AsyncSession, user_id: str | None
+ ) -> list[ReferenceType]:
+ """Return the types the principal may read.
+
+ An ownerless principal (``user_id is None``) reads public types only: an
+ ``owner_id = NULL`` comparison is never true in SQL, so it is left out
+ rather than relied on.
+ """
+ condition: ColumnElement[bool]
+ if user_id is None:
+ condition = ReferenceType.read_visibility == "public"
+ else:
+ condition = or_(
+ ReferenceType.owner_id == user_id,
+ ReferenceType.read_visibility == "public",
+ )
+ result = await session.execute(select(ReferenceType).where(condition))
+ return list(result.scalars().all())
+
+ async def list_all(self, session: AsyncSession) -> list[ReferenceType]:
+ result = await session.execute(select(ReferenceType))
+ return list(result.scalars().all())
+
+ async def update_fields(
+ self,
+ session: AsyncSession,
+ type_: str,
+ *,
+ display_name: str | None = None,
+ instructions: str | None = None,
+ value_hint: str | None = None,
+ read_visibility: str | None = None,
+ write_visibility: str | None = None,
+ ) -> ReferenceType:
+ rt = await session.get(ReferenceType, type_)
+ if rt is None:
+ raise ValueError(f"Reference type not found: {type_}")
+ if display_name is not None:
+ rt.display_name = display_name
+ if instructions is not None:
+ rt.instructions = instructions
+ if value_hint is not None:
+ rt.value_hint = value_hint
+ if read_visibility is not None:
+ rt.read_visibility = read_visibility
+ if write_visibility is not None:
+ rt.write_visibility = write_visibility
+ await session.flush()
+ return rt
+
+ async def delete(self, session: AsyncSession, type_: str) -> None:
+ rt = await session.get(ReferenceType, type_)
+ if rt is None:
+ raise ValueError(f"Reference type not found: {type_}")
+ await session.delete(rt)
+ await session.flush()
+
+ async def count_references_of_type(self, session: AsyncSession, type_: str) -> int:
+ result = await session.execute(
+ select(func.count()).select_from(Reference).where(Reference.type == type_)
+ )
+ return int(result.scalar_one())
diff --git a/core/switch_core/migrations/versions/e7a1b2c3d4f5_add_reference_types.py b/core/switch_core/migrations/versions/e7a1b2c3d4f5_add_reference_types.py
new file mode 100644
index 000000000..b0bce1b1d
--- /dev/null
+++ b/core/switch_core/migrations/versions/e7a1b2c3d4f5_add_reference_types.py
@@ -0,0 +1,42 @@
+"""add reference_types
+
+Revision ID: e7a1b2c3d4f5
+Revises: a2171c0de1f4
+Create Date: 2026-09-01 00:00:00.000000
+
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "e7a1b2c3d4f5"
+down_revision: str | None = "a2171c0de1f4"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.create_table(
+ "reference_types",
+ sa.Column("type", sa.Text(), nullable=False),
+ sa.Column("owner_id", sa.Text(), nullable=False),
+ sa.Column("read_visibility", sa.Text(), nullable=False),
+ sa.Column("write_visibility", sa.Text(), nullable=False),
+ sa.Column("display_name", sa.Text(), nullable=False),
+ sa.Column("instructions", sa.Text(), nullable=False),
+ sa.Column("value_hint", sa.Text(), nullable=False),
+ sa.Column(
+ "created_at",
+ sa.DateTime(timezone=True),
+ server_default=sa.text("now()"),
+ nullable=False,
+ ),
+ sa.ForeignKeyConstraint(["owner_id"], ["users.id"]),
+ sa.PrimaryKeyConstraint("type"),
+ )
+
+
+def downgrade() -> None:
+ op.drop_table("reference_types")
diff --git a/core/tests/switch_core/db/stores/test_reference_type_store.py b/core/tests/switch_core/db/stores/test_reference_type_store.py
new file mode 100644
index 000000000..837f63379
--- /dev/null
+++ b/core/tests/switch_core/db/stores/test_reference_type_store.py
@@ -0,0 +1,252 @@
+from __future__ import annotations
+
+import pytest
+from sqlalchemy.exc import IntegrityError
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import Reference, ReferenceType, User
+from switch_core.db.stores.reference_store import ReferenceStore
+from switch_core.db.stores.reference_type_store import ReferenceTypeStore
+
+
+async def _make_user(session: AsyncSession, name: str) -> User:
+ user = User(name=name, email=f"{name}@example.invalid", role="user")
+ session.add(user)
+ await session.flush()
+ return user
+
+
+def _type(
+ slug: str,
+ owner_id: str,
+ *,
+ read_visibility: str = "private",
+ write_visibility: str = "private",
+) -> ReferenceType:
+ return ReferenceType(
+ type=slug,
+ owner_id=owner_id,
+ read_visibility=read_visibility,
+ write_visibility=write_visibility,
+ display_name=slug.replace("_", " ").title(),
+ instructions=f"Use {slug} links.",
+ value_hint=f"Paste {slug} URLs.",
+ )
+
+
+def _reference(type_: str, owner_id: str) -> Reference:
+ return Reference(
+ owner_id=owner_id,
+ read_visibility="private",
+ write_visibility="private",
+ type=type_,
+ name=f"{type_} ref",
+ description="",
+ instructions="",
+ value={"urls": ["https://example.invalid/doc"]},
+ )
+
+
+class TestReferenceTypeStore:
+ async def test_create_and_get(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = ReferenceTypeStore()
+ async with session_factory() as session:
+ user = await _make_user(session, "ada")
+ created = await store.create(session, _type("notion", user.id))
+ await session.commit()
+
+ assert created.type == "notion"
+ assert created.created_at is not None
+
+ loaded = await store.get(session, "notion")
+ assert loaded is not None
+ assert loaded.owner_id == user.id
+ assert loaded.display_name == "Notion"
+ assert loaded.value_hint == "Paste notion URLs."
+ assert await store.get(session, "nope") is None
+
+ async def test_get_many(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = ReferenceTypeStore()
+ async with session_factory() as session:
+ user = await _make_user(session, "ada")
+ for slug in ("notion", "linear", "figma"):
+ await store.create(session, _type(slug, user.id))
+ await session.commit()
+
+ found = await store.get_many(session, ["notion", "figma", "absent"])
+ assert {rt.type for rt in found} == {"notion", "figma"}
+ assert await store.get_many(session, []) == []
+
+ async def test_duplicate_slug_raises_value_error_and_keeps_session_usable(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """A clashing slug is a ValueError the gateway turns into a 400, not a 500."""
+ store = ReferenceTypeStore()
+ async with session_factory() as session:
+ ada = await _make_user(session, "ada")
+ grace = await _make_user(session, "grace")
+ await store.create(session, _type("notion", ada.id))
+ await session.commit()
+
+ with pytest.raises(
+ ValueError, match="Reference type 'notion' already exists"
+ ):
+ await store.create(session, _type("notion", grace.id))
+
+ # The savepoint means the surrounding transaction survives the clash.
+ await store.create(session, _type("linear", grace.id))
+ await session.commit()
+ assert {rt.type for rt in await store.list_all(session)} == {
+ "notion",
+ "linear",
+ }
+ notion = await store.get(session, "notion")
+ assert notion is not None
+ assert notion.owner_id == ada.id
+
+ async def test_integrity_error_that_is_not_a_duplicate_propagates(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """An unknown owner is a foreign-key violation, not a slug clash."""
+ store = ReferenceTypeStore()
+ async with session_factory() as session:
+ with pytest.raises(IntegrityError):
+ await store.create(session, _type("notion", "no-such-user"))
+
+ async def test_list_for_user_filters_by_owner_and_public_read(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = ReferenceTypeStore()
+ async with session_factory() as session:
+ ada = await _make_user(session, "ada")
+ grace = await _make_user(session, "grace")
+ await store.create(session, _type("ada_private", ada.id))
+ await store.create(
+ session, _type("ada_public", ada.id, read_visibility="public")
+ )
+ await store.create(session, _type("grace_private", grace.id))
+ await store.create(
+ session, _type("grace_public", grace.id, read_visibility="public")
+ )
+ await session.commit()
+
+ assert {rt.type for rt in await store.list_for_user(session, ada.id)} == {
+ "ada_private",
+ "ada_public",
+ "grace_public",
+ }
+ assert {rt.type for rt in await store.list_for_user(session, grace.id)} == {
+ "grace_private",
+ "grace_public",
+ "ada_public",
+ }
+
+ async def test_list_for_user_none_returns_public_rows_only(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """An ownerless principal sees public types and nothing else."""
+ store = ReferenceTypeStore()
+ async with session_factory() as session:
+ ada = await _make_user(session, "ada")
+ await store.create(session, _type("ada_private", ada.id))
+ await store.create(
+ session, _type("ada_public", ada.id, read_visibility="public")
+ )
+ await session.commit()
+
+ assert {rt.type for rt in await store.list_for_user(session, None)} == {
+ "ada_public"
+ }
+
+ async def test_list_all_returns_every_row(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = ReferenceTypeStore()
+ async with session_factory() as session:
+ assert await store.list_all(session) == []
+ ada = await _make_user(session, "ada")
+ await store.create(session, _type("ada_private", ada.id))
+ await store.create(
+ session, _type("ada_public", ada.id, read_visibility="public")
+ )
+ await session.commit()
+
+ assert {rt.type for rt in await store.list_all(session)} == {
+ "ada_private",
+ "ada_public",
+ }
+
+ async def test_update_fields_updates_only_what_is_passed(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = ReferenceTypeStore()
+ async with session_factory() as session:
+ ada = await _make_user(session, "ada")
+ await store.create(session, _type("notion", ada.id))
+ await session.commit()
+
+ updated = await store.update_fields(
+ session,
+ "notion",
+ display_name="Notion Workspace",
+ read_visibility="public",
+ write_visibility="public",
+ )
+ await session.commit()
+
+ assert updated.display_name == "Notion Workspace"
+ assert updated.read_visibility == "public"
+ assert updated.write_visibility == "public"
+ assert updated.instructions == "Use notion links."
+ assert updated.value_hint == "Paste notion URLs."
+ assert updated.type == "notion"
+
+ async def test_update_fields_on_missing_type_raises(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = ReferenceTypeStore()
+ async with session_factory() as session:
+ with pytest.raises(ValueError, match="Reference type not found: notion"):
+ await store.update_fields(session, "notion", display_name="X")
+
+ async def test_delete_removes_the_row(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = ReferenceTypeStore()
+ async with session_factory() as session:
+ ada = await _make_user(session, "ada")
+ await store.create(session, _type("notion", ada.id))
+ await session.commit()
+
+ await store.delete(session, "notion")
+ await session.commit()
+ assert await store.get(session, "notion") is None
+
+ async def test_delete_missing_type_raises(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = ReferenceTypeStore()
+ async with session_factory() as session:
+ with pytest.raises(ValueError, match="Reference type not found: notion"):
+ await store.delete(session, "notion")
+
+ async def test_count_references_of_type(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = ReferenceTypeStore()
+ references = ReferenceStore()
+ async with session_factory() as session:
+ ada = await _make_user(session, "ada")
+ await store.create(session, _type("notion", ada.id))
+ await references.create(session, _reference("notion", ada.id))
+ await references.create(session, _reference("notion", ada.id))
+ await references.create(session, _reference("github", ada.id))
+ await session.commit()
+
+ assert await store.count_references_of_type(session, "notion") == 2
+ assert await store.count_references_of_type(session, "github") == 1
+ assert await store.count_references_of_type(session, "unused") == 0