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
feat(gateway): reference type CRUD routes and resolved display names
raullopez-sandboxe946752d9d63
diff --git a/core/switch_core/bridges/resource/service.py b/core/switch_core/bridges/resource/service.pyindex 6f8bf676a..1ca408784 100644--- a/core/switch_core/bridges/resource/service.py+++ b/core/switch_core/bridges/resource/service.py@@ -43,6 +43,15 @@ ROOM_DOCUMENT_MAX_CONTENT_BYTES = 1_048_576REFERENCE_TYPE_SLUG_PATTERN = re.compile(r"^[a-z][a-z0-9_]{1,62}$")+class ReferenceTypeInUseError(ValueError):+ """A reference type still has references and so cannot be deleted.++ A ValueError so callers matching the broad kind keep working; a distinct+ class so the gateway can answer 409 rather than the 404 it gives every+ other ValueError on a by-slug route.+ """++@dataclass(frozen=True)class ReferenceTypeView:"""One entry of the resolution list — a type a principal may pick.@@ -329,7 +338,7 @@ class ResourceService:require(Principal(user_id, is_admin), "delete", reference_type)in_use = await self._reference_types.count_references_of_type(session, type_)if in_use:- raise ValueError(+ raise ReferenceTypeInUseError(f"Reference type '{type_}' is used by {in_use} reference(s) ""and cannot be deleted")diff --git a/core/switch_core/gateway/references.py b/core/switch_core/gateway/references.pyindex db44b90a6..3c038ffa8 100644--- a/core/switch_core/gateway/references.py+++ b/core/switch_core/gateway/references.py@@ -5,8 +5,13 @@ from typing import Annotatedfrom fastapi import APIRouter, Depends, HTTPExceptionfrom sqlalchemy.ext.asyncio import AsyncSession-from switch_core.bridges.resource.registry import REFERENCE_TYPES-from switch_core.bridges.resource.service import ResourceService+from switch_core.bridges.resource.registry import ReferenceValue, is_builtin_type+from switch_core.bridges.resource.service import (+ ReferenceTypeInUseError,+ ReferenceTypeRow,+ ReferenceTypeView,+ ResourceService,+)from switch_core.db.models import Reference, Userfrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.user_store import UserStore@@ -21,7 +26,11 @@ from switch_core.gateway.schemas import (ReferenceCreateRequest,ReferenceDeleteResponse,ReferenceDetail,+ ReferenceTypeCreateRequest,+ ReferenceTypeDeleteResponse,+ ReferenceTypeDetail,ReferenceTypeInfo,+ ReferenceTypeUpdateRequest,ReferenceUpdateRequest,ResourceRoom,)@@ -33,6 +42,7 @@ def _to_detail(ref: Reference,*,owner_name: str | None = None,+ type_display_name: str | None = None,attached_rooms_count: int = 0,packages: list[str] | None = None,) -> ReferenceDetail:@@ -50,6 +60,7 @@ def _to_detail(attached_rooms_count=attached_rooms_count,packages=packages or [],created_at=str(ref.created_at),+ type_display_name=type_display_name,)@@ -67,16 +78,20 @@ async def _enrich(pkg_map = await resource_service.get_packages_for_references(session, [r.id for r in refs])- owner_ids = list({r.owner_id for r in refs})+ owner_ids = {r.owner_id for r in refs if r.owner_id is not None}owners: dict[str, str] = {}for oid in owner_ids:u = await user_store.get(session, oid)if u is not None:owners[oid] = u.name+ type_names = await resource_service.resolve_display_names(+ session, {r.type for r in refs}+ )return [_to_detail(r,owner_name=owners.get(r.owner_id),+ type_display_name=type_names.get(r.type),attached_rooms_count=counts.get(r.id, 0),packages=pkg_map.get(r.id, []),)@@ -94,19 +109,172 @@ async def _enrich_one(return results[0]+async def _owner_names(+ session: AsyncSession, user_store: UserStore, owner_ids: set[str]+) -> dict[str, str]:+ names: dict[str, str] = {}+ for oid in owner_ids:+ u = await user_store.get(session, oid)+ if u is not None:+ names[oid] = u.name+ return names+++def _type_to_info(view: ReferenceTypeView, owner_name: str | None) -> ReferenceTypeInfo:+ return ReferenceTypeInfo(+ type=view.spec.type,+ display_name=view.spec.display_name,+ instructions=view.spec.instructions,+ value_schema=view.spec.value_json_schema(),+ value_hint=view.spec.value_hint,+ is_builtin=view.is_builtin,+ owner_id=view.owner_id,+ owner_name=owner_name,+ )+++def _type_to_detail(+ entry: ReferenceTypeRow, owner_name: str | None+) -> ReferenceTypeDetail:+ row = entry.row+ return ReferenceTypeDetail(+ type=row.type,+ display_name=row.display_name,+ instructions=row.instructions,+ value_schema=ReferenceValue.model_json_schema(),+ value_hint=row.value_hint,+ is_builtin=False,+ owner_id=row.owner_id,+ owner_name=owner_name,+ read_visibility=row.read_visibility,+ write_visibility=row.write_visibility,+ shadowed_by_builtin=entry.shadowed_by_builtin,+ created_at=str(row.created_at),+ )+++# The five /references/reference-types routes are declared above+# /references/{reference_id}: FastAPI matches in declaration order, so a+# greedy sibling declared first would swallow every one of them. For the same+# reason /reference-types/owned precedes /reference-types/{type}.++@router.get("/references/reference-types")-async def list_reference_types() -> list[ReferenceTypeInfo]:+async def list_reference_types(+ session: Annotated[AsyncSession, Depends(get_session)],+ resource_service: Annotated[ResourceService, Depends(get_resource_service)],+ user_store: Annotated[UserStore, Depends(get_user_store)],+ user: Annotated[User, Depends(get_current_user)],+) -> list[ReferenceTypeInfo]:+ views = await resource_service.list_reference_types_for_principal(+ session, user_id=user.id, is_admin=user.role == "admin"+ )+ owners = await _owner_names(+ session, user_store, {v.owner_id for v in views if v.owner_id is not None}+ )return [- ReferenceTypeInfo(- type=spec.type,- display_name=spec.display_name,- instructions=spec.instructions,- value_schema=spec.value_json_schema(),- )- for spec in REFERENCE_TYPES.values()+ _type_to_info(v, owners.get(v.owner_id) if v.owner_id is not None else None)+ for v in views][email protected]("/references/reference-types/owned")+async def list_owned_reference_types(+ session: Annotated[AsyncSession, Depends(get_session)],+ resource_service: Annotated[ResourceService, Depends(get_resource_service)],+ user_store: Annotated[UserStore, Depends(get_user_store)],+ user: Annotated[User, Depends(get_current_user)],+) -> list[ReferenceTypeDetail]:+ rows = await resource_service.list_owned_reference_types(+ session, user_id=user.id, is_admin=user.role == "admin"+ )+ owners = await _owner_names(session, user_store, {e.row.owner_id for e in rows})+ return [_type_to_detail(e, owners.get(e.row.owner_id)) for e in rows]++[email protected]("/references/reference-types", status_code=201)+async def create_reference_type(+ req: ReferenceTypeCreateRequest,+ session: Annotated[AsyncSession, Depends(get_session)],+ resource_service: Annotated[ResourceService, Depends(get_resource_service)],+ user_store: Annotated[UserStore, Depends(get_user_store)],+ user: Annotated[User, Depends(get_current_user)],+) -> ReferenceTypeDetail:+ try:+ row = await resource_service.create_reference_type(+ session,+ owner_id=user.id,+ type=req.type,+ display_name=req.display_name,+ instructions=req.instructions,+ value_hint=req.value_hint,+ read_visibility=req.read_visibility,+ write_visibility=req.write_visibility,+ )+ except ValueError as e:+ raise HTTPException(status_code=400, detail=str(e)) from e+ await session.commit()+ owners = await _owner_names(session, user_store, {row.owner_id})+ return _type_to_detail(+ ReferenceTypeRow(row=row, shadowed_by_builtin=False),+ owners.get(row.owner_id),+ )++[email protected]("/references/reference-types/{type}")+async def patch_reference_type(+ type: str,+ req: ReferenceTypeUpdateRequest,+ session: Annotated[AsyncSession, Depends(get_session)],+ resource_service: Annotated[ResourceService, Depends(get_resource_service)],+ user_store: Annotated[UserStore, Depends(get_user_store)],+ user: Annotated[User, Depends(get_current_user)],+) -> ReferenceTypeDetail:+ try:+ row = await resource_service.update_reference_type(+ session,+ type,+ user_id=user.id,+ is_admin=user.role == "admin",+ display_name=req.display_name,+ instructions=req.instructions,+ value_hint=req.value_hint,+ read_visibility=req.read_visibility,+ write_visibility=req.write_visibility,+ )+ except ValueError as e:+ raise HTTPException(status_code=404, detail=str(e)) from e+ except PermissionError as e:+ raise HTTPException(status_code=403, detail=str(e)) from e+ await session.commit()+ owners = await _owner_names(session, user_store, {row.owner_id})+ return _type_to_detail(+ ReferenceTypeRow(row=row, shadowed_by_builtin=is_builtin_type(row.type)),+ owners.get(row.owner_id),+ )++[email protected]("/references/reference-types/{type}")+async def delete_reference_type(+ type: str,+ session: Annotated[AsyncSession, Depends(get_session)],+ resource_service: Annotated[ResourceService, Depends(get_resource_service)],+ user: Annotated[User, Depends(get_current_user)],+) -> ReferenceTypeDeleteResponse:+ try:+ await resource_service.delete_reference_type(+ session, type, user_id=user.id, is_admin=user.role == "admin"+ )+ except ReferenceTypeInUseError as e:+ raise HTTPException(status_code=409, detail=str(e)) from e+ except ValueError as e:+ raise HTTPException(status_code=404, detail=str(e)) from e+ except PermissionError as e:+ raise HTTPException(status_code=403, detail=str(e)) from e+ await session.commit()+ return ReferenceTypeDeleteResponse(deleted_type=type)++@router.get("/references")async def list_references(session: Annotated[AsyncSession, Depends(get_session)],diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex f2931cdee..2f9062881 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -690,6 +690,9 @@ class ReferenceDetail(BaseModel):attached_rooms_count: int = 0packages: list[str] = []created_at: str+ # Resolved server-side, unfiltered by the type's visibility: the caller can+ # already read the raw slug. Null when the slug resolves to no type at all.+ type_display_name: str | None = Noneclass ReferenceCreateRequest(BaseModel):@@ -718,10 +721,65 @@ class ReferenceDeleteResponse(BaseModel):class ReferenceTypeInfo(BaseModel):+ """A type a user may pick, built-in or user-defined.++ The owner pair is the disclosure that makes user-authored types safe to+ offer: a type's instructions are prose every agent in a room is told to+ follow, so the picker names who wrote them. Both are null for a built-in.+ Visibility is not part of picking a type and stays off this shape.+ """++ type: str+ display_name: str+ instructions: str+ value_schema: dict[str, Any]+ value_hint: str+ is_builtin: bool+ owner_id: str | None+ owner_name: str | None+++class ReferenceTypeDetail(BaseModel):+ """A stored reference type, for the management list. Never a built-in."""+type: strdisplay_name: strinstructions: strvalue_schema: dict[str, Any]+ value_hint: str+ is_builtin: bool+ owner_id: str+ owner_name: str | None+ read_visibility: str+ write_visibility: str+ shadowed_by_builtin: bool+ created_at: str+++class ReferenceTypeCreateRequest(BaseModel):+ type: str+ display_name: str+ instructions: str+ value_hint: str+ read_visibility: str = "private"+ write_visibility: str = "private"+++class ReferenceTypeUpdateRequest(BaseModel):+ """A partial update. The slug is immutable, so a body carrying `type` is a+ 422 rather than a silently ignored field."""++ model_config = {"extra": "forbid"}++ display_name: str | None = None+ instructions: str | None = None+ value_hint: str | None = None+ read_visibility: str | None = None+ write_visibility: str | None = None+++class ReferenceTypeDeleteResponse(BaseModel):+ deleted_type: strclass ResourceRoom(BaseModel):diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex db33568c3..78beffb6c 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -232,6 +232,8 @@ async def run() -> None:room_link_store=room_link_store,session_factory=session_factory,)+ async with session_factory() as session:+ await resource_service.log_builtin_shadowing(session)# One connection registry for the process. Created here rather than inside# the agent bridge because the Matrix agent clients are wired first and readdiff --git a/core/tests/switch_core/gateway/test_reference_types_routes.py b/core/tests/switch_core/gateway/test_reference_types_routes.pynew file mode 100644index 000000000..685527d3a--- /dev/null+++ b/core/tests/switch_core/gateway/test_reference_types_routes.py@@ -0,0 +1,451 @@+"""The gateway's reference-type routes, exercised as coroutines against real+Postgres, plus the two things only a client can show: the list route's 401 and+the `extra="forbid"` 422 on PATCH.+"""++from __future__ import annotations++from collections.abc import AsyncIterator++import pytest+from fastapi import FastAPI, HTTPException+from fastapi.testclient import TestClient+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.bridges.resource.service import ResourceService+from switch_core.db.models import Reference, 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+from switch_core.db.stores.user_store import UserStore+from switch_core.gateway.auth import get_current_user+from switch_core.gateway.dependencies import (+ get_config,+ get_resource_service,+ get_session,+ get_user_store,+)+from switch_core.gateway.references import (+ create_reference,+ create_reference_type,+ delete_reference_type,+ get_reference,+ list_owned_reference_types,+ list_reference_types,+ list_references,+ patch_reference_type,+ router,+)+from switch_core.gateway.schemas import (+ ReferenceCreateRequest,+ ReferenceTypeCreateRequest,+ ReferenceTypeUpdateRequest,+)++_USER_STORE = UserStore()+_REFERENCE_STORE = ReferenceStore()+++def _resource_service(+ session_factory: async_sessionmaker[AsyncSession],+) -> ResourceService:+ return ResourceService(+ reference_store=_REFERENCE_STORE,+ reference_type_store=ReferenceTypeStore(),+ document_store=DocumentStore(),+ package_store=PackageStore(),+ room_link_store=RoomLinkStore(),+ session_factory=session_factory,+ )+++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+++def _create_request(slug: str, **overrides: str) -> ReferenceTypeCreateRequest:+ body: dict[str, str] = {+ "type": slug,+ "display_name": slug.replace("_", " ").title(),+ "instructions": f"Use the {slug} links as {slug} material.",+ "value_hint": f"Paste {slug} links.",+ "read_visibility": "private",+ "write_visibility": "private",+ }+ body.update(overrides)+ return ReferenceTypeCreateRequest(**body)+++# ── Route ordering ─────────────────────────────────────────────────────────+++class TestRouteOrdering:+ """FastAPI matches in declaration order, so ordering here is behaviour.++ A `/references/{reference_id}` declared first would answer every+ reference-type request, and `/reference-types/{type}` declared first would+ treat `owned` as a slug. Both mistakes surface as a puzzling 404.+ """++ def test_reference_type_routes_precede_the_reference_id_route(self) -> None:+ paths = [r.path for r in router.routes] # type: ignore[attr-defined]+ greedy = paths.index("/references/{reference_id}")+ type_paths = [+ i+ for i, p in enumerate(paths)+ if p.startswith("/references/reference-types")+ ]+ assert type_paths, "no /references/reference-types routes are registered"+ assert max(type_paths) < greedy++ def test_owned_precedes_the_slug_route(self) -> None:+ paths = [r.path for r in router.routes] # type: ignore[attr-defined]+ assert paths.index("/references/reference-types/owned") < paths.index(+ "/references/reference-types/{type}"+ )+++# ── Client-only behaviours ─────────────────────────────────────────────────+++async def _stub_session() -> AsyncIterator[None]:+ yield None+++class _RefusingResourceService:+ """Enough service to prove the PATCH route ran, and nothing more."""++ async def update_reference_type(self, *args: object, **kwargs: object) -> None:+ raise ValueError("Reference type not found: notion")+++def _app() -> FastAPI:+ """An app whose dependencies are overridden on the instance.++ Deliberately not `init_dependencies`: that populates a process-global with+ no teardown and would leak real services into every later test. The stubs+ must exist even where nothing touches them, because FastAPI resolves every+ sub-dependency before the endpoint runs.+ """+ app = FastAPI()+ app.include_router(router)+ app.dependency_overrides[get_session] = _stub_session+ app.dependency_overrides[get_user_store] = lambda: None+ app.dependency_overrides[get_config] = lambda: None+ app.dependency_overrides[get_resource_service] = lambda: None+ return app+++def _anonymous_client() -> TestClient:+ return TestClient(_app())+++def _authenticated_client() -> TestClient:+ """Signed in, so a request gets as far as body validation.++ A dependency raising 401 aborts resolution before FastAPI has collected the+ body errors, so the anonymous client answers 401 to a malformed body too+ and cannot show a 422 at all.+ """+ app = _app()+ app.dependency_overrides[get_current_user] = lambda: User(+ name="alice", email="[email protected]", role="user"+ )+ app.dependency_overrides[get_resource_service] = _RefusingResourceService+ return TestClient(app)+++class TestClientBehaviours:+ def test_listing_types_now_requires_authentication(self) -> None:+ response = _anonymous_client().get("/references/reference-types")+ assert response.status_code == 401+ assert response.json() == {"detail": "Not authenticated"}++ def test_patch_carrying_type_is_422(self) -> None:+ """The slug is immutable, so a body naming it is rejected outright+ rather than silently ignored."""+ response = _authenticated_client().patch(+ "/references/reference-types/notion",+ json={"type": "notion2", "display_name": "Notion"},+ )+ assert response.status_code == 422++ def test_patch_without_type_reaches_the_route(self) -> None:+ # Same client, same route, body minus the forbidden field: it reaches+ # the service and gets that stub's 404, so the 422 above is+ # `extra="forbid"` doing its job and not a broken route.+ response = _authenticated_client().patch(+ "/references/reference-types/notion",+ json={"display_name": "Notion"},+ )+ assert response.status_code == 404+++# ── CRUD against real Postgres ─────────────────────────────────────────────+++class TestReferenceTypeCrudRoutes:+ async def test_create_then_list_and_own(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ svc = _resource_service(session_factory)+ async with session_factory() as session:+ alice = await _make_user(session, "alice")++ created = await create_reference_type(+ _create_request("notion"), session, svc, _USER_STORE, alice+ )+ assert created.type == "notion"+ assert created.owner_id == alice.id+ assert created.owner_name == "alice"+ assert created.is_builtin is False+ assert created.shadowed_by_builtin is False+ assert created.value_schema["properties"]["urls"]++ listed = await list_reference_types(session, svc, _USER_STORE, alice)+ by_slug = {t.type: t for t in listed}+ assert "notion" in by_slug+ assert by_slug["notion"].owner_name == "alice"+ assert by_slug["github"].is_builtin is True+ assert by_slug["github"].owner_id is None+ assert by_slug["github"].owner_name is None+ assert by_slug["github"].value_hint++ owned = await list_owned_reference_types(session, svc, _USER_STORE, alice)+ assert [t.type for t in owned] == ["notion"]++ async def test_a_private_type_is_invisible_to_another_user(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ svc = _resource_service(session_factory)+ async with session_factory() as session:+ alice = await _make_user(session, "alice")+ bob = await _make_user(session, "bob")+ await create_reference_type(+ _create_request("notion"), session, svc, _USER_STORE, alice+ )++ listed = await list_reference_types(session, svc, _USER_STORE, bob)++ assert "notion" not in {t.type for t in listed}+ assert (+ await list_owned_reference_types(session, svc, _USER_STORE, bob) == []+ )++ async def test_invalid_slug_is_400(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ svc = _resource_service(session_factory)+ async with session_factory() as session:+ alice = await _make_user(session, "alice")++ with pytest.raises(HTTPException) as exc:+ await create_reference_type(+ _create_request("Notion"), session, svc, _USER_STORE, alice+ )++ assert exc.value.status_code == 400++ async def test_builtin_slug_is_400(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ svc = _resource_service(session_factory)+ async with session_factory() as session:+ alice = await _make_user(session, "alice")++ with pytest.raises(HTTPException) as exc:+ await create_reference_type(+ _create_request("github"), session, svc, _USER_STORE, alice+ )++ assert exc.value.status_code == 400+ assert "built-in" in exc.value.detail++ async def test_duplicate_slug_is_400(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ svc = _resource_service(session_factory)+ async with session_factory() as session:+ alice = await _make_user(session, "alice")+ await create_reference_type(+ _create_request("notion"), session, svc, _USER_STORE, alice+ )++ with pytest.raises(HTTPException) as exc:+ await create_reference_type(+ _create_request("notion"), session, svc, _USER_STORE, alice+ )++ assert exc.value.status_code == 400+ assert "already exists" in exc.value.detail++ async def test_patch_updates_and_a_non_owner_is_403(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ svc = _resource_service(session_factory)+ async with session_factory() as session:+ alice = await _make_user(session, "alice")+ bob = await _make_user(session, "bob")+ await create_reference_type(+ _create_request("notion"), session, svc, _USER_STORE, alice+ )++ updated = await patch_reference_type(+ "notion",+ ReferenceTypeUpdateRequest(display_name="Notion Workspace"),+ session,+ svc,+ _USER_STORE,+ alice,+ )+ assert updated.display_name == "Notion Workspace"++ with pytest.raises(HTTPException) as exc:+ await patch_reference_type(+ "notion",+ ReferenceTypeUpdateRequest(display_name="Hijacked"),+ session,+ svc,+ _USER_STORE,+ bob,+ )+ assert exc.value.status_code == 403++ async def test_patch_of_an_unknown_slug_is_404(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ svc = _resource_service(session_factory)+ async with session_factory() as session:+ alice = await _make_user(session, "alice")++ with pytest.raises(HTTPException) as exc:+ await patch_reference_type(+ "never_registered",+ ReferenceTypeUpdateRequest(display_name="x"),+ session,+ svc,+ _USER_STORE,+ alice,+ )++ assert exc.value.status_code == 404++ async def test_delete_removes_an_unused_type(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ svc = _resource_service(session_factory)+ async with session_factory() as session:+ alice = await _make_user(session, "alice")+ await create_reference_type(+ _create_request("notion"), session, svc, _USER_STORE, alice+ )++ response = await delete_reference_type("notion", session, svc, alice)++ assert response.deleted_type == "notion"+ assert (+ await list_owned_reference_types(session, svc, _USER_STORE, alice) == []+ )++ async def test_delete_of_a_type_in_use_is_409(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """Not the 404 every other ValueError on a by-slug route gets: the type+ exists and the caller may delete it, the request just conflicts with+ live data."""+ svc = _resource_service(session_factory)+ async with session_factory() as session:+ alice = await _make_user(session, "alice")+ await create_reference_type(+ _create_request("notion"), session, svc, _USER_STORE, alice+ )+ await create_reference(+ ReferenceCreateRequest(+ type="notion",+ name="Handbook",+ description="d",+ instructions="",+ value={"urls": ["https://notion.example.invalid/handbook"]},+ ),+ session,+ svc,+ _USER_STORE,+ alice,+ )++ with pytest.raises(HTTPException) as exc:+ await delete_reference_type("notion", session, svc, alice)++ assert exc.value.status_code == 409+ assert "cannot be deleted" in exc.value.detail+++# ── type_display_name on ReferenceDetail ───────────────────────────────────+++class TestTypeDisplayName:+ async def test_a_resolvable_slug_carries_its_display_name(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ svc = _resource_service(session_factory)+ async with session_factory() as session:+ alice = await _make_user(session, "alice")+ await create_reference_type(+ _create_request("notion", display_name="Notion"),+ session,+ svc,+ _USER_STORE,+ alice,+ )+ created = await create_reference(+ ReferenceCreateRequest(+ type="notion",+ name="Handbook",+ description="d",+ instructions="",+ value={"urls": ["https://notion.example.invalid/handbook"]},+ ),+ session,+ svc,+ _USER_STORE,+ alice,+ )++ assert created.type_display_name == "Notion"++ fetched = await get_reference(created.id, session, svc, _USER_STORE, alice)+ assert fetched.type_display_name == "Notion"++ async def test_an_unresolvable_slug_maps_to_none(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """A slug with no type behind it is a real state — `references.type`+ has no foreign key and cannot have one, because built-ins are not rows.+ The row is written through the store, which validates nothing.+ """+ svc = _resource_service(session_factory)+ async with session_factory() as session:+ alice = await _make_user(session, "alice")+ await _REFERENCE_STORE.create(+ session,+ Reference(+ owner_id=alice.id,+ read_visibility="private",+ write_visibility="private",+ type="never_registered",+ name="Orphan",+ description="d",+ instructions="",+ value={"urls": ["https://example.invalid/orphan"]},+ ),+ )++ listed = await list_references(session, svc, _USER_STORE, alice)++ assert [r.type for r in listed] == ["never_registered"]+ assert listed[0].type_display_name is None