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(templates): template registry — server-side storage and API (CHOO-2677) (#421)
Christian McDermott514d5ba414f3
diff --git a/core/switch_core/config.py b/core/switch_core/config.pyindex 31a7bb8cb..d7e83bfc2 100644--- a/core/switch_core/config.py+++ b/core/switch_core/config.py@@ -169,6 +169,11 @@ class SwitchConfig(BaseSettings):# of being truncated or silently dropped.agent_media_max_bytes: int = 20 * 1024 * 1024+ # Upper bound on a template document uploaded to the registry. The column+ # itself is unbounded, so raising this is a deploy-time change and never a+ # migration. Oversize uploads are refused rather than truncated.+ template_max_bytes: int = 1024 * 1024+# Every authenticated agent request resolves its bearer token against the# database before the handler runs, and each live agent connection beats# every 2s, so the pool is sized against connection count rather than@@ -271,6 +276,10 @@ class SwitchConfig(BaseSettings):)if not self.tenant_id.strip():raise ValueError("TENANT_ID must not be empty.")+ if self.template_max_bytes < 1:+ raise ValueError(+ f"TEMPLATE_MAX_BYTES must be at least 1, got {self.template_max_bytes}."+ )return self@model_validator(mode="after")diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.pyindex 957e0b8c0..7124c0b0a 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -874,6 +874,48 @@ class Document(TenantScoped, Base):)+# ── Templates ─────────────────────────────────────────────────────────────────+++class Template(TenantScoped, Base):+ """A template document held on this server, plus the metadata to find it.++ ``content`` is stored verbatim and never parsed, so a document in a format+ this server does not yet understand still round-trips byte for byte.+ ``kind`` is free text for the same reason: room, group and agent templates+ differ only in a string, not in the schema.++ ``version`` counts revisions of the stored row, incrementing whenever the+ content is replaced. It is not the author's name for a release, and not the+ inert ``version:`` key inside the document — those belong to the format.+ """++ __tablename__ = "templates"+ __table_args__ = (+ # Not widened to include the tenant: an owner belongs to one, so+ # scoping the name to the owner already scopes it to the tenant.+ UniqueConstraint("owner_id", "name", name="uq_templates_owner_name"),+ UniqueConstraint("id", "tenant_id", name="uq_templates_id_tenant"),+ )++ id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)+ owner_id: Mapped[str] = mapped_column(Text, ForeignKey("users.id"), nullable=False)+ name: Mapped[str] = mapped_column(Text, nullable=False)+ description: Mapped[str] = mapped_column(Text, nullable=False)+ kind: Mapped[str] = mapped_column(Text, nullable=False)+ content: Mapped[str] = mapped_column(Text, nullable=False)+ version: Mapped[int] = mapped_column(Integer, nullable=False, server_default="1")+ created_at: Mapped[str] = mapped_column(+ DateTime(timezone=True), server_default=func.now(), nullable=False+ )+ updated_at: Mapped[str] = mapped_column(+ DateTime(timezone=True),+ server_default=func.now(),+ onupdate=func.now(),+ nullable=False,+ )++# ── Packages ──────────────────────────────────────────────────────────────────diff --git a/core/switch_core/db/stores/__init__.py b/core/switch_core/db/stores/__init__.pyindex 11e7d5ce4..c9243625c 100644--- a/core/switch_core/db/stores/__init__.py+++ b/core/switch_core/db/stores/__init__.py@@ -13,6 +13,7 @@ from switch_core.db.stores.room_link_store import RoomLinkStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.skill_store import SkillStorefrom switch_core.db.stores.task_store import TaskStore+from switch_core.db.stores.template_store import TemplateStorefrom switch_core.db.stores.tenant_store import TenantStorefrom switch_core.db.stores.user_store import UserStore@@ -32,6 +33,7 @@ __all__ = ["RoomStore","SkillStore","TaskStore",+ "TemplateStore","TenantStore","UserStore",]diff --git a/core/switch_core/db/stores/template_store.py b/core/switch_core/db/stores/template_store.pynew file mode 100644index 000000000..b8d898db7--- /dev/null+++ b/core/switch_core/db/stores/template_store.py@@ -0,0 +1,225 @@+from dataclasses import dataclass++from sqlalchemy import ColumnElement, func, or_, select+from sqlalchemy.exc import IntegrityError+from sqlalchemy.ext.asyncio import AsyncSession++from switch_core.db.models import Template, require_tenant_id++_LIKE_ESCAPE = "\\"+++class TemplateNameTaken(ValueError):+ """This owner already has a template by that name.++ A ValueError, so a caller that only knows the house convention still+ catches it, but distinguishable so a router can answer 409 rather than+ folding it in with "not found".+ """+++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}%"+++@dataclass(frozen=True)+class TemplateListing:+ """One row of the catalogue — everything but the document itself.++ The document is the whole reason a listing has to be careful: reading a+ thousand templates to render a thousand names would drag a thousand+ documents through Postgres and into memory with them. The size is measured+ in the database instead, so a listing costs the same whatever is stored.+ """++ id: str+ owner_id: str+ name: str+ description: str+ kind: str+ version: int+ size_bytes: int+ created_at: object+ updated_at: object+++class TemplateStore:+ async def create(self, session: AsyncSession, template: Template) -> Template:+ owner_id, name = template.owner_id, template.name+ try:+ # Savepoint: a duplicate name must not poison the caller's transaction.+ async with session.begin_nested():+ session.add(template)+ await session.flush()+ except IntegrityError as exc:+ clash = await session.execute(+ select(Template.id).where(+ Template.tenant_id == require_tenant_id(),+ Template.owner_id == owner_id,+ Template.name == name,+ )+ )+ if clash.scalar_one_or_none() is not None:+ raise TemplateNameTaken(+ f"You already have a template named '{name}'"+ ) from exc+ raise+ return template++ async def get(self, session: AsyncSession, template_id: str) -> Template | None:+ return await session.get(Template, template_id)++ async def list_all(+ self,+ session: AsyncSession,+ *,+ query: str | None = None,+ kind: str | None = None,+ owner_id: str | None = None,+ ) -> list[TemplateListing]:+ """The catalogue, newest first, without the documents.++ Every template in the tenant, whoever uploaded it: ownership governs+ who may change or remove one, not who may see it. The tenant boundary+ is the database's to enforce, not this query's — row-level security+ filters it, so a filter here would be a second answer to a question+ already answered, and the wrong place to notice if the two disagreed.+ """+ conditions: list[ColumnElement[bool]] = []+ if query:+ needle = _like_needle(query)+ conditions.append(+ or_(+ Template.name.ilike(needle, escape=_LIKE_ESCAPE),+ Template.description.ilike(needle, escape=_LIKE_ESCAPE),+ )+ )+ if kind:+ conditions.append(Template.kind == kind)+ if owner_id:+ conditions.append(Template.owner_id == owner_id)++ stmt = (+ select(+ Template.id,+ Template.owner_id,+ Template.name,+ Template.description,+ Template.kind,+ Template.version,+ # Bytes, not characters — `length()` would undercount anything+ # outside ASCII and disagree with the upload limit.+ func.octet_length(Template.content).label("size_bytes"),+ Template.created_at,+ Template.updated_at,+ )+ .where(*conditions)+ .order_by(Template.created_at.desc(), Template.id.asc())+ )+ result = await session.execute(stmt)+ # By name, not by position: bound positionally, reordering either the+ # select or the dataclass would land a timestamp in `size_bytes` and+ # say nothing about it.+ return [TemplateListing(**row) for row in result.mappings()]++ async def update_fields(+ self,+ session: AsyncSession,+ template_id: str,+ *,+ name: str | None = None,+ description: str | None = None,+ kind: str | None = None,+ content: str | None = None,+ ) -> Template:+ """Change a stored template. Replacing the content bumps ``version``.++ Metadata-only edits leave the revision alone: the document someone+ fetched is still the document they would fetch now.++ The row is locked for the read-modify-write. Bumping a revision means+ reading the old one first, so two edits racing on an unlocked row would+ both compute the same next number and the later write would drop the+ earlier one silently — the one failure mode worse than an error.++ ``populate_existing`` is what makes the lock worth taking: the caller+ has usually loaded this row already to check ownership, and without it+ the refreshed values are free to lose to the copy sitting in the+ identity map. Locking a row and then computing from a stale read of it+ would be the same lost update, behind a lock that looks like it stopped+ one.+ """+ template = await session.get(+ Template, template_id, with_for_update=True, populate_existing=True+ )+ if template is None:+ raise ValueError(f"Template not found: {template_id}")++ if name is not None and name != template.name:+ # Asked before anything is mutated: a flush that fails the unique+ # constraint deactivates the caller's transaction, and a session in+ # that state cannot even be asked what went wrong.+ clash = await session.execute(+ select(Template.id).where(+ Template.tenant_id == template.tenant_id,+ Template.owner_id == template.owner_id,+ Template.name == name,+ Template.id != template_id,+ )+ )+ if clash.scalar_one_or_none() is not None:+ raise TemplateNameTaken(f"You already have a template named '{name}'")+ template.name = name++ if content is not None and content != template.content:+ template.content = content+ template.version += 1+ if description is not None:+ template.description = description+ if kind is not None:+ template.kind = kind++ # Read off the object now: after a failed flush, touching it again can+ # lazy-load against a session that is no longer in a state to answer.+ owner_id, final_name = template.owner_id, template.name++ try:+ # The lock serialises edits to this row, but says nothing about a+ # *different* row claiming the name first, so the constraint is+ # still the arbiter and the savepoint keeps its refusal survivable.+ async with session.begin_nested():+ await session.flush()+ except IntegrityError as exc:+ # Confirm it really is the name before saying so, the same way+ # `create` does. Reporting every constraint this row could ever+ # violate as a name clash would be a confident wrong answer.+ clash = await session.execute(+ select(Template.id).where(+ Template.owner_id == owner_id,+ Template.name == final_name,+ Template.id != template_id,+ )+ )+ if clash.scalar_one_or_none() is not None:+ raise TemplateNameTaken(+ f"You already have a template named '{final_name}'"+ ) from exc+ raise++ # `updated_at` is computed by Postgres, so the flush leaves it expired.+ # Reload here, where there is a running event loop, rather than leaving+ # the caller to trip a lazy load from synchronous code.+ await session.refresh(template)+ return template++ async def delete(self, session: AsyncSession, template_id: str) -> None:+ template = await session.get(Template, template_id)+ if template is None:+ raise ValueError(f"Template not found: {template_id}")+ await session.delete(template)+ await session.flush()diff --git a/core/switch_core/gateway/app.py b/core/switch_core/gateway/app.pyindex ab24b4e3c..f97229980 100644--- a/core/switch_core/gateway/app.py+++ b/core/switch_core/gateway/app.py@@ -21,6 +21,7 @@ from switch_core.db.stores.external_user_store import ExternalUserStorefrom switch_core.db.stores.room_group_store import RoomGroupStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.server_connector_store import ServerConnectorStore+from switch_core.db.stores.template_store import TemplateStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.gateway.agents import router as agents_routerfrom switch_core.gateway.api_keys import router as api_keys_router@@ -37,6 +38,7 @@ from switch_core.gateway.references import router as references_routerfrom switch_core.gateway.room_groups import router as room_groups_routerfrom switch_core.gateway.room_links import router as room_links_routerfrom switch_core.gateway.rooms import router as rooms_router+from switch_core.gateway.templates import router as templates_routerfrom switch_core.room_service import RoomService@@ -56,6 +58,7 @@ def create_gateway_app(user_store: UserStore,external_user_store: ExternalUserStore,api_key_store: ApiKeyStore,+ template_store: TemplateStore,resource_service: ResourceService,protocol: ProtocolService,config: SwitchConfig,@@ -75,6 +78,7 @@ def create_gateway_app(user_store=user_store,external_user_store=external_user_store,api_key_store=api_key_store,+ template_store=template_store,resource_service=resource_service,protocol=protocol,config=config,@@ -109,6 +113,7 @@ def create_gateway_app(app.include_router(room_links_router, tags=["linked-rooms"])app.include_router(documents_router, tags=["documents"])app.include_router(packages_router, tags=["packages"])+ app.include_router(templates_router, tags=["templates"])app.include_router(ecosystem_router, prefix="/ecosystem", tags=["ecosystem"])return appdiff --git a/core/switch_core/gateway/dependencies.py b/core/switch_core/gateway/dependencies.pyindex 3879e7384..708ee6543 100644--- a/core/switch_core/gateway/dependencies.py+++ b/core/switch_core/gateway/dependencies.py@@ -23,6 +23,7 @@ from switch_core.db.stores.external_user_store import ExternalUserStorefrom switch_core.db.stores.room_group_store import RoomGroupStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.server_connector_store import ServerConnectorStore+from switch_core.db.stores.template_store import TemplateStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.room_service import RoomServicefrom switch_core.rooms_yaml import RoomYamlService@@ -46,6 +47,7 @@ def init_dependencies(user_store: UserStore,external_user_store: ExternalUserStore,api_key_store: ApiKeyStore,+ template_store: TemplateStore,resource_service: ResourceService,protocol: ProtocolService,config: SwitchConfig,@@ -64,6 +66,7 @@ def init_dependencies(_state["user_store"] = user_store_state["external_user_store"] = external_user_store_state["api_key_store"] = api_key_store+ _state["template_store"] = template_store_state["resource_service"] = resource_service_state["protocol"] = protocol_state["config"] = config@@ -189,6 +192,10 @@ def get_connector_store() -> ServerConnectorStore:return _state["connector_store"] # type: ignore[no-any-return]+def get_template_store() -> TemplateStore:+ return _state["template_store"] # type: ignore[no-any-return]++def get_config() -> SwitchConfig:return _state["config"] # type: ignore[no-any-return]diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex 35a6bd677..c5c973da8 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -1006,3 +1006,93 @@ class PackageMemberRemoveResponse(BaseModel):member_id: straffected_room_ids: list[str]affected_room_names: list[str]+++# ── Templates ─────────────────────────────────────────────────────────────────+++class TemplateSummary(BaseModel):+ """A template as it appears in the catalogue.++ Deliberately without `content`: a listing is a browse, and shipping every+ stored document to render a list of names would grow with the registry.+ Fetch one to get its content.+ """++ id: str+ owner_id: str+ owner_name: str | None = None+ name: str+ description: str+ kind: str+ version: int+ size_bytes: int+ created_at: str+ updated_at: str+++class TemplateDetail(TemplateSummary):+ content: str+++# The document has its own budget (TEMPLATE_MAX_BYTES); these are the labels+# around it. Bounded because the columns are unbounded `Text` and nothing else+# in the request path caps a field — without these, a name is as big as the+# body someone is willing to send.+TEMPLATE_NAME_MAX = 200+TEMPLATE_DESCRIPTION_MAX = 2000+TEMPLATE_KIND_MAX = 64+++class TemplateCreateRequest(BaseModel):+ # Same stance as the update request: a body naming a field this does not+ # have is a caller expecting something, and ignoring it silently answers+ # 201 to a request that did not do what was asked.+ model_config = {"extra": "forbid"}++ name: str = Field(min_length=1, max_length=TEMPLATE_NAME_MAX)+ description: str = Field(default="", max_length=TEMPLATE_DESCRIPTION_MAX)+ kind: str = Field(default="room", min_length=1, max_length=TEMPLATE_KIND_MAX)+ content: str = Field(min_length=1)+++class TemplateUpdateRequest(BaseModel):+ model_config = {"extra": "forbid"}++ name: str | None = Field(default=None, min_length=1, max_length=TEMPLATE_NAME_MAX)+ description: str | None = Field(default=None, max_length=TEMPLATE_DESCRIPTION_MAX)+ kind: str | None = Field(default=None, min_length=1, max_length=TEMPLATE_KIND_MAX)+ content: str | None = Field(default=None, min_length=1)+++class TemplateDeleteResponse(BaseModel):+ deleted_id: str+++class TemplateValidateRequest(BaseModel):+ model_config = {"extra": "forbid"}++ content: str+++class TemplateFinding(BaseModel):+ code: str+ message: str+ subject: str | None = None+ # Whether this one is a refusal rather than a remark.+ blocking: bool = False+++class TemplateValidateResponse(BaseModel):+ """What the checker made of a document, and whether it bars the door.++ `blocked` is the only part an upload consults: a document that is not YAML+ at all is refused, everything else is said and then allowed. `ok` is the+ wider question of whether anything is wrong, which a form shows without+ acting on.+ """++ ok: bool+ blocked: bool+ errors: list[TemplateFinding]+ warnings: list[TemplateFinding]diff --git a/core/switch_core/gateway/templates.py b/core/switch_core/gateway/templates.pynew file mode 100644index 000000000..43ac1abd5--- /dev/null+++ b/core/switch_core/gateway/templates.py@@ -0,0 +1,343 @@+"""The template registry's HTTP surface.++Two rules shape the whole of this module. A stored document is returned exactly+as it arrived — nothing here parses, validates or reformats it — and the+catalogue is shared, so ownership decides who may change a template rather than+who may see it.++"Shared" means shared within the tenant. Nothing here says so, and that is+deliberate: row-level security draws that boundary in the database, and a+second copy of it in these queries would be a second answer to a question+already answered — agreeing right up until the day it did not.+"""++from __future__ import annotations++import re+from typing import Annotated+from urllib.parse import quote++from fastapi import APIRouter, Depends, HTTPException, Query, Response+from sqlalchemy.ext.asyncio import AsyncSession++from switch_core.authz import Principal, require_manage+from switch_core.config import SwitchConfig+from switch_core.db.models import Template, User+from switch_core.db.stores.template_store import (+ TemplateListing,+ TemplateNameTaken,+ TemplateStore,+)+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_session,+ get_template_store,+ get_user_store,+)+from switch_core.gateway.schemas import (+ TemplateCreateRequest,+ TemplateDeleteResponse,+ TemplateDetail,+ TemplateFinding,+ TemplateSummary,+ TemplateUpdateRequest,+ TemplateValidateRequest,+ TemplateValidateResponse,+)+from switch_core.template_lint import lint_template++router = APIRouter()+++_UNSAFE_IN_FILENAME = re.compile(r"[^A-Za-z0-9._-]+")+++def _size_bytes(content: str) -> int:+ """What the document weighs on the wire, not how many characters it has."""+ return len(content.encode("utf-8"))+++def _content_disposition(name: str) -> str:+ """A download header a template name cannot break out of (RFC 6266).++ The name is free text, so it may hold a quote, a newline, or a character+ outside latin-1. Interpolated raw, the first corrupts the header, the+ second appends one of the caller's choosing, and the third fails the whole+ response — headers are latin-1 on the wire. So the plain `filename` is+ reduced to an ASCII skeleton and the real name travels percent-encoded in+ `filename*`, which is what a modern client prefers anyway.+ """+ stem = _UNSAFE_IN_FILENAME.sub("-", name).strip("-") or "template"+ encoded = quote(f"{name}.yaml", safe="")+ return f"attachment; filename=\"{stem}.yaml\"; filename*=UTF-8''{encoded}"+++def _summary(row: TemplateListing, owner_name: str | None) -> TemplateSummary:+ return TemplateSummary(+ id=row.id,+ owner_id=row.owner_id,+ owner_name=owner_name,+ name=row.name,+ description=row.description,+ kind=row.kind,+ version=row.version,+ size_bytes=row.size_bytes,+ created_at=str(row.created_at),+ updated_at=str(row.updated_at),+ )+++def _detail(template: Template, owner_name: str | None) -> TemplateDetail:+ return TemplateDetail(+ id=template.id,+ owner_id=template.owner_id,+ owner_name=owner_name,+ name=template.name,+ description=template.description,+ kind=template.kind,+ version=template.version,+ size_bytes=_size_bytes(template.content),+ created_at=str(template.created_at),+ updated_at=str(template.updated_at),+ content=template.content,+ )+++async def _owner_names(+ session: AsyncSession, user_store: UserStore, owner_ids: set[str]+) -> dict[str, str]:+ names: dict[str, str] = {}+ for owner_id in owner_ids:+ owner = await user_store.get(session, owner_id)+ if owner is not None:+ names[owner_id] = owner.name+ return names+++async def _owner_name(+ session: AsyncSession, user_store: UserStore, owner_id: str+) -> str | None:+ owner = await user_store.get(session, owner_id)+ return owner.name if owner is not None else None+++def _require_storable(content: str) -> None:+ """Refuse a document no consumer could ever provision.++ Only the checker's blocking findings — not YAML, empty, not a mapping —+ are refused here. Everything else it says is advice the caller is free to+ ignore, because the format keeps moving and this check has been wrong+ about a valid document before.++ Enforced on the API rather than only in the form, so the two cannot+ disagree and a `curl` cannot walk past a rule the dashboard applies.+ """+ result = lint_template(content)+ if result.blocked:+ raise HTTPException(+ status_code=422,+ detail="; ".join(f.message for f in result.errors if f.blocking),+ )+++def _require_within_size_limit(content: str, config: SwitchConfig) -> None:+ size = _size_bytes(content)+ if size > config.template_max_bytes:+ raise HTTPException(+ status_code=413,+ detail=(+ f"Template is {size} bytes, over the {config.template_max_bytes}-byte "+ "limit for this server."+ ),+ )+++async def _load_for_management(+ session: AsyncSession, store: TemplateStore, template_id: str, user: User+) -> Template:+ """Fetch a template the caller is allowed to change, or fail saying why."""+ template = await store.get(session, template_id)+ if template is None:+ raise HTTPException(+ status_code=404, detail=f"Template not found: {template_id}"+ )+ try:+ require_manage(Principal(user.id, user.role == "admin"), template.owner_id)+ except PermissionError as e:+ raise HTTPException(status_code=403, detail=str(e)) from e+ return template++[email protected]("/templates")+async def list_templates(+ session: Annotated[AsyncSession, Depends(get_session)],+ template_store: Annotated[TemplateStore, Depends(get_template_store)],+ user_store: Annotated[UserStore, Depends(get_user_store)],+ _user: Annotated[User, Depends(get_current_user)],+ q: Annotated[str | None, Query()] = None,+ kind: Annotated[str | None, Query()] = None,+ owner_id: Annotated[str | None, Query()] = None,+) -> list[TemplateSummary]:+ """Browse the catalogue. `q` matches name or description, case-insensitively."""+ rows = await template_store.list_all(session, query=q, kind=kind, owner_id=owner_id)+ names = await _owner_names(session, user_store, {r.owner_id for r in rows})+ return [_summary(r, names.get(r.owner_id)) for r in rows]++[email protected]("/templates", status_code=201)+async def create_template(+ req: TemplateCreateRequest,+ session: Annotated[AsyncSession, Depends(get_session)],+ template_store: Annotated[TemplateStore, Depends(get_template_store)],+ user_store: Annotated[UserStore, Depends(get_user_store)],+ config: Annotated[SwitchConfig, Depends(get_config)],+ user: Annotated[User, Depends(get_current_user)],+) -> TemplateDetail:+ _require_within_size_limit(req.content, config)+ _require_storable(req.content)+ try:+ template = await template_store.create(+ session,+ Template(+ owner_id=user.id,+ name=req.name,+ description=req.description,+ kind=req.kind,+ content=req.content,+ ),+ )+ except TemplateNameTaken as e:+ raise HTTPException(status_code=409, detail=str(e)) from e+ await session.commit()+ return _detail(template, await _owner_name(session, user_store, user.id))++[email protected]("/templates/validate")+async def validate_template(+ req: TemplateValidateRequest,+ _user: Annotated[User, Depends(get_current_user)],+) -> TemplateValidateResponse:+ """Check a document without storing it.++ Declared above `/templates/{template_id}` so the literal path wins; FastAPI+ matches in declaration order and would otherwise read "validate" as an id.++ Advisory by design. It never asks whether this is a room, a group or+ something newer — the registry holds documents in shapes this server may+ not know, and upload does not consult this at all.+ """+ result = lint_template(req.content)+ return TemplateValidateResponse(+ ok=result.ok,+ blocked=result.blocked,+ errors=[+ TemplateFinding(+ code=f.code,+ message=f.message,+ subject=f.subject,+ blocking=f.blocking,+ )+ for f in result.errors+ ],+ warnings=[+ TemplateFinding(+ code=f.code,+ message=f.message,+ subject=f.subject,+ blocking=f.blocking,+ )+ for f in result.warnings+ ],+ )++[email protected]("/templates/{template_id}")+async def get_template(+ template_id: str,+ session: Annotated[AsyncSession, Depends(get_session)],+ template_store: Annotated[TemplateStore, Depends(get_template_store)],+ user_store: Annotated[UserStore, Depends(get_user_store)],+ _user: Annotated[User, Depends(get_current_user)],+) -> TemplateDetail:+ template = await template_store.get(session, template_id)+ if template is None:+ raise HTTPException(+ status_code=404, detail=f"Template not found: {template_id}"+ )+ return _detail(template, await _owner_name(session, user_store, template.owner_id))++[email protected]("/templates/{template_id}/content", response_model=None)+async def get_template_content(+ template_id: str,+ session: Annotated[AsyncSession, Depends(get_session)],+ template_store: Annotated[TemplateStore, Depends(get_template_store)],+ _user: Annotated[User, Depends(get_current_user)],+) -> Response:+ """The stored document itself, byte for byte, with no envelope around it."""+ template = await template_store.get(session, template_id)+ if template is None:+ raise HTTPException(+ status_code=404, detail=f"Template not found: {template_id}"+ )+ return Response(+ content=template.content.encode("utf-8"),+ media_type="application/x-yaml",+ headers={+ "Content-Disposition": _content_disposition(template.name),+ # The bytes are whatever someone uploaded, so a browser must not be+ # talked into sniffing them into something it will render.+ "X-Content-Type-Options": "nosniff",+ },+ )++[email protected]("/templates/{template_id}")+async def patch_template(+ template_id: str,+ req: TemplateUpdateRequest,+ session: Annotated[AsyncSession, Depends(get_session)],+ template_store: Annotated[TemplateStore, Depends(get_template_store)],+ user_store: Annotated[UserStore, Depends(get_user_store)],+ config: Annotated[SwitchConfig, Depends(get_config)],+ user: Annotated[User, Depends(get_current_user)],+) -> TemplateDetail:+ await _load_for_management(session, template_store, template_id, user)+ if req.content is not None:+ _require_within_size_limit(req.content, config)+ _require_storable(req.content)+ try:+ template = await template_store.update_fields(+ session,+ template_id,+ name=req.name,+ description=req.description,+ kind=req.kind,+ content=req.content,+ )+ except TemplateNameTaken as e:+ raise HTTPException(status_code=409, detail=str(e)) from e+ except ValueError as e:+ # The row was there for the ownership check a moment ago, so this is a+ # delete that landed in between — gone, not in conflict.+ raise HTTPException(status_code=404, detail=str(e)) from e+ await session.commit()+ return _detail(template, await _owner_name(session, user_store, template.owner_id))++[email protected]("/templates/{template_id}")+async def delete_template(+ template_id: str,+ session: Annotated[AsyncSession, Depends(get_session)],+ template_store: Annotated[TemplateStore, Depends(get_template_store)],+ user: Annotated[User, Depends(get_current_user)],+) -> TemplateDeleteResponse:+ await _load_for_management(session, template_store, template_id, user)+ try:+ await template_store.delete(session, template_id)+ except ValueError as e:+ raise HTTPException(status_code=404, detail=str(e)) from e+ await session.commit()+ return TemplateDeleteResponse(deleted_id=template_id)diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex 55c0c29ac..4750e9f67 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -108,6 +108,7 @@ from switch_core.db.stores.room_role_store import RoomRoleStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.server_connector_store import ServerConnectorStorefrom switch_core.db.stores.task_store import TaskStore+from switch_core.db.stores.template_store import TemplateStorefrom switch_core.db.stores.tenant_store import TenantStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.db.tenant_lookup import all_tenant_ids@@ -290,6 +291,7 @@ async def run(config: SwitchConfig) -> None:room_role_store = RoomRoleStore()message_store = MessageStore()media_store = MediaStore()+ template_store = TemplateStore()# ── Seed admin user + agent-registration bootstrap key ──────────────────# A second acquisition of the boot lock, distinct from the one around the@@ -487,6 +489,7 @@ async def run(config: SwitchConfig) -> None:user_store=user_store,external_user_store=external_user_store,api_key_store=api_key_store,+ template_store=template_store,resource_service=resource_service,protocol=protocol,config=config,diff --git a/core/switch_core/migrations/versions/a3f61c02d5be_templates_table.py b/core/switch_core/migrations/versions/a3f61c02d5be_templates_table.pynew file mode 100644index 000000000..d49f2567d--- /dev/null+++ b/core/switch_core/migrations/versions/a3f61c02d5be_templates_table.py@@ -0,0 +1,95 @@+"""templates are held on the server, not passed around as files++Revision ID: a3f61c02d5be+Revises: b1d7c4f0a92e++A template has until now been a YAML file someone mailed you. This table is+where a Switch server keeps one, so a template can be uploaded once and found+by everyone on the server afterwards (CHOO-2677).++Two choices here are deliberate and worth stating, because they are what let+the format keep moving without this table moving with it.++``content`` is ``Text`` and holds the document exactly as it was uploaded. The+registry never parses, validates or normalises it. That is what makes the+round-trip byte-identical, and it means a document written for a newer format+than this server understands is still stored and served back intact rather+than rejected at the door.++``kind`` is free text rather than an enum or a check constraint. Room, group+and agent templates are all coming, and they should differ by a string, not by+a migration. An enum here would buy nothing and cost a schema change per kind.++Uniqueness is ``(owner_id, name)``, not ``name``: two people may each keep a+template called "deploy-room", but neither may keep two of their own by that+name. It is deliberately not widened to include the tenant — an owner belongs+to exactly one, so scoping the name to the owner already scopes it to the+tenant.++The table is tenant-scoped like every other table holding customer data, so it+carries ``tenant_id`` and arrives with row-level security already on it rather+than waiting to be swept up later. The DDL below is a verbatim copy of+``switch_core/db/rls_ddl.py`` as it stood when this migration was written,+copied rather than imported for the reason ``265ed188ad6f`` gives: a migration+records a change that already happened, and importing the live module would+let a later edit to it silently change what this migration means.+"""++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++revision: str = "a3f61c02d5be"+down_revision: str | Sequence[str] | None = "b1d7c4f0a92e"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++REQUIRE_TENANT_FUNCTION_NAME = "require_tenant_id"+POLICY_NAME = "tenant_isolation"++_PREDICATE = f'"tenant_id" = (SELECT {REQUIRE_TENANT_FUNCTION_NAME}())'+_CREATE_POLICY = (+ f'CREATE POLICY {POLICY_NAME} ON "templates"\n'+ f" FOR ALL\n"+ f" USING ({_PREDICATE})\n"+ f" WITH CHECK ({_PREDICATE})"+)+++def upgrade() -> None:+ op.create_table(+ "templates",+ sa.Column("id", sa.Text(), primary_key=True),+ sa.Column("tenant_id", sa.Text(), nullable=False),+ sa.Column("owner_id", sa.Text(), sa.ForeignKey("users.id"), nullable=False),+ sa.Column("name", sa.Text(), nullable=False),+ sa.Column("description", sa.Text(), nullable=False),+ sa.Column("kind", sa.Text(), nullable=False),+ sa.Column("content", sa.Text(), nullable=False),+ sa.Column("version", sa.Integer(), server_default="1", nullable=False),+ sa.Column(+ "created_at",+ sa.DateTime(timezone=True),+ server_default=sa.func.now(),+ nullable=False,+ ),+ sa.Column(+ "updated_at",+ sa.DateTime(timezone=True),+ server_default=sa.func.now(),+ nullable=False,+ ),+ sa.ForeignKeyConstraint(+ ["tenant_id"], ["tenants.id"], name="fk_templates_tenant"+ ),+ sa.UniqueConstraint("owner_id", "name", name="uq_templates_owner_name"),+ sa.UniqueConstraint("id", "tenant_id", name="uq_templates_id_tenant"),+ )+ op.execute('ALTER TABLE "templates" ENABLE ROW LEVEL SECURITY')+ op.execute(_CREATE_POLICY)+++def downgrade() -> None:+ op.execute(f'DROP POLICY IF EXISTS {POLICY_NAME} ON "templates"')+ op.drop_table("templates")diff --git a/core/switch_core/template_lint.py b/core/switch_core/template_lint.pynew file mode 100644index 000000000..680604e44--- /dev/null+++ b/core/switch_core/template_lint.py@@ -0,0 +1,310 @@+"""Advisory checks on a template document, for a form to show before upload.++Deliberately weaker than provisioning. It answers "will this obviously not do+what you meant", never "is this a valid room template" — the registry stores+documents whose shape this server may not know yet, and a check that insisted+on today's shape would start refusing tomorrow's. Group templates already have+a different top-level key from room templates, and agent templates are coming,+so nothing here asks what kind of document it is looking at.++What that leaves is the mistakes that are wrong under every shape: text that+is not YAML, a params block that provisioning will reject, and placeholders+that do not line up with the parameters declared for them — the typo that+otherwise ships silently, because an undeclared `{owner}` is left in the+document verbatim rather than failing.++Nothing here rejects an upload. The registry accepts what it is given; this+only lets a person see the problem first.+"""++from __future__ import annotations++import re+from dataclasses import dataclass, field+from typing import Any++import yaml+from pydantic import ValidationError++from switch_core.rooms_yaml import PLACEHOLDER_RE, ParamSpec++# Top-level keys any shape of template may carry, across every shape known to+# be in flight — room, group, and the kickoff message that rides beside them.+# Additive on purpose, and only ever a warning: an unrecognised key is as+# likely to be a format this server predates as it is to be a typo.+_KNOWN_TOP_LEVEL = frozenset({"room", "group", "rooms", "params", "version", "kickoff"})++# `{$...}` placeholders the server fills in itself. A template does not declare+# them and must not be told to.+_BUILTINS = frozenset({"$creator", "$creator_email", "$date", "$timestamp"})++# Matched here rather than left to `PLACEHOLDER_RE`, which only learned about+# the `$` prefix alongside the builtins themselves. Scanning for them directly+# means a misspelled `{$creatr}` is caught the same way whichever version of+# the format module this server is running.+_BUILTIN_RE = re.compile(r"\{(\$[A-Za-z_][A-Za-z0-9_]*)\}")+++# The findings an upload is refused for. Deliberately only the three that are+# true of a template under every shape it could ever take: text that is not+# YAML, nothing at all, or something other than a mapping. A document failing+# one of these cannot be provisioned by any consumer, now or later, so storing+# it serves nobody.+#+# Everything else stays advisory, and the reason is evidence rather than+# caution. The params checks are the format's, and the format moves: this+# checker called the canonical example invalid twice in a week. Console's+# parser and this server also disagree today about a bare param with no spec —+# Console reads it as a string, the server refuses it — so a block on that+# would refuse a document the Console wizard renders happily.+_BLOCKING_CODES = frozenset({"empty", "invalid_yaml", "not_a_mapping"})+++@dataclass(frozen=True)+class Finding:+ code: str+ message: str+ # The param or key the finding is about, when it is about one.+ subject: str | None = None++ @property+ def blocking(self) -> bool:+ return self.code in _BLOCKING_CODES+++@dataclass(frozen=True)+class LintResult:+ errors: list[Finding] = field(default_factory=list)+ warnings: list[Finding] = field(default_factory=list)++ @property+ def ok(self) -> bool:+ return not self.errors++ @property+ def blocked(self) -> bool:+ """Whether an upload of this document should be refused outright."""+ return any(f.blocking for f in self.errors)+++def _walk_strings(node: Any) -> list[str]:+ """Every string anywhere in the document, so no placeholder is missed."""+ if isinstance(node, str):+ return [node]+ if isinstance(node, dict):+ found: list[str] = []+ for key, value in node.items():+ if isinstance(key, str):+ found.append(key)+ found.extend(_walk_strings(value))+ return found+ if isinstance(node, list):+ return [s for item in node for s in _walk_strings(item)]+ return []+++def _unknown_keys(details: list[Any]) -> set[str]:+ """The field names an `extra_forbidden` complaint was about."""+ return {str(d["loc"][-1]) for d in details if d["loc"]}+++def _check_params(raw: Any, errors: list[Finding], warnings: list[Finding]) -> set[str]:+ """Validate the params block against the spec provisioning will apply.++ Uses `ParamSpec` itself rather than re-describing it, so a form cannot+ accept a param that provisioning would then refuse — and so a field added+ to the spec is understood here the moment it is added there, with nothing+ to keep in step by hand.++ One kind of complaint is demoted to a warning: a field `ParamSpec` does not+ know. `extra="forbid"` cannot tell "you misspelled it" from "this server is+ older than the template", and the second is ordinary for a registry that+ holds documents written against a newer Switch than the one reading them.+ """+ if not isinstance(raw, dict):+ errors.append(+ Finding(+ "params_not_a_mapping",+ "'params' must be a mapping of parameter name to its spec.",+ )+ )+ return set()++ declared: set[str] = set()+ for name, spec in raw.items():+ if not isinstance(name, str):+ errors.append(+ Finding(+ "param_name_not_a_string", f"Parameter name {name!r} is not text."+ )+ )+ continue+ declared.add(name)+ if spec is None:+ errors.append(+ Finding(+ "param_has_no_spec",+ f"Parameter '{name}' has no spec. Give it at least a type.",+ name,+ )+ )+ continue+ try:+ parsed = ParamSpec.model_validate(spec)+ except ValidationError as e:+ unknown = [d for d in e.errors() if d["type"] == "extra_forbidden"]+ malformed = [d for d in e.errors() if d["type"] != "extra_forbidden"]+ for detail in unknown:+ where = ".".join(str(p) for p in detail["loc"]) or "spec"+ warnings.append(+ Finding(+ "unknown_param_field",+ f"Parameter '{name}' sets '{where}', which this server "+ "does not know. It may be from a newer Switch, or a typo.",+ name,+ )+ )+ for detail in malformed:+ where = ".".join(str(p) for p in detail["loc"]) or "spec"+ errors.append(+ Finding(+ "invalid_param_spec",+ f"Parameter '{name}' is not valid: {where} — {detail['msg']}.",+ name,+ )+ )+ # An unknown field is the only complaint, so the rest of the spec+ # is sound and the checks below still have something to say.+ if malformed:+ continue+ try:+ parsed = ParamSpec.model_validate(+ {k: v for k, v in spec.items() if k not in _unknown_keys(unknown)}+ if isinstance(spec, dict)+ else spec+ )+ except ValidationError:+ continue++ # Two things a well-formed ParamSpec can still say that provisioning+ # will refuse. They surface here because they only bite at the moment+ # somebody tries to use the template, which is far from the mistake.+ if parsed.type == "enum":+ if not parsed.enum:+ errors.append(+ Finding(+ "enum_without_choices",+ f"Parameter '{name}' is an enum but lists no choices.",+ name,+ )+ )+ elif parsed.default is not None and parsed.default not in parsed.enum:+ errors.append(+ Finding(+ "default_not_in_enum",+ f"Parameter '{name}' defaults to {parsed.default!r}, which is "+ f"not one of its choices ({', '.join(parsed.enum)}).",+ name,+ )+ )+ return declared+++def lint_template(text: str) -> LintResult:+ """Check a template document without storing or provisioning anything."""+ errors: list[Finding] = []+ warnings: list[Finding] = []++ if not text.strip():+ errors.append(Finding("empty", "The document is empty."))+ return LintResult(errors, warnings)++ try:+ document = yaml.safe_load(text)+ except yaml.YAMLError as e:+ # A mark carries the line and column, which is the whole value of the+ # message to someone staring at an editor.+ mark = getattr(e, "problem_mark", None)+ where = f" at line {mark.line + 1}, column {mark.column + 1}" if mark else ""+ problem = getattr(e, "problem", None) or "could not be parsed"+ errors.append(Finding("invalid_yaml", f"Not valid YAML{where}: {problem}."))+ return LintResult(errors, warnings)++ if document is None:+ errors.append(Finding("empty", "The document is empty."))+ return LintResult(errors, warnings)++ if not isinstance(document, dict):+ errors.append(+ Finding(+ "not_a_mapping",+ "The document must be a mapping of keys at the top level, "+ f"not {type(document).__name__}.",+ )+ )+ return LintResult(errors, warnings)++ for key in sorted(k for k in document if isinstance(k, str)):+ if key not in _KNOWN_TOP_LEVEL:+ warnings.append(+ Finding(+ "unknown_top_level_key",+ f"'{key}' is not a key this server recognises. It will be "+ "stored as-is, but check it is not a typo.",+ key,+ )+ )++ declared = (+ _check_params(document["params"], errors, warnings)+ if "params" in document+ else set()+ )++ # Placeholders are looked for everywhere except the params block, which+ # declares them rather than using them.+ body = {k: v for k, v in document.items() if k != "params"}+ body_strings = _walk_strings(body)+ used = {+ match+ for text_node in body_strings+ for match in re.findall(PLACEHOLDER_RE, text_node)+ }+ builtins_used = {+ match for text_node in body_strings for match in _BUILTIN_RE.findall(text_node)+ }+ # Whether `$creator` also came back from PLACEHOLDER_RE depends on this+ # server's version of it; either way it is a builtin, not a missing param.+ used -= builtins_used++ # `{$...}` is the server's to fill, not the template's to declare, so it is+ # held to a different question: is it one the server actually knows?+ for name in sorted(builtins_used - _BUILTINS):+ warnings.append(+ Finding(+ "unknown_builtin",+ f"'{{{name}}}' looks like a server-provided value, but this "+ f"server provides only {', '.join(sorted(_BUILTINS))}.",+ name,+ )+ )++ for name in sorted(used - declared):+ warnings.append(+ Finding(+ "undeclared_placeholder",+ f"'{{{name}}}' is used but no parameter declares it, so it will "+ "be left in the document as written.",+ name,+ )+ )+ for name in sorted(declared - used):+ warnings.append(+ Finding(+ "unused_param",+ f"Parameter '{name}' is declared but never used.",+ name,+ )+ )++ return LintResult(errors, warnings)diff --git a/core/tests/switch_core/db/stores/test_template_store.py b/core/tests/switch_core/db/stores/test_template_store.pynew file mode 100644index 000000000..44ec391ca--- /dev/null+++ b/core/tests/switch_core/db/stores/test_template_store.py@@ -0,0 +1,425 @@+"""The template registry's storage layer, against real Postgres.++The load-bearing property is that a document survives storage untouched: the+registry keeps templates for formats it does not parse, so anything it does to+the bytes on the way in or out is a bug.+"""++from __future__ import annotations++import asyncio++import pytest+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.models import Template, User+from switch_core.db.stores.template_store import TemplateNameTaken, TemplateStore++_STORE = TemplateStore()++# A document with a params block, CRLF line endings, trailing whitespace, tabs,+# unicode and no trailing newline — every one of which a "helpful" normaliser+# would quietly rewrite.+_AWKWARD_DOCUMENT = (+ "params:\r\n"+ " owner:\r\n"+ " type: string\r\n"+ "\tdescription: tab-indented on purpose \r\n"+ "room:\r\n"+ ' name: "{owner} — café ☕"\r\n'+ " description: |\n"+ " trailing spaces follow: \n"+ " and a tab:\there\n"+ " agents: []"+)+++async def _make_user(session: AsyncSession, name: str) -> User:+ user = User(name=name, email=f"{name}@test", role="user", password_hash="x")+ session.add(user)+ await session.flush()+ return user+++async def _make_template(+ session: AsyncSession,+ *,+ owner_id: str,+ name: str,+ description: str = "d",+ kind: str = "room",+ content: str = "room:\n name: r\n",+) -> Template:+ return await _STORE.create(+ session,+ Template(+ owner_id=owner_id,+ name=name,+ description=description,+ kind=kind,+ content=content,+ ),+ )+++class TestTemplateStoreRoundTrip:+ async def test_document_is_stored_byte_identical(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ owner = await _make_user(session, "alice")+ created = await _make_template(+ session, owner_id=owner.id, name="awkward", content=_AWKWARD_DOCUMENT+ )+ await session.commit()++ # A second session, so the assertion reads from Postgres rather than+ # from the identity map that just wrote it.+ async with session_factory() as session:+ fetched = await _STORE.get(session, created.id)+ assert fetched is not None+ assert fetched.content == _AWKWARD_DOCUMENT++ async def test_a_document_the_server_cannot_parse_is_still_stored(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """Kind-agnostic storage: unknown kinds and unparseable text both keep."""+ garbage = "this: is: not: valid: yaml: at: all\n\t- [unclosed"+ async with session_factory() as session:+ owner = await _make_user(session, "alice")+ created = await _make_template(+ session,+ owner_id=owner.id,+ name="future-format",+ kind="constellation",+ content=garbage,+ )+ await session.commit()++ async with session_factory() as session:+ fetched = await _STORE.get(session, created.id)+ assert fetched is not None+ assert fetched.content == garbage+ assert fetched.kind == "constellation"++ async def test_new_template_starts_at_version_one(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ owner = await _make_user(session, "alice")+ created = await _make_template(session, owner_id=owner.id, name="t")+ await session.commit()+ await session.refresh(created)+ assert created.version == 1+++class TestTemplateStoreListing:+ async def test_listing_reports_size_without_reading_the_document(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """A catalogue row carries a byte count, not the bytes.++ Measured by Postgres, so listing a thousand templates does not drag a+ thousand documents through it — and measured in bytes, so it agrees+ with the upload limit rather than undercounting multibyte text.+ """+ async with session_factory() as session:+ owner = await _make_user(session, "alice")+ await _make_template(+ session, owner_id=owner.id, name="coffee", content="☕" * 10+ )++ (row,) = await _STORE.list_all(session)+ assert row.size_bytes == 30+ assert not hasattr(row, "content")++ async def test_lists_templates_from_every_owner(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """The registry is a server-wide catalogue, not a per-user shelf."""+ async with session_factory() as session:+ alice = await _make_user(session, "alice")+ bob = await _make_user(session, "bob")+ await _make_template(session, owner_id=alice.id, name="alice-room")+ await _make_template(session, owner_id=bob.id, name="bob-room")++ listed = {t.name for t in await _STORE.list_all(session)}+ assert listed == {"alice-room", "bob-room"}++ async def test_search_matches_name_and_description(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ owner = await _make_user(session, "alice")+ await _make_template(+ session, owner_id=owner.id, name="deploy-room", description="unrelated"+ )+ await _make_template(+ session,+ owner_id=owner.id,+ name="unrelated",+ description="for DEPLOYing things",+ )+ await _make_template(+ session, owner_id=owner.id, name="other", description="nothing here"+ )++ hits = {t.name for t in await _STORE.list_all(session, query="deploy")}+ assert hits == {"deploy-room", "unrelated"}++ async def test_search_treats_wildcards_as_literal_text(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """`%` is a character someone typed, not a match-everything operator."""+ async with session_factory() as session:+ owner = await _make_user(session, "alice")+ await _make_template(session, owner_id=owner.id, name="100%-coverage")+ await _make_template(session, owner_id=owner.id, name="plain")++ hits = {t.name for t in await _STORE.list_all(session, query="%")}+ assert hits == {"100%-coverage"}++ async def test_filters_by_kind_and_owner(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ alice = await _make_user(session, "alice")+ bob = await _make_user(session, "bob")+ await _make_template(session, owner_id=alice.id, name="a-room", kind="room")+ await _make_template(+ session, owner_id=alice.id, name="a-group", kind="group"+ )+ await _make_template(session, owner_id=bob.id, name="b-room", kind="room")++ by_kind = {t.name for t in await _STORE.list_all(session, kind="room")}+ assert by_kind == {"a-room", "b-room"}++ by_owner = {+ t.name for t in await _STORE.list_all(session, owner_id=alice.id)+ }+ assert by_owner == {"a-room", "a-group"}+++class TestTemplateStoreNaming:+ async def test_one_owner_cannot_reuse_a_name(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ owner = await _make_user(session, "alice")+ await _make_template(session, owner_id=owner.id, name="deploy-room")++ with pytest.raises(+ TemplateNameTaken, match="already have a template named"+ ):+ await _make_template(session, owner_id=owner.id, name="deploy-room")++ async def test_a_clash_leaves_the_session_usable(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """The savepoint's whole point: the caller can carry on after the error."""+ async with session_factory() as session:+ owner = await _make_user(session, "alice")+ await _make_template(session, owner_id=owner.id, name="deploy-room")+ with pytest.raises(TemplateNameTaken):+ await _make_template(session, owner_id=owner.id, name="deploy-room")++ await _make_template(session, owner_id=owner.id, name="something-else")+ assert len(await _STORE.list_all(session)) == 2++ async def test_two_owners_may_share_a_name(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ alice = await _make_user(session, "alice")+ bob = await _make_user(session, "bob")+ await _make_template(session, owner_id=alice.id, name="deploy-room")+ await _make_template(session, owner_id=bob.id, name="deploy-room")++ assert len(await _STORE.list_all(session)) == 2+++class TestTemplateStoreUpdate:+ async def test_replacing_content_bumps_the_version(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ owner = await _make_user(session, "alice")+ created = await _make_template(session, owner_id=owner.id, name="t")+ await session.commit()++ updated = await _STORE.update_fields(+ session, created.id, content="room:\n name: changed\n"+ )+ assert updated.version == 2+ assert updated.content == "room:\n name: changed\n"++ async def test_metadata_only_edit_leaves_the_version_alone(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ owner = await _make_user(session, "alice")+ created = await _make_template(session, owner_id=owner.id, name="t")+ await session.commit()++ updated = await _STORE.update_fields(+ session, created.id, description="a better description"+ )+ assert updated.version == 1+ assert updated.description == "a better description"++ async def test_rewriting_identical_content_is_not_a_new_revision(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ owner = await _make_user(session, "alice")+ created = await _make_template(+ session, owner_id=owner.id, name="t", content="room:\n name: r\n"+ )+ await session.commit()++ updated = await _STORE.update_fields(+ session, created.id, content="room:\n name: r\n"+ )+ assert updated.version == 1++ async def test_renaming_onto_a_name_you_already_use_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ owner = await _make_user(session, "alice")+ await _make_template(session, owner_id=owner.id, name="taken")+ other = await _make_template(session, owner_id=owner.id, name="free")+ await session.commit()++ with pytest.raises(+ TemplateNameTaken, match="already have a template named"+ ):+ await _STORE.update_fields(session, other.id, name="taken")++ async def test_server_computed_timestamps_are_readable_after_an_update(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """`updated_at` is set by Postgres, so a flush leaves it expired.++ Reading it later would lazy-load, and a lazy load from synchronous code+ raises MissingGreenlet instead of returning a timestamp — so the store+ has to hand back a row that is fully loaded.+ """+ async with session_factory() as session:+ owner = await _make_user(session, "alice")+ created = await _make_template(session, owner_id=owner.id, name="t")+ await session.commit()++ updated = await _STORE.update_fields(session, created.id, description="x")+ await session.commit()++ assert updated.updated_at is not None+ assert updated.created_at is not None++ async def test_two_concurrent_edits_do_not_lose_one(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """The revision counts edits, so both of two racing edits must land.++ Bumping a revision means reading the old one first. Without the row+ lock both readers see version 1, both write 2, and the later write+ silently replaces the earlier one while both callers are told they+ succeeded — data loss with no error anywhere.+ """+ async with session_factory() as setup:+ owner = await _make_user(setup, "alice")+ created = await _make_template(setup, owner_id=owner.id, name="t")+ await setup.commit()+ template_id, owner_id = created.id, owner.id++ async def edit(content: str) -> None:+ async with session_factory() as session:+ await _STORE.update_fields(session, template_id, content=content)+ await session.commit()++ # Genuinely concurrent: two sessions, two connections, one row.+ await asyncio.gather(edit("room:\n name: one\n"), edit("room:\n name: two\n"))++ async with session_factory() as session:+ final = await _STORE.get(session, template_id)+ assert final is not None+ # Three, not two: each edit counted, neither overwrote the other's+ # bump. Which of the two documents won is up to the scheduler.+ assert final.version == 3+ assert final.content in (+ "room:\n name: one\n",+ "room:\n name: two\n",+ )+ assert final.owner_id == owner_id++ async def test_no_lost_update_when_the_row_was_already_read_unlocked(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """The router's real order: read to check ownership, then edit.++ That first read seeds the session's identity map, so the locked read+ inside `update_fields` has a stale copy sitting in front of it. If the+ lock does not displace that copy, the edit is computed from the value+ the loser read and the winner's write disappears — with the lock in+ place and both callers told they succeeded.+ """+ async with session_factory() as setup:+ owner = await _make_user(setup, "alice")+ created = await _make_template(setup, owner_id=owner.id, name="t")+ await setup.commit()+ template_id = created.id++ loser_has_read = asyncio.Event()+ winner_committed = asyncio.Event()++ async def winner() -> None:+ await loser_has_read.wait()+ async with session_factory() as session:+ await _STORE.get(session, template_id)+ await _STORE.update_fields(session, template_id, content="from-winner")+ await session.commit()+ winner_committed.set()++ async def loser() -> None:+ async with session_factory() as session:+ # Ownership check, unlocked — this is what seeds the stale copy.+ await _STORE.get(session, template_id)+ loser_has_read.set()+ await winner_committed.wait()+ await _STORE.update_fields(session, template_id, content="from-loser")+ await session.commit()++ await asyncio.gather(winner(), loser())++ async with session_factory() as session:+ final = await _STORE.get(session, template_id)+ assert final is not None+ assert final.version == 3, "an edit was computed from a stale read"+ assert final.content == "from-loser"++ async def test_update_of_a_missing_template_raises(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ with pytest.raises(ValueError, match="Template not found"):+ await _STORE.update_fields(session, "nope", description="x")+++class TestTemplateStoreDelete:+ async def test_delete_removes_the_template(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ owner = await _make_user(session, "alice")+ created = await _make_template(session, owner_id=owner.id, name="t")++ await _STORE.delete(session, created.id)+ assert await _STORE.get(session, created.id) is None+ assert await _STORE.list_all(session) == []++ async def test_delete_of_a_missing_template_raises(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ with pytest.raises(ValueError, match="Template not found"):+ await _STORE.delete(session, "nope")diff --git a/core/tests/switch_core/db/test_row_level_security.py b/core/tests/switch_core/db/test_row_level_security.pyindex 7e22f6410..b1446b51c 100644--- a/core/tests/switch_core/db/test_row_level_security.py+++ b/core/tests/switch_core/db/test_row_level_security.py@@ -406,25 +406,53 @@ class TestCatalogueCoverage:f"{wrong_predicate}")- async def test_the_migrations_frozen_table_list_matches_the_models(self) -> None:+ async def test_the_migrations_frozen_table_list_names_no_table_the_models_lost(+ self,+ ) -> None:"""`265ed188ad6f` carries its own copy of the scoped-table list, on- purpose — a migration must not change meaning because a model did. The- cost of a frozen copy is that it can silently fall behind: a table- added to the models gets a policy from `create_all`, so every test in- this file still passes, while a real deployment built by Alembic has- none. Nothing compared the two before this; they agree at 38 today.-- A deliberate divergence is still expressible — it just has to be a- new migration, which is the point.+ purpose — a migration must not change meaning because a model did.++ Only one direction of that comparison can be asserted here. A table+ added to the models *after* this revision cannot appear in its list:+ the revision runs before the table exists, so an `ALTER TABLE` naming+ it would abort `upgrade head` on a fresh database. Such a table brings+ its own `ENABLE ROW LEVEL SECURITY` and policy in its own revision,+ which is what this revision's own prose means by "a deliberate+ divergence just has to be a new migration".++ So this asserts the direction that stays meaningful: the frozen list+ must name nothing the models have since dropped, which would leave the+ chain policing a table that is no longer there.++ The direction it cannot check — that every scoped model table really+ does end up policed — is not left uncovered. It is checked against a+ database rather than a source list, by+ `test_frozen_ddl_matches_create_all.py`, which replays the whole chain+ and compares the policies and RLS-enabled sets it produces against the+ ones `create_all` builds from `rls_ddl.py`. That is the stronger+ statement, and it sees every later revision."""from_models = scoped_tables(Base.metadata)from_migration = dict(_migration_module().SCOPED_TABLES)- assert from_migration == from_models, (- "the frozen SCOPED_TABLES in migration 265ed188ad6f no longer "- "matches the models: only in the migration "- f"{sorted(set(from_migration) - set(from_models))}, only in the "- f"models {sorted(set(from_models) - set(from_migration))}"+ stale = {+ table: column+ for table, column in from_migration.items()+ if table not in from_models+ }+ assert stale == {}, (+ "the frozen SCOPED_TABLES in migration 265ed188ad6f names tables "+ f"the models no longer have: {sorted(stale)}"+ )+ disagreeing = {+ table: (column, from_models[table])+ for table, column in from_migration.items()+ if table in from_models and from_models[table] != column+ }+ assert disagreeing == {}, (+ "the frozen SCOPED_TABLES in migration 265ed188ad6f policies a "+ "different column than the models scope by (migration, models): "+ f"{disagreeing}")async def test_global_tables_carry_no_policy(diff --git a/core/tests/switch_core/gateway/test_template_http.py b/core/tests/switch_core/gateway/test_template_http.pynew file mode 100644index 000000000..38038e235--- /dev/null+++ b/core/tests/switch_core/gateway/test_template_http.py@@ -0,0 +1,567 @@+"""The registry over real HTTP, against real Postgres.++The other route tests call the handler coroutines directly, which skips the+part the acceptance condition is actually about: a template has to survive+being JSON-encoded onto the wire and decoded off it again. A document full of+CRLFs, tabs and multibyte characters is exactly what a careless encoding step+mangles, so it makes the trip here for real.+"""++from __future__ import annotations++from collections.abc import AsyncIterator++import httpx+import pytest+import pytest_asyncio+from fastapi import FastAPI+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.config import SwitchConfig+from switch_core.db.models import User+from switch_core.db.stores.template_store import TemplateStore+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_session,+ get_session_factory,+ get_template_store,+ get_user_store,+)+from switch_core.gateway.templates import router++_AWKWARD_DOCUMENT = (+ "params:\r\n"+ " owner:\r\n"+ " type: string\r\n"+ "room:\r\n"+ ' name: "{owner} — café ☕" \r\n'+ " description: |\n"+ " tabbed:\there\n"+ " quoted: \"double\" and 'single'\n"+ " backslash: C:\\path\\to\\thing\n"+ " agents: []"+)+++def _config() -> SwitchConfig:+ return SwitchConfig( # type: ignore[call-arg]+ db_host="localhost",+ db_port="5432",+ db_user="u",+ db_password="p",+ db_name="d",+ matrix_server_name="test",+ agent_registration_token="t",+ jwt_secret_key="s",+ gateway_admin_email="admin@test",+ gateway_admin_password="pw",+ )+++@pytest_asyncio.fixture+async def users(+ session_factory: async_sessionmaker[AsyncSession],+) -> AsyncIterator[dict[str, User]]:+ """Two owners, so cross-owner listing and deletion can be exercised."""+ async with session_factory() as session:+ alice = User(name="alice", email="alice@test", role="user", password_hash="x")+ bob = User(name="bob", email="bob@test", role="user", password_hash="x")+ session.add_all([alice, bob])+ await session.commit()+ yield {"alice": alice, "bob": bob}+++def _client(+ session_factory: async_sessionmaker[AsyncSession], acting_as: User+) -> httpx.AsyncClient:+ """An app with only this router mounted and its dependencies overridden.++ Driven over an in-process ASGI transport rather than `TestClient`: that one+ runs the app on an event loop of its own, and these Postgres connections+ belong to the test's loop, so the two cannot share a connection.++ Deliberately not `init_dependencies`, which populates a process-global with+ no teardown and would leak into later tests.+ """++ async def _session() -> AsyncIterator[AsyncSession]:+ async with session_factory() as session:+ yield session++ app = FastAPI()+ app.include_router(router)+ app.dependency_overrides[get_session] = _session+ app.dependency_overrides[get_template_store] = TemplateStore+ app.dependency_overrides[get_user_store] = UserStore+ app.dependency_overrides[get_config] = _config+ app.dependency_overrides[get_current_user] = lambda: acting_as+ return httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url="http://test"+ )+++async def _upload(client: httpx.AsyncClient, **body: object) -> dict:+ payload: dict[str, object] = {+ "name": "t",+ "description": "d",+ "kind": "room",+ "content": "room:\n name: r\n",+ }+ payload.update(body)+ response = await client.post("/templates", json=payload)+ assert response.status_code == 201, response.text+ return response.json() # type: ignore[no-any-return]+++class TestOverTheWire:+ async def test_a_document_survives_the_round_trip_byte_for_byte(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ client = _client(session_factory, users["alice"])+ created = await _upload(client, name="awkward", content=_AWKWARD_DOCUMENT)++ detail = await client.get(f"/templates/{created['id']}")+ assert detail.status_code == 200+ assert detail.json()["content"] == _AWKWARD_DOCUMENT++ raw = await client.get(f"/templates/{created['id']}/content")+ assert raw.status_code == 200+ assert raw.content.decode("utf-8") == _AWKWARD_DOCUMENT+ assert raw.headers["content-type"].startswith("application/x-yaml")++ async def test_the_raw_document_carries_no_json_envelope(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ """It should be pipeable straight into a file, not unwrapped first."""+ client = _client(session_factory, users["alice"])+ created = await _upload(client, name="plain", content=_AWKWARD_DOCUMENT)++ raw = await client.get(f"/templates/{created['id']}/content")+ assert not raw.text.startswith("{")+ assert "owner_id" not in raw.text++ @pytest.mark.parametrize(+ "name",+ ["café ☕", 'has"quote', "line\r\nX-Injected: yes", "../../etc/passwd", " "],+ ids=["non-latin1", "quote", "crlf", "traversal", "blank-ish"],+ )+ async def test_a_hostile_name_cannot_break_the_download_header(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ users: dict[str, User],+ name: str,+ ) -> None:+ """Headers are latin-1 on the wire and the name is free text.++ Interpolated raw, a `☕` fails the response outright and a CRLF appends+ a header of the caller's choosing.+ """+ client = _client(session_factory, users["alice"])+ created = await _upload(client, name=name, content="room:\n name: r\n")++ raw = await client.get(f"/templates/{created['id']}/content")+ assert raw.status_code == 200+ assert raw.content == b"room:\n name: r\n"++ disposition = raw.headers["content-disposition"]+ assert "\r" not in disposition and "\n" not in disposition+ assert "X-Injected" not in raw.headers+ # The plain filename is an ASCII skeleton; the real name rides in+ # `filename*`, percent-encoded.+ ascii_part = disposition.split(";")[1]+ assert ascii_part.strip().startswith('filename="')+ assert ascii_part.encode("latin-1")+ assert "filename*=UTF-8''" in disposition++ async def test_the_download_refuses_to_be_sniffed(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ """The bytes are whatever someone uploaded, HTML included."""+ client = _client(session_factory, users["alice"])+ created = await _upload(+ client, name="sneaky", content="room:\n name: <script>alert(1)</script>\n"+ )++ raw = await client.get(f"/templates/{created['id']}/content")+ assert raw.headers["x-content-type-options"] == "nosniff"+ assert raw.headers["content-type"].startswith("application/x-yaml")++ async def test_the_two_endpoints_agree_on_a_document_s_size(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ """Listing measures in Postgres, detail measures in Python.++ Two ways of counting the same bytes, so a template that reported one+ size in the catalogue and another on its own page would be the visible+ symptom of them having drifted apart.+ """+ client = _client(session_factory, users["alice"])+ created = await _upload(client, name="sized", content=_AWKWARD_DOCUMENT)+ expected = len(_AWKWARD_DOCUMENT.encode("utf-8"))++ listing = await client.get("/templates", params={"q": "sized"})+ (row,) = listing.json()+ detail = await client.get(f"/templates/{created['id']}")++ assert row["size_bytes"] == expected+ assert detail.json()["size_bytes"] == expected+ # And it is bytes, not characters — the document has multibyte text in it.+ assert expected > len(_AWKWARD_DOCUMENT)++ async def test_validate_reports_without_storing(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ client = _client(session_factory, users["alice"])++ response = await client.post(+ "/templates/validate", json={"content": "a: [unclosed\n"}+ )+ assert response.status_code == 200+ body = response.json()+ assert body["ok"] is False+ assert [e["code"] for e in body["errors"]] == ["invalid_yaml"]++ # The point of it: nothing was created by asking.+ listing = await client.get("/templates")+ assert listing.json() == []++ async def test_a_document_that_is_not_yaml_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ """The one refusal: nothing could ever provision this.++ Enforced here and not only in the form, so a `curl` cannot walk past a+ rule the dashboard applies.+ """+ client = _client(session_factory, users["alice"])+ garbage = "a: [unclosed\n"++ check = await client.post("/templates/validate", json={"content": garbage})+ assert check.json()["blocked"] is True++ refused = await client.post(+ "/templates",+ json={+ "name": "not-yaml",+ "description": "d",+ "kind": "room",+ "content": garbage,+ },+ )+ assert refused.status_code == 422+ assert "Not valid YAML" in refused.json()["detail"]+ assert (await client.get("/templates")).json() == []++ async def test_everything_else_it_says_is_advice(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ """A document the checker dislikes but cannot prove wrong still stores.++ The format keeps moving and this checker has called a valid document+ invalid before, so only the refusal that holds under every shape is+ allowed to bar the door.+ """+ client = _client(session_factory, users["alice"])+ # An enum with no choices: a real error, and still not this checker's+ # decision to make on the registry's behalf.+ doubtful = "params:\n v:\n type: enum\nroom:\n name: '{v}'\n"++ check = await client.post("/templates/validate", json={"content": doubtful})+ assert check.json()["ok"] is False+ assert check.json()["blocked"] is False++ created = await _upload(client, name="stored-anyway", content=doubtful)+ raw = await client.get(f"/templates/{created['id']}/content")+ assert raw.content.decode("utf-8") == doubtful++ async def test_an_edit_cannot_replace_a_document_with_something_unparseable(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ client = _client(session_factory, users["alice"])+ created = await _upload(client, name="fine", content="room:\n name: r\n")++ refused = await client.patch(+ f"/templates/{created['id']}", json={"content": "a: [unclosed\n"}+ )+ assert refused.status_code == 422++ raw = await client.get(f"/templates/{created['id']}/content")+ assert raw.content.decode("utf-8") == "room:\n name: r\n"++ async def test_validate_warns_without_failing(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ client = _client(session_factory, users["alice"])+ response = await client.post(+ "/templates/validate",+ json={+ "content": (+ "params:\n owner:\n type: string\nroom:\n name: '{ownr}'\n"+ )+ },+ )+ body = response.json()+ assert body["ok"] is True+ assert body["errors"] == []+ assert {w["code"] for w in body["warnings"]} == {+ "undeclared_placeholder",+ "unused_param",+ }++ async def test_validate_accepts_a_shape_this_server_does_not_provision(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ """A group template has no `room:` key and must not be called wrong."""+ client = _client(session_factory, users["alice"])+ response = await client.post(+ "/templates/validate",+ json={+ "content": "group:\n name: workstream\nrooms:\n - name: planning\n"+ },+ )+ assert response.json() == {+ "ok": True,+ "blocked": False,+ "errors": [],+ "warnings": [],+ }++ async def test_validate_is_not_mistaken_for_a_template_id(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ """`/templates/validate` sits beside `/templates/{id}`; order decides."""+ client = _client(session_factory, users["alice"])+ response = await client.post(+ "/templates/validate", json={"content": "room: {}"}+ )+ assert response.status_code == 200+ assert "ok" in response.json()++ async def test_validate_needs_authentication_like_everything_else(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ async def _no_session() -> AsyncIterator[None]:+ yield None++ app = FastAPI()+ app.include_router(router)+ # Stubbed because FastAPI resolves every sub-dependency before the+ # endpoint runs, so `get_current_user` cannot reach its 401 without+ # them. Left real, it is the thing under test.+ app.dependency_overrides[get_session] = _no_session+ app.dependency_overrides[get_session_factory] = lambda: None+ app.dependency_overrides[get_user_store] = lambda: None+ app.dependency_overrides[get_config] = _config+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url="http://test"+ ) as anonymous:+ response = await anonymous.post(+ "/templates/validate", json={"content": "room: {}"}+ )+ assert response.status_code in (401, 403)++ async def test_the_catalogue_shows_every_owners_templates(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ await _upload(_client(session_factory, users["alice"]), name="alice-room")+ await _upload(_client(session_factory, users["bob"]), name="bob-room")++ for who in ("alice", "bob"):+ listing = await _client(session_factory, users[who]).get("/templates")+ assert listing.status_code == 200+ assert {t["name"] for t in listing.json()} == {"alice-room", "bob-room"}++ async def test_search_narrows_the_catalogue(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ client = _client(session_factory, users["alice"])+ await _upload(client, name="deploy-room", description="x")+ await _upload(client, name="other", description="for DEPLOYing")+ await _upload(client, name="unrelated", description="x")++ hits = await client.get("/templates", params={"q": "deploy"})+ assert {t["name"] for t in hits.json()} == {"deploy-room", "other"}++ async def test_deleting_someone_elses_template_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ created = await _upload(+ _client(session_factory, users["alice"]), name="alice-room"+ )+ as_bob = _client(session_factory, users["bob"])++ refused = await as_bob.delete(f"/templates/{created['id']}")+ assert refused.status_code == 403++ # Still there, and still readable by the person who was refused.+ survived = await as_bob.get(f"/templates/{created['id']}")+ assert survived.status_code == 200++ async def test_an_owner_may_delete_their_own(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ client = _client(session_factory, users["alice"])+ created = await _upload(client, name="alice-room")++ deleted = await client.delete(f"/templates/{created['id']}")+ assert deleted.status_code == 200+ assert deleted.json() == {"deleted_id": created["id"]}++ gone = await client.get(f"/templates/{created['id']}")+ assert gone.status_code == 404++ async def test_reusing_your_own_name_is_a_409(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ client = _client(session_factory, users["alice"])+ await _upload(client, name="deploy-room")++ clash = await client.post(+ "/templates",+ json={+ "name": "deploy-room",+ "description": "d",+ "kind": "room",+ "content": "room:\n name: r\n",+ },+ )+ assert clash.status_code == 409++ async def test_two_owners_may_each_have_the_same_name(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ await _upload(_client(session_factory, users["alice"]), name="deploy-room")+ await _upload(_client(session_factory, users["bob"]), name="deploy-room")++ listing = await _client(session_factory, users["alice"]).get("/templates")+ assert len(listing.json()) == 2++ async def test_replacing_the_document_bumps_the_revision(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ client = _client(session_factory, users["alice"])+ created = await _upload(client, name="t")+ assert created["version"] == 1++ updated = await client.patch(+ f"/templates/{created['id']}", json={"content": _AWKWARD_DOCUMENT}+ )+ assert updated.status_code == 200+ assert updated.json()["version"] == 2+ assert updated.json()["content"] == _AWKWARD_DOCUMENT++ async def test_a_shape_this_server_cannot_provision_is_still_accepted(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ """Storage is opaque to the format — just not to YAML itself.++ The document parses; nothing here knows what an `orbit:` is, and that+ is the whole point of a kind-agnostic registry.+ """+ future = "orbit:\n around: whatever comes next\n params: []\n"+ client = _client(session_factory, users["alice"])+ created = await _upload(+ client, name="future", kind="constellation", content=future+ )++ raw = await client.get(f"/templates/{created['id']}/content")+ assert raw.content.decode("utf-8") == future++ async def test_an_unknown_template_is_a_404_on_both_read_routes(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ client = _client(session_factory, users["alice"])+ assert (await client.get("/templates/nope")).status_code == 404+ assert (await client.get("/templates/nope/content")).status_code == 404++ @pytest.mark.parametrize(+ "body",+ [+ {"name": "", "description": "d", "kind": "room", "content": "x"},+ {"name": "t", "description": "d", "kind": "", "content": "x"},+ {"name": "t", "description": "d", "kind": "room", "content": ""},+ {"description": "d", "kind": "room", "content": "x"},+ ],+ ids=["blank-name", "blank-kind", "empty-document", "no-name"],+ )+ async def test_an_incomplete_upload_is_rejected(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ users: dict[str, User],+ body: dict[str, str],+ ) -> None:+ client = _client(session_factory, users["alice"])+ response = await client.post("/templates", json=body)+ assert response.status_code == 422++ @pytest.mark.parametrize(+ "field,size",+ [("name", 201), ("description", 2001), ("kind", 65)],+ ids=["name", "description", "kind"],+ )+ async def test_an_oversize_label_is_rejected(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ users: dict[str, User],+ field: str,+ size: int,+ ) -> None:+ """The document has a byte budget; the labels around it need one too.++ The columns are unbounded `Text` and nothing else in the request path+ caps a field, so without these a name is as large as the body someone+ is willing to send.+ """+ client = _client(session_factory, users["alice"])+ body = {+ "name": "t",+ "description": "d",+ "kind": "room",+ "content": "room:\n name: r\n",+ }+ body[field] = "x" * size+ assert (await client.post("/templates", json=body)).status_code == 422++ created = await _upload(client, name="fine")+ patched = await client.patch(+ f"/templates/{created['id']}", json={field: "x" * size}+ )+ assert patched.status_code == 422++ async def test_an_upload_naming_the_owner_is_refused_outright(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ """A 201 to a request that quietly did something else is worse than a 422."""+ client = _client(session_factory, users["alice"])+ response = await client.post(+ "/templates",+ json={+ "name": "smuggled",+ "description": "d",+ "kind": "room",+ "content": "room:\n name: r\n",+ "owner_id": users["bob"].id,+ },+ )+ assert response.status_code == 422++ listing = await client.get("/templates", params={"q": "smuggled"})+ assert listing.json() == []++ async def test_a_body_naming_the_owner_is_refused_outright(+ self, session_factory: async_sessionmaker[AsyncSession], users: dict[str, User]+ ) -> None:+ """Not silently ignored — a caller trying to reassign should hear so."""+ client = _client(session_factory, users["alice"])+ created = await _upload(client, name="t")++ response = await client.patch(+ f"/templates/{created['id']}",+ json={"owner_id": users["bob"].id, "description": "x"},+ )+ assert response.status_code == 422++ unchanged = await client.get(f"/templates/{created['id']}")+ assert unchanged.json()["owner_id"] == users["alice"].iddiff --git a/core/tests/switch_core/gateway/test_template_routes.py b/core/tests/switch_core/gateway/test_template_routes.pynew file mode 100644index 000000000..490c37de6--- /dev/null+++ b/core/tests/switch_core/gateway/test_template_routes.py@@ -0,0 +1,489 @@+"""The template registry's HTTP surface, against real Postgres and real stores.++These cover the acceptance conditions for the registry: a document survives the+round trip unchanged, the catalogue shows every owner's templates, and deleting+someone else's is refused.+"""++from __future__ import annotations++import pytest+from fastapi import HTTPException+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.config import SwitchConfig+from switch_core.db.stores.template_store import TemplateStore+from switch_core.db.stores.user_store import UserStore+from switch_core.gateway.schemas import (+ TemplateCreateRequest,+ TemplateUpdateRequest,+)+from switch_core.gateway.templates import (+ create_template,+ delete_template,+ get_template,+ get_template_content,+ list_templates,+ patch_template,+)+from tests.switch_core.gateway.agent_route_harness import add_user++_TEMPLATE_STORE = TemplateStore()+_USER_STORE = UserStore()++# Awkward on purpose: CRLF, a tab, trailing spaces, unicode, no final newline.+_AWKWARD_DOCUMENT = (+ "params:\r\n"+ " owner:\r\n"+ " type: string\r\n"+ "room:\r\n"+ ' name: "{owner} — café ☕" \r\n'+ " description: |\n"+ " tabbed:\there\n"+ " agents: []"+)+++def _config(**overrides: object) -> SwitchConfig:+ base: dict[str, object] = {+ "db_host": "localhost",+ "db_port": "5432",+ "db_user": "u",+ "db_password": "p",+ "db_name": "d",+ "matrix_server_name": "test",+ "agent_registration_token": "t",+ "jwt_secret_key": "s",+ "gateway_admin_email": "admin@test",+ "gateway_admin_password": "pw",+ }+ base.update(overrides)+ return SwitchConfig(**base) # type: ignore[arg-type]+++async def _create(+ session: AsyncSession,+ user: object,+ *,+ name: str,+ description: str = "d",+ kind: str = "room",+ content: str = "room:\n name: r\n",+ config: SwitchConfig | None = None,+) -> object:+ return await create_template(+ TemplateCreateRequest(+ name=name, description=description, kind=kind, content=content+ ),+ session,+ _TEMPLATE_STORE,+ _USER_STORE,+ config or _config(),+ user, # type: ignore[arg-type]+ )+++class TestUploadAndFetch:+ async def test_a_document_round_trips_byte_identical(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ owner = await add_user(session, name="alice")+ await session.commit()++ created = await _create(+ session, owner, name="awkward", content=_AWKWARD_DOCUMENT+ )++ fetched = await get_template(+ created.id, # type: ignore[attr-defined]+ session,+ _TEMPLATE_STORE,+ _USER_STORE,+ owner,+ )+ assert fetched.content == _AWKWARD_DOCUMENT++ raw = await get_template_content(+ created.id, # type: ignore[attr-defined]+ session,+ _TEMPLATE_STORE,+ owner,+ )+ assert raw.body.decode("utf-8") == _AWKWARD_DOCUMENT+ assert raw.media_type == "application/x-yaml"++ async def test_upload_reports_the_owner_and_starts_at_version_one(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ owner = await add_user(session, name="alice")+ await session.commit()++ created = await _create(session, owner, name="t")+ assert created.owner_name == "alice" # type: ignore[attr-defined]+ assert created.version == 1 # type: ignore[attr-defined]++ async def test_size_is_measured_in_bytes_not_characters(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ owner = await add_user(session, name="alice")+ await session.commit()++ created = await _create(session, owner, name="t", content="room: ☕\n")+ assert created.size_bytes == 10 # type: ignore[attr-defined]++ async def test_reusing_your_own_name_is_a_conflict(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ owner = await add_user(session, name="alice")+ await session.commit()+ await _create(session, owner, name="deploy-room")++ with pytest.raises(HTTPException) as exc:+ await _create(session, owner, name="deploy-room")+ assert exc.value.status_code == 409++ async def test_fetching_a_missing_template_is_a_404(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ owner = await add_user(session, name="alice")+ await session.commit()++ with pytest.raises(HTTPException) as exc:+ await get_template("nope", session, _TEMPLATE_STORE, _USER_STORE, owner)+ assert exc.value.status_code == 404+++class TestSizeLimit:+ async def test_an_oversize_upload_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ owner = await add_user(session, name="alice")+ await session.commit()++ with pytest.raises(HTTPException) as exc:+ await _create(+ session,+ owner,+ name="huge",+ content="room: " + "x" * 101,+ config=_config(template_max_bytes=100),+ )+ assert exc.value.status_code == 413+ assert "over the 100-byte limit" in exc.value.detail++ async def test_nothing_is_stored_when_an_upload_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ owner = await add_user(session, name="alice")+ await session.commit()++ with pytest.raises(HTTPException):+ await _create(+ session,+ owner,+ name="huge",+ content="room: " + "x" * 101,+ config=_config(template_max_bytes=100),+ )+ assert await _TEMPLATE_STORE.list_all(session) == []++ async def test_the_limit_counts_bytes_so_multibyte_text_cannot_slip_past(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """Ten ☕ is ten characters but thirty bytes."""+ async with session_factory() as session:+ owner = await add_user(session, name="alice")+ await session.commit()++ with pytest.raises(HTTPException) as exc:+ await _create(+ session,+ owner,+ name="coffee",+ content="room: " + "☕" * 10,+ config=_config(template_max_bytes=20),+ )+ assert exc.value.status_code == 413+++class TestCatalogue:+ async def test_every_owners_templates_are_listed(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ alice = await add_user(session, name="alice")+ bob = await add_user(session, name="bob")+ await session.commit()+ await _create(session, alice, name="alice-room")+ await _create(session, bob, name="bob-room")++ # Listed identically whoever is asking.+ for caller in (alice, bob):+ listed = await list_templates(+ session, _TEMPLATE_STORE, _USER_STORE, caller+ )+ assert {t.name for t in listed} == {"alice-room", "bob-room"}+ assert {t.owner_name for t in listed} == {"alice", "bob"}++ async def test_listing_omits_the_document_bodies(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ owner = await add_user(session, name="alice")+ await session.commit()+ await _create(session, owner, name="t", content=_AWKWARD_DOCUMENT)++ listed = await list_templates(session, _TEMPLATE_STORE, _USER_STORE, owner)+ assert not hasattr(listed[0], "content")+ assert listed[0].size_bytes == len(_AWKWARD_DOCUMENT.encode("utf-8"))++ async def test_search_matches_name_and_description(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ owner = await add_user(session, name="alice")+ await session.commit()+ await _create(session, owner, name="deploy-room", description="x")+ await _create(session, owner, name="other", description="for DEPLOYing")+ await _create(session, owner, name="unrelated", description="x")++ hits = await list_templates(+ session, _TEMPLATE_STORE, _USER_STORE, owner, q="deploy"+ )+ assert {t.name for t in hits} == {"deploy-room", "other"}++ async def test_filters_by_kind(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ owner = await add_user(session, name="alice")+ await session.commit()+ await _create(session, owner, name="a", kind="room")+ await _create(session, owner, name="b", kind="group")++ hits = await list_templates(+ session, _TEMPLATE_STORE, _USER_STORE, owner, kind="group"+ )+ assert {t.name for t in hits} == {"b"}+++class TestOwnership:+ async def test_deleting_someone_elses_template_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ alice = await add_user(session, name="alice")+ bob = await add_user(session, name="bob")+ await session.commit()+ created = await _create(session, alice, name="alice-room")++ with pytest.raises(HTTPException) as exc:+ await delete_template(+ created.id, # type: ignore[attr-defined]+ session,+ _TEMPLATE_STORE,+ bob,+ )+ assert exc.value.status_code == 403+ assert await _TEMPLATE_STORE.get(session, created.id) is not None # type: ignore[attr-defined]++ async def test_editing_someone_elses_template_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ alice = await add_user(session, name="alice")+ bob = await add_user(session, name="bob")+ await session.commit()+ created = await _create(session, alice, name="alice-room")++ with pytest.raises(HTTPException) as exc:+ await patch_template(+ created.id, # type: ignore[attr-defined]+ TemplateUpdateRequest(content="room:\n name: hijacked\n"),+ session,+ _TEMPLATE_STORE,+ _USER_STORE,+ _config(),+ bob,+ )+ assert exc.value.status_code == 403++ async def test_anyone_may_read_anyone_elses_template(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """Ownership governs change, not visibility."""+ async with session_factory() as session:+ alice = await add_user(session, name="alice")+ bob = await add_user(session, name="bob")+ await session.commit()+ created = await _create(+ session, alice, name="alice-room", content=_AWKWARD_DOCUMENT+ )++ fetched = await get_template(+ created.id, # type: ignore[attr-defined]+ session,+ _TEMPLATE_STORE,+ _USER_STORE,+ bob,+ )+ assert fetched.content == _AWKWARD_DOCUMENT++ async def test_an_owner_may_delete_their_own(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ alice = await add_user(session, name="alice")+ await session.commit()+ created = await _create(session, alice, name="alice-room")++ result = await delete_template(+ created.id, # type: ignore[attr-defined]+ session,+ _TEMPLATE_STORE,+ alice,+ )+ assert result.deleted_id == created.id # type: ignore[attr-defined]+ assert await _TEMPLATE_STORE.get(session, created.id) is None # type: ignore[attr-defined]++ async def test_an_admin_may_delete_anyones(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ alice = await add_user(session, name="alice")+ admin = await add_user(session, name="root", role="admin")+ await session.commit()+ created = await _create(session, alice, name="alice-room")++ await delete_template(+ created.id, # type: ignore[attr-defined]+ session,+ _TEMPLATE_STORE,+ admin,+ )+ assert await _TEMPLATE_STORE.get(session, created.id) is None # type: ignore[attr-defined]++ async def test_an_admin_may_edit_anyones(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ alice = await add_user(session, name="alice")+ admin = await add_user(session, name="root", role="admin")+ await session.commit()+ created = await _create(session, alice, name="alice-room")++ updated = await patch_template(+ created.id, # type: ignore[attr-defined]+ TemplateUpdateRequest(description="tidied up by an admin"),+ session,+ _TEMPLATE_STORE,+ _USER_STORE,+ _config(),+ admin,+ )+ assert updated.description == "tidied up by an admin"+ # Still Alice's — an admin edit is not a transfer of ownership.+ assert updated.owner_id == alice.id++ async def test_deleting_a_missing_template_is_a_404(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ alice = await add_user(session, name="alice")+ await session.commit()++ with pytest.raises(HTTPException) as exc:+ await delete_template("nope", session, _TEMPLATE_STORE, alice)+ assert exc.value.status_code == 404+++class TestUpdate:+ async def test_replacing_content_bumps_the_version(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ alice = await add_user(session, name="alice")+ await session.commit()+ created = await _create(session, alice, name="t")++ updated = await patch_template(+ created.id, # type: ignore[attr-defined]+ TemplateUpdateRequest(content="room:\n name: changed\n"),+ session,+ _TEMPLATE_STORE,+ _USER_STORE,+ _config(),+ alice,+ )+ assert updated.version == 2+ assert updated.content == "room:\n name: changed\n"++ async def test_a_metadata_edit_leaves_the_version_alone(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ alice = await add_user(session, name="alice")+ await session.commit()+ created = await _create(session, alice, name="t")++ updated = await patch_template(+ created.id, # type: ignore[attr-defined]+ TemplateUpdateRequest(description="clearer"),+ session,+ _TEMPLATE_STORE,+ _USER_STORE,+ _config(),+ alice,+ )+ assert updated.version == 1+ assert updated.description == "clearer"++ async def test_an_oversize_replacement_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ alice = await add_user(session, name="alice")+ await session.commit()+ created = await _create(session, alice, name="t", content="room: small\n")++ with pytest.raises(HTTPException) as exc:+ await patch_template(+ created.id, # type: ignore[attr-defined]+ TemplateUpdateRequest(content="room: " + "x" * 101),+ session,+ _TEMPLATE_STORE,+ _USER_STORE,+ _config(template_max_bytes=100),+ alice,+ )+ assert exc.value.status_code == 413+ stored = await _TEMPLATE_STORE.get(session, created.id) # type: ignore[attr-defined]+ assert stored is not None and stored.content == "room: small\n"++ async def test_renaming_onto_a_name_you_already_use_is_a_conflict(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ alice = await add_user(session, name="alice")+ await session.commit()+ await _create(session, alice, name="taken")+ other = await _create(session, alice, name="free")++ with pytest.raises(HTTPException) as exc:+ await patch_template(+ other.id, # type: ignore[attr-defined]+ TemplateUpdateRequest(name="taken"),+ session,+ _TEMPLATE_STORE,+ _USER_STORE,+ _config(),+ alice,+ )+ assert exc.value.status_code == 409diff --git a/core/tests/switch_core/test_template_lint.py b/core/tests/switch_core/test_template_lint.pynew file mode 100644index 000000000..8203cdaa4--- /dev/null+++ b/core/tests/switch_core/test_template_lint.py@@ -0,0 +1,422 @@+"""Advisory checks on a template document.++The property that matters most here is what the linter *declines* to have an+opinion about. It runs against documents the registry is required to store in+shapes this server may not know, so a check that quietly encoded today's room+format would start refusing group templates the day they land.+"""++from __future__ import annotations++import pytest++from switch_core.template_lint import lint_template+++def _codes(findings: list) -> set[str]:+ return {f.code for f in findings}+++# The canonical example for the room-template surface, kept here rather than+# read from `examples/` because that file arrives with CHOO-2656 and this+# branch must not add a second copy of it. It exercises three things at once:+# a `kickoff:` block beside `room:`, `{$creator}` builtins, and a `multiline`+# param field — none of which the format module on this branch knows yet.+_CANONICAL_EXAMPLE = """\+params:+ task_name:+ type: string+ description: Short name for the task (used in the room name)+ coder_agent:+ type: string+ description: Agent that implements the task+ reviewer_agent:+ type: string+ description: Agent that reviews and drives the acceptance loop+ brief:+ type: string+ multiline: true+ description: The task brief (paste the full text)+room:+ name: "Switch work: {task_name}"+ description: "Workroom for {task_name} — coder/reviewer loop, human-gated."+ channel_type: channel_private+ agents: ["{coder_agent}", "{reviewer_agent}"]+ users: ["{$creator}"]+ instructions: |+ This room implements {task_name}. {coder_agent} owns the branch and+ commits. {reviewer_agent} reviews against the Acceptance section of the+ brief and pushes the coder in a loop until every item is met. Only+ {$creator}'s explicit confirmation stops the loop.++ Brief:+ {brief}+kickoff: |+ @{coder_agent} @{reviewer_agent} — kicking off {task_name}.++ @{coder_agent}: read the brief in the room instructions and start+ implementing. Post your plan here before your first commit.++ @{reviewer_agent}: drive the acceptance loop. Review every hand-off+ against the brief's Acceptance section and push back until every item is+ met, then ping {$creator} to confirm and close.+"""+++class TestTheCanonicalExample:+ """The document the room-template surface is documented by.++ If the checker calls this wrong, the checker is wrong. It is the sharpest+ test of shape-agnosticism available, because it was written against a+ newer format module than this branch carries.+ """++ def test_it_raises_no_errors(self) -> None:+ result = lint_template(_CANONICAL_EXAMPLE)+ assert result.ok, [f.message for f in result.errors]++ def test_kickoff_is_not_called_an_unknown_key(self) -> None:+ result = lint_template(_CANONICAL_EXAMPLE)+ assert "unknown_top_level_key" not in _codes(result.warnings)++ def test_the_creator_builtin_is_not_called_an_undeclared_placeholder(self) -> None:+ """`{$creator}` is the server's to fill; a template must not declare it."""+ result = lint_template(_CANONICAL_EXAMPLE)+ assert "undeclared_placeholder" not in _codes(result.warnings)+ assert "unknown_builtin" not in _codes(result.warnings)++ def test_every_parameter_is_seen_as_used(self) -> None:+ """Two of them are only referenced from inside the kickoff block."""+ result = lint_template(_CANONICAL_EXAMPLE)+ assert "unused_param" not in _codes(result.warnings)++ def test_a_newer_param_field_is_a_warning_not_an_error(self) -> None:+ """`multiline` lands with CHOO-2656; this branch predates it.++ Reported so a typo is still visible, but not as an error — a document+ written for a newer Switch is the ordinary case for a registry, not a+ broken document.+ """+ result = lint_template(_CANONICAL_EXAMPLE)+ (warning,) = [w for w in result.warnings if w.code == "unknown_param_field"]+ assert warning.subject == "brief"+ assert "multiline" in warning.message+++class TestWhatBarsTheDoor:+ """Which findings refuse an upload, and — more importantly — which do not.++ The blocking set is deliberately tiny and deliberately shape-independent.+ Every entry added to it is a document some future format cannot store, so+ the list itself is the thing to be sceptical of.+ """++ @pytest.mark.parametrize(+ "text",+ ["", "a: [unclosed\n", "- one\n- two\n", "just a bare string"],+ ids=["empty", "not-yaml", "a-list", "a-scalar"],+ )+ def test_a_document_no_consumer_could_read_is_blocked(self, text: str) -> None:+ assert lint_template(text).blocked++ @pytest.mark.parametrize(+ "text",+ [+ "params:\n v:\n type: enum\nroom:\n name: '{v}'\n",+ "params:\n owner:\nroom:\n name: '{owner}'\n",+ "params:\n owner:\n type: nonsense\nroom:\n name: '{owner}'\n",+ "params:\n - a\n - b\nroom:\n name: r\n",+ ],+ ids=[+ "enum-without-choices",+ "bare-param",+ "unknown-type",+ "params-not-a-mapping",+ ],+ )+ def test_a_document_only_the_format_objects_to_is_not_blocked(+ self, text: str+ ) -> None:+ """These are errors, and still not this checker's call to make.++ The format moves and this checker has called a valid document invalid+ before — and Console's own parser accepts a bare param that this+ server refuses, so the two already disagree about one of these.+ """+ result = lint_template(text)+ assert result.errors, "expected the checker to object"+ assert not result.blocked++ def test_the_blocking_finding_says_it_blocks(self) -> None:+ """So a caller can show which one is the refusal."""+ (error,) = lint_template("a: [unclosed\n").errors+ assert error.blocking is True++ def test_a_document_it_merely_dislikes_says_it_does_not(self) -> None:+ (error,) = lint_template(+ "params:\n v:\n type: enum\nroom:\n name: '{v}'\n"+ ).errors+ assert error.blocking is False+++class TestBuiltins:+ def test_a_misspelled_builtin_is_caught(self) -> None:+ result = lint_template('room:\n users: ["{$creatr}"]\n')+ (warning,) = [w for w in result.warnings if w.code == "unknown_builtin"]+ assert warning.subject == "$creatr"+ assert "$creator" in warning.message++ @pytest.mark.parametrize(+ "builtin", ["$creator", "$creator_email", "$date", "$timestamp"]+ )+ def test_each_known_builtin_passes(self, builtin: str) -> None:+ result = lint_template(f'room:\n name: "{{{builtin}}}"\n')+ assert result.ok and result.warnings == []++ def test_a_builtin_is_never_reported_as_a_missing_parameter(self) -> None:+ result = lint_template('room:\n users: ["{$creator}"]\n')+ assert result.warnings == []+++class TestUnknownParamFields:+ def test_the_rest_of_the_spec_is_still_checked(self) -> None:+ """An unknown field must not buy a free pass on a real mistake."""+ result = lint_template(+ "params:\n"+ " visibility:\n"+ " type: enum\n"+ " multiline: true\n"+ "room:\n"+ " channel_type: '{visibility}'\n"+ )+ assert _codes(result.errors) == {"enum_without_choices"}+ assert _codes(result.warnings) == {"unknown_param_field"}++ def test_a_malformed_field_is_still_an_error_alongside_an_unknown_one(self) -> None:+ result = lint_template(+ "params:\n"+ " owner:\n"+ " type: nonsense\n"+ " multiline: true\n"+ "room:\n"+ " name: '{owner}'\n"+ )+ assert "invalid_param_spec" in _codes(result.errors)+ assert "unknown_param_field" in _codes(result.warnings)+++class TestShapeAgnosticism:+ def test_a_room_template_is_clean(self) -> None:+ result = lint_template(+ "params:\n"+ " owner:\n"+ " type: string\n"+ "room:\n"+ ' name: "{owner} deploy"\n'+ " description: d\n"+ )+ assert result.ok+ assert result.warnings == []++ def test_a_group_template_is_clean_too(self) -> None:+ """No `room:` key at all — the shape CHOO-2657 introduces.++ The linter must not have learned that a template is a room, or it+ starts rejecting valid documents the moment a second shape exists.+ """+ result = lint_template(+ "params:\n"+ " owner:\n"+ " type: string\n"+ "group:\n"+ ' name: "{owner} workstream"\n'+ "rooms:\n"+ " - name: planning\n"+ " - name: delivery\n"+ )+ assert result.ok+ assert result.warnings == []++ def test_a_shape_nobody_has_invented_yet_is_a_warning_not_an_error(self) -> None:+ result = lint_template("agent:\n name: helper\n model: sonnet\n")+ assert result.ok, "an unknown shape must still be storable"+ assert _codes(result.warnings) == {"unknown_top_level_key"}++ def test_a_document_with_no_recognised_key_is_still_only_warned_about(self) -> None:+ result = lint_template("whatever:\n - 1\n - 2\n")+ assert result.ok+++class TestUnparseableInput:+ @pytest.mark.parametrize(+ "text,code",+ [+ ("", "empty"),+ (" \n \n", "empty"),+ ("# just a comment\n", "empty"),+ ("- one\n- two\n", "not_a_mapping"),+ ("just a bare string", "not_a_mapping"),+ ("42", "not_a_mapping"),+ ("room:\n name: x\n bad-indent: y\n", "invalid_yaml"),+ ("a: [unclosed\n", "invalid_yaml"),+ ],+ ids=[+ "empty",+ "whitespace",+ "comment-only",+ "list",+ "scalar",+ "number",+ "bad-indent",+ "unclosed",+ ],+ )+ def test_it_is_reported_as_an_error(self, text: str, code: str) -> None:+ result = lint_template(text)+ assert not result.ok+ assert code in _codes(result.errors)++ def test_a_syntax_error_says_where(self) -> None:+ """A line number is most of the value when you are staring at an editor."""+ result = lint_template("room:\n name: x\n bad: y\n")+ (error,) = result.errors+ assert "line" in error.message and "column" in error.message+++class TestParamsBlock:+ def test_a_params_block_that_is_not_a_mapping_is_an_error(self) -> None:+ result = lint_template("params:\n - owner\nroom:\n name: x\n")+ assert _codes(result.errors) == {"params_not_a_mapping"}++ def test_a_bare_param_with_no_spec_is_an_error(self) -> None:+ """Provisioning refuses it, so the form should say so first."""+ result = lint_template("params:\n owner:\nroom:\n name: '{owner}'\n")+ assert _codes(result.errors) == {"param_has_no_spec"}++ @pytest.mark.parametrize(+ "spec",+ [+ "type: colour",+ "type: [not, a, type]",+ "enum: not-a-list",+ ],+ ids=["unknown-type", "type-is-a-list", "enum-is-not-a-list"],+ )+ def test_a_spec_provisioning_would_reject_is_an_error(self, spec: str) -> None:+ result = lint_template(+ f"params:\n owner:\n {spec}\nroom:\n name: '{{owner}}'\n"+ )+ assert not result.ok+ assert "invalid_param_spec" in _codes(result.errors)++ def test_an_enum_with_no_choices_is_an_error(self) -> None:+ """Well-formed as a spec, and still unusable.++ `ParamSpec` allows an enum with no `enum:` list, so this only fails+ when somebody tries to resolve the parameter — long after, and far+ from, the mistake.+ """+ result = lint_template(+ "params:\n visibility:\n type: enum\n"+ "room:\n channel_type: '{visibility}'\n"+ )+ assert _codes(result.errors) == {"enum_without_choices"}++ def test_a_default_outside_the_choices_is_an_error(self) -> None:+ result = lint_template(+ "params:\n"+ " visibility:\n"+ " type: enum\n"+ " enum: [channel_public, channel_private]\n"+ " default: secret\n"+ "room:\n"+ " channel_type: '{visibility}'\n"+ )+ (error,) = result.errors+ assert error.code == "default_not_in_enum"+ assert "secret" in error.message and "channel_public" in error.message++ def test_the_error_names_the_parameter(self) -> None:+ result = lint_template(+ "params:\n first:\n type: string\n"+ " second:\n type: nonsense\n"+ "room:\n name: '{first}{second}'\n"+ )+ (error,) = result.errors+ assert error.subject == "second"++ def test_a_valid_enum_param_is_clean(self) -> None:+ result = lint_template(+ "params:\n"+ " visibility:\n"+ " type: enum\n"+ " enum: [channel_public, channel_private]\n"+ " default: channel_private\n"+ "room:\n"+ " channel_type: '{visibility}'\n"+ )+ assert result.ok and result.warnings == []+++class TestPlaceholders:+ def test_a_placeholder_nothing_declares_is_warned_about(self) -> None:+ """The typo that otherwise ships silently.++ An undeclared placeholder is not an error anywhere — interpolation+ leaves it in the document verbatim — so the room ends up named+ literally "{ownr} deploy" and nothing ever said so.+ """+ result = lint_template(+ "params:\n owner:\n type: string\nroom:\n name: '{ownr} deploy'\n"+ )+ assert result.ok+ codes = _codes(result.warnings)+ assert "undeclared_placeholder" in codes+ assert "unused_param" in codes+ assert {w.subject for w in result.warnings} == {"ownr", "owner"}++ def test_a_declared_param_nobody_uses_is_warned_about(self) -> None:+ result = lint_template(+ "params:\n unused:\n type: string\nroom:\n name: fixed\n"+ )+ assert _codes(result.warnings) == {"unused_param"}++ def test_placeholders_are_found_at_any_depth(self) -> None:+ result = lint_template(+ "params:\n"+ " owner:\n type: string\n"+ " repo:\n type: string\n"+ " agent:\n type: string\n"+ "room:\n"+ " name: fixed\n"+ " agents: ['{agent}']\n"+ " docs:\n"+ " - name: readme\n"+ " content: |\n"+ " {owner} owns {repo}\n"+ )+ assert result.warnings == [], "every declared param is used somewhere"++ def test_a_placeholder_in_the_params_block_does_not_count_as_use(self) -> None:+ """`params:` declares placeholders; it does not consume them."""+ result = lint_template(+ "params:\n"+ " owner:\n"+ " type: string\n"+ " description: 'the {owner} of the room'\n"+ "room:\n"+ " name: fixed\n"+ )+ assert _codes(result.warnings) == {"unused_param"}++ def test_a_brace_that_is_not_a_placeholder_is_ignored(self) -> None:+ result = lint_template("room:\n name: 'a {} b {1} c'\n")+ assert result.ok and result.warnings == []+++class TestItNeverBlocksAnUpload:+ def test_even_the_worst_document_only_reports(self) -> None:+ """The registry stores what it is given; this only describes it."""+ result = lint_template("a: [unclosed\n")+ assert not result.ok+ assert isinstance(result.errors, list)diff --git a/gateway/src/App.tsx b/gateway/src/App.tsxindex 9b3800b5f..bbb09b715 100644--- a/gateway/src/App.tsx+++ b/gateway/src/App.tsx@@ -12,6 +12,7 @@ import DocumentDetailPage from "./pages/resources/DocumentDetailPage";import PackageDetailPage from "./pages/resources/PackageDetailPage";import ReferenceDetailPage from "./pages/resources/ReferenceDetailPage";import ResourcesPage from "./pages/resources/ResourcesPage";+import TemplateDetailPage from "./pages/resources/TemplateDetailPage";import CreateRoomPage from "./pages/rooms/CreateRoomPage";import GroupsPage from "./pages/rooms/GroupsPage";import RoomDetailPage from "./pages/rooms/RoomDetailPage";@@ -74,6 +75,10 @@ function AppRoutes() {path="resources/packages/:id"element={<PackageDetailPage />}/>+ <Route+ path="resources/templates/:id"+ element={<TemplateDetailPage />}+ /><Route path="agents" element={<AgentsPage />} /><Route path="agents/:agentId" element={<AgentDetailPage />} /><Route path="collaborations" element={<CollaborationsPage />} />diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.tsindex 324a5aab5..30489c490 100644--- a/gateway/src/data/api.ts+++ b/gateway/src/data/api.ts@@ -1495,3 +1495,107 @@ export async function detachPackageFromRoom(throw new Error(body?.detail ?? `${res.status} ${res.statusText}`);}}++// ── Templates ────────────────────────────────────────────────────────────────++export interface TemplateSummary {+ id: string;+ owner_id: string;+ owner_name: string | null;+ name: string;+ description: string;+ kind: string;+ version: number;+ size_bytes: number;+ created_at: string;+ updated_at: string;+}++export interface TemplateDetail extends TemplateSummary {+ content: string;+}++export interface TemplateCreateInput {+ name: string;+ description: string;+ kind: string;+ content: string;+}++export interface TemplateUpdateInput {+ name?: string;+ description?: string;+ kind?: string;+ content?: string;+}++export interface TemplateDeleteResult {+ deleted_id: string;+}++export async function fetchTemplates(): Promise<TemplateSummary[] | null> {+ return fetchJson<TemplateSummary[]>("/templates");+}++export async function fetchTemplate(id: string): Promise<TemplateDetail | null> {+ return fetchJson<TemplateDetail>(`/templates/${id}`);+}++export async function createTemplate(+ input: TemplateCreateInput,+): Promise<TemplateDetail> {+ return jsonRequest<TemplateDetail>("/templates", "POST", input);+}++export async function updateTemplate(+ id: string,+ input: TemplateUpdateInput,+): Promise<TemplateDetail> {+ return jsonRequest<TemplateDetail>(`/templates/${id}`, "PATCH", input);+}++export async function deleteTemplate(id: string): Promise<TemplateDeleteResult> {+ return jsonRequest<TemplateDeleteResult>(`/templates/${id}`, "DELETE");+}++/** The stored document itself, exactly as uploaded — for download and copy. */+export async function fetchTemplateContent(id: string): Promise<string> {+ const res = await fetch(`${BASE}/templates/${id}/content`, {+ credentials: "include",+ });+ if (!res.ok) {+ const body = await res.json().catch(() => null);+ throw new Error(body?.detail ?? `${res.status} ${res.statusText}`);+ }+ return res.text();+}++export interface TemplateFinding {+ code: string;+ message: string;+ subject: string | null;+ blocking: boolean;+}++export interface TemplateValidation {+ ok: boolean;+ /** The server refuses an upload of this document. */+ blocked: boolean;+ errors: TemplateFinding[];+ warnings: TemplateFinding[];+}++/**+ * Check a document without storing it.+ *+ * Mostly advisory — but `blocked` is not. The server refuses an upload that+ * is not YAML at all, so a form that ignored it would offer a button that+ * always fails.+ */+export async function validateTemplate(+ content: string,+): Promise<TemplateValidation> {+ return jsonRequest<TemplateValidation>("/templates/validate", "POST", {+ content,+ });+}diff --git a/gateway/src/data/hooks.ts b/gateway/src/data/hooks.tsindex e5db72b35..c89af9d67 100644--- a/gateway/src/data/hooks.ts+++ b/gateway/src/data/hooks.ts@@ -22,6 +22,7 @@ import {type RoomDetail,type RoomGroupDetail,type RoomSummary,+ type TemplateSummary,type UserInfo,fetchAgent,fetchAgents,@@ -54,6 +55,7 @@ import {fetchRoomPackages,fetchRoomReferences,fetchRooms,+ fetchTemplates,fetchUsers,} from "./api";@@ -320,3 +322,7 @@ export function usePackageDocuments();return useQuery(fetcher);}++export function useTemplates(): UseQueryResult<TemplateSummary[]> {+ return useQuery(fetchTemplates);+}diff --git a/gateway/src/pages/resources/CreateTemplateDialog.tsx b/gateway/src/pages/resources/CreateTemplateDialog.tsxnew file mode 100644index 000000000..0929edb27--- /dev/null+++ b/gateway/src/pages/resources/CreateTemplateDialog.tsx@@ -0,0 +1,183 @@+import UploadFileIcon from "@mui/icons-material/UploadFile";+import {+ Alert,+ Button,+ CircularProgress,+ Dialog,+ DialogActions,+ DialogContent,+ DialogTitle,+ Stack,+ TextField,+} from "@mui/material";+import { useRef, useState } from "react";+import { createTemplate } from "../../data/api";+import TemplateFindings from "./TemplateFindings";+import { MAX_DOCUMENT_BYTES, formatBytes } from "./templateFormat";+import { useTemplateValidation } from "./useTemplateValidation";++interface Props {+ open: boolean;+ onClose: () => void;+ onCreated: (id: string) => void;+}++export default function CreateTemplateDialog({+ open,+ onClose,+ onCreated,+}: Props) {+ const [name, setName] = useState("");+ const [description, setDescription] = useState("");+ const [kind, setKind] = useState("room");+ const [content, setContent] = useState("");+ const [submitting, setSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const fileInput = useRef<HTMLInputElement>(null);+ const { result: validation, checking } = useTemplateValidation(content, {+ enabled: open,+ });++ const reset = () => {+ setName("");+ setDescription("");+ setKind("room");+ setContent("");+ setError(null);+ };++ const handleClose = () => {+ if (submitting) return;+ reset();+ onClose();+ };++ const handleFile = async (file: File) => {+ setError(null);+ if (file.size > MAX_DOCUMENT_BYTES) {+ // Caught here so a large file is refused before it is read into memory,+ // rather than after a round trip that ends in a 413.+ setError(+ `That file is ${formatBytes(file.size)}, over the ` ++ `${formatBytes(MAX_DOCUMENT_BYTES)} limit for a template.`,+ );+ return;+ }+ // Read as text and hand the string on unchanged — the registry stores what+ // it is given, so anything reformatted here would be stored reformatted.+ const text = await file.text();+ setContent(text);+ // Against the latest name, not the one captured when this handler was+ // made: reading the file is async, and the user may have typed meanwhile.+ setName((current) =>+ current.trim() ? current : file.name.replace(/\.(ya?ml)$/i, ""),+ );+ };++ const handleSubmit = async () => {+ setSubmitting(true);+ setError(null);+ try {+ const created = await createTemplate({+ name: name.trim(),+ description,+ kind: kind.trim(),+ content,+ });+ reset();+ onCreated(created.id);+ } catch (e) {+ setError(e instanceof Error ? e.message : "Failed to upload template");+ } finally {+ setSubmitting(false);+ }+ };++ const canSubmit =+ name.trim().length > 0 &&+ kind.trim().length > 0 &&+ content.length > 0 &&+ !submitting &&+ // Only a document the server would refuse outright. Every other finding+ // is advice, and a form that gated on advice would be the checker+ // deciding what may be stored.+ !validation?.blocked;++ return (+ <Dialog open={open} onClose={handleClose} fullWidth maxWidth="md">+ <DialogTitle>Upload template</DialogTitle>+ <DialogContent>+ <Stack spacing={2} sx={{ mt: 1 }}>+ <TextField+ label="Name"+ value={name}+ onChange={(e) => setName(e.target.value)}+ disabled={submitting}+ helperText="Unique among your own templates. Others may reuse it."+ />+ <TextField+ label="Description"+ value={description}+ onChange={(e) => setDescription(e.target.value)}+ disabled={submitting}+ multiline+ minRows={2}+ helperText="Shown in the catalogue, and searched alongside the name."+ />+ <TextField+ label="Kind"+ value={kind}+ onChange={(e) => setKind(e.target.value)}+ disabled={submitting}+ helperText="What this template provisions — room, group, agent."+ />+ <Stack direction="row" spacing={1} alignItems="center">+ <Button+ startIcon={<UploadFileIcon />}+ onClick={() => fileInput.current?.click()}+ disabled={submitting}+ >+ Load from file+ </Button>+ <input+ ref={fileInput}+ type="file"+ accept=".yaml,.yml,text/yaml,application/x-yaml"+ hidden+ onChange={(e) => {+ const file = e.target.files?.[0];+ if (file) void handleFile(file);+ e.target.value = "";+ }}+ />+ </Stack>+ <TextField+ label="Document"+ value={content}+ onChange={(e) => setContent(e.target.value)}+ disabled={submitting}+ multiline+ minRows={12}+ slotProps={{ input: { sx: { fontFamily: "monospace" } } }}+ helperText="Stored exactly as written. The registry does not parse it."+ />+ <TemplateFindings result={validation} checking={checking} />+ {error && <Alert severity="error">{error}</Alert>}+ </Stack>+ </DialogContent>+ <DialogActions>+ <Button onClick={handleClose} disabled={submitting}>+ Cancel+ </Button>+ <Button+ variant="contained"+ onClick={handleSubmit}+ disabled={!canSubmit}+ startIcon={submitting ? <CircularProgress size={16} /> : undefined}+ >+ Upload+ </Button>+ </DialogActions>+ </Dialog>+ );+}diff --git a/gateway/src/pages/resources/DeleteTemplateDialog.tsx b/gateway/src/pages/resources/DeleteTemplateDialog.tsxnew file mode 100644index 000000000..3fc6e5b0a--- /dev/null+++ b/gateway/src/pages/resources/DeleteTemplateDialog.tsx@@ -0,0 +1,85 @@+import {+ Alert,+ Button,+ CircularProgress,+ Dialog,+ DialogActions,+ DialogContent,+ DialogContentText,+ DialogTitle,+} from "@mui/material";+import { useState } from "react";+import { deleteTemplate } from "../../data/api";++/**+ * Separate from `DeleteResourceDialog` on purpose: that one warns which rooms a+ * resource is about to be detached from, and a template is attached to nothing.+ */+interface Props {+ open: boolean;+ templateId: string;+ templateLabel: string;+ onClose: () => void;+ onDeleted: () => void;+}++export default function DeleteTemplateDialog({+ open,+ templateId,+ templateLabel,+ onClose,+ onDeleted,+}: Props) {+ const [submitting, setSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const handleClose = () => {+ if (submitting) return;+ setError(null);+ onClose();+ };++ const handleDelete = async () => {+ setSubmitting(true);+ setError(null);+ try {+ await deleteTemplate(templateId);+ onDeleted();+ } catch (e) {+ setError(e instanceof Error ? e.message : "Failed to delete");+ } finally {+ setSubmitting(false);+ }+ };++ return (+ <Dialog open={open} onClose={handleClose} fullWidth maxWidth="xs">+ <DialogTitle>Delete template</DialogTitle>+ <DialogContent>+ <DialogContentText>+ Delete <b>{templateLabel}</b>? This cannot be undone. Rooms already+ created from it are unaffected.+ </DialogContentText>+ {error && (+ <Alert severity="error" sx={{ mt: 2 }}>+ {error}+ </Alert>+ )}+ </DialogContent>+ <DialogActions>+ <Button onClick={handleClose} disabled={submitting}>+ Cancel+ </Button>+ <Button+ color="error"+ variant="contained"+ onClick={handleDelete}+ disabled={submitting}+ startIcon={submitting ? <CircularProgress size={16} /> : undefined}+ >+ Delete+ </Button>+ </DialogActions>+ </Dialog>+ );+}diff --git a/gateway/src/pages/resources/ResourceFiltersBar.tsx b/gateway/src/pages/resources/ResourceFiltersBar.tsxindex 1f41931d0..5fa59f173 100644--- a/gateway/src/pages/resources/ResourceFiltersBar.tsx+++ b/gateway/src/pages/resources/ResourceFiltersBar.tsx@@ -25,6 +25,8 @@ interface Props {typeFilter?: string;onTypeChange?: (t: string) => void;types?: TypeOption[];+ /** What this axis is called on the resource being listed. */+ typeLabel?: string;}export default function ResourceFiltersBar({@@ -36,6 +38,7 @@ export default function ResourceFiltersBar({typeFilter,onTypeChange,types,+ typeLabel = "Type",}: Props) {const hasType = types !== undefined && onTypeChange !== undefined;@@ -76,12 +79,12 @@ export default function ResourceFiltersBar({<TextFieldsize="small"select- label="Type"+ label={typeLabel}value={typeFilter ?? ""}onChange={(e) => onTypeChange(e.target.value)}sx={{ minWidth: 180 }}>- <MenuItem value="">All types</MenuItem>+ <MenuItem value="">{`All ${typeLabel.toLowerCase()}s`}</MenuItem>{(types ?? []).map((t) => (<MenuItem key={t.value} value={t.value}>{t.label}diff --git a/gateway/src/pages/resources/ResourcesPage.tsx b/gateway/src/pages/resources/ResourcesPage.tsxindex 2154720d2..67a7f16d6 100644--- a/gateway/src/pages/resources/ResourcesPage.tsx+++ b/gateway/src/pages/resources/ResourcesPage.tsx@@ -9,29 +9,30 @@ import CreateReferenceTypeDialog from "./CreateReferenceTypeDialog";import DocumentsTab from "./DocumentsTab";import PackagesTab from "./PackagesTab";import ReferencesTab from "./ReferencesTab";+import CreateTemplateDialog from "./CreateTemplateDialog";import ReferenceTypesTab from "./ReferenceTypesTab";+import TemplatesTab from "./TemplatesTab";-type ResourceTab = "references" | "types" | "documents" | "packages";+// One list drives the tab bar, the URL parameter, the type and the create+// button's label. They belong together: a tab listed in one and missed in+// another renders a body nothing can navigate to, which compiles cleanly and+// is invisible until someone goes looking for the tab.+const TABS = [+ { value: "references", label: "References", newLabel: "New reference" },+ { value: "types", label: "Reference types", newLabel: "New reference type" },+ { value: "documents", label: "Documents", newLabel: "New document" },+ { value: "packages", label: "Packages", newLabel: "New package" },+ { value: "templates", label: "Templates", newLabel: "Upload template" },+] as const;-const NEW_LABELS: Record<ResourceTab, string> = {- references: "New reference",- types: "New reference type",- documents: "New document",- packages: "New package",-};+type ResourceTab = (typeof TABS)[number]["value"];export default function ResourcesPage() {const navigate = useNavigate();const [searchParams, setSearchParams] = useSearchParams();const tabParam = searchParams.get("tab");- const tab: ResourceTab =- tabParam === "documents"- ? "documents"- : tabParam === "packages"- ? "packages"- : tabParam === "types"- ? "types"- : "references";+ const active = TABS.find((t) => t.value === tabParam) ?? TABS[0];+ const tab: ResourceTab = active.value;const [createOpen, setCreateOpen] = useState(false);const [refreshKey, setRefreshKey] = useState(0);@@ -59,12 +60,16 @@ export default function ResourcesPage() {navigate(`/resources/packages/${id}`);};- const handleReferenceTypeCreated = () => {+ const handleTemplateCreated = (id: string) => {setCreateOpen(false);setRefreshKey((k) => k + 1);+ navigate(`/resources/templates/${id}`);};- const newLabel = NEW_LABELS[tab];+ const handleReferenceTypeCreated = () => {+ setCreateOpen(false);+ setRefreshKey((k) => k + 1);+ };return (<Box sx={{ display: "flex", flexDirection: "column", flexGrow: 1, minHeight: 0 }}>@@ -75,7 +80,7 @@ export default function ResourcesPage() {startIcon={<AddIcon />}onClick={() => setCreateOpen(true)}>- {newLabel}+ {active.newLabel}</Button></Stack>@@ -84,10 +89,9 @@ export default function ResourcesPage() {onChange={(_, v) => setTab(v as ResourceTab)}sx={{ mb: 2, borderBottom: 1, borderColor: "divider" }}>- <Tab label="References" value="references" />- <Tab label="Reference types" value="types" />- <Tab label="Documents" value="documents" />- <Tab label="Packages" value="packages" />+ {TABS.map((t) => (+ <Tab key={t.value} label={t.label} value={t.value} />+ ))}</Tabs><Box sx={{ display: "flex", flexDirection: "column", flexGrow: 1, minHeight: 0 }}>@@ -95,6 +99,7 @@ export default function ResourcesPage() {{tab === "types" && <ReferenceTypesTab refreshKey={refreshKey} />}{tab === "documents" && <DocumentsTab refreshKey={refreshKey} />}{tab === "packages" && <PackagesTab refreshKey={refreshKey} />}+ {tab === "templates" && <TemplatesTab refreshKey={refreshKey} />}</Box>{tab === "references" && (@@ -125,6 +130,13 @@ export default function ResourcesPage() {onCreated={handlePackageCreated}/>)}+ {tab === "templates" && (+ <CreateTemplateDialog+ open={createOpen}+ onClose={() => setCreateOpen(false)}+ onCreated={handleTemplateCreated}+ />+ )}</Box>);}diff --git a/gateway/src/pages/resources/TemplateDetailPage.tsx b/gateway/src/pages/resources/TemplateDetailPage.tsxnew file mode 100644index 000000000..47642299a--- /dev/null+++ b/gateway/src/pages/resources/TemplateDetailPage.tsx@@ -0,0 +1,355 @@+import ArrowBack from "@mui/icons-material/ArrowBack";+import ContentCopy from "@mui/icons-material/ContentCopy";+import DeleteOutline from "@mui/icons-material/DeleteOutline";+import Download from "@mui/icons-material/Download";+import {+ Alert,+ Box,+ Button,+ Chip,+ CircularProgress,+ Divider,+ IconButton,+ Stack,+ TextField,+ Typography,+} from "@mui/material";+import { useEffect, useMemo, useState } from "react";+import { useNavigate, useParams } from "react-router";+import {+ type TemplateDetail,+ fetchTemplate,+ fetchTemplateContent,+ updateTemplate,+} from "../../data/api";+import { useAuth } from "../../data/AuthContext";+import { EM_DASH, MONO_SX, formatDateTime } from "../../theme/hootFormat";+import DeleteTemplateDialog from "./DeleteTemplateDialog";+import TemplateFindings from "./TemplateFindings";+import { formatBytes, templateFilename } from "./templateFormat";+import { useTemplateValidation } from "./useTemplateValidation";++const LIST_URL = "/resources?tab=templates";++export default function TemplateDetailPage() {+ const { id } = useParams<{ id: string }>();+ const navigate = useNavigate();+ const { user } = useAuth();+ const [template, setTemplate] = useState<TemplateDetail | null>(null);+ const [loading, setLoading] = useState(true);+ const [fetchError, setFetchError] = useState<string | null>(null);+ const [deleteOpen, setDeleteOpen] = useState(false);++ useEffect(() => {+ if (!id) return;+ let cancelled = false;+ setLoading(true);+ fetchTemplate(id).then((t) => {+ if (cancelled) return;+ if (t) setTemplate(t);+ else setFetchError("Template not found");+ setLoading(false);+ });+ return () => {+ cancelled = true;+ };+ }, [id]);++ if (loading) {+ return (+ <Box sx={{ display: "flex", justifyContent: "center", py: 8 }}>+ <CircularProgress />+ </Box>+ );+ }++ if (fetchError || !template || !id) {+ return (+ <Box>+ <Button startIcon={<ArrowBack />} onClick={() => navigate("/resources")}>+ Back to resources+ </Button>+ <Alert severity="error" sx={{ mt: 2 }}>+ {fetchError ?? "Template not found"}+ </Alert>+ </Box>+ );+ }++ const canMutate =+ !!user && (user.id === template.owner_id || user.role === "admin");++ return (+ <Box>+ <Stack direction="row" alignItems="center" spacing={1} mb={2}>+ <IconButton onClick={() => navigate(LIST_URL)} size="small">+ <ArrowBack />+ </IconButton>+ <Typography variant="h5" sx={{ flexGrow: 1 }}>+ {template.name || "Template"}+ </Typography>+ <Chip size="small" variant="outlined" label={template.kind} />+ </Stack>++ <Stack spacing={4}>+ <InfoSection template={template} />+ <Divider />+ <DocumentSection+ template={template}+ canMutate={canMutate}+ onSaved={setTemplate}+ />+ {canMutate && (+ <>+ <Divider />+ <DangerSection onDelete={() => setDeleteOpen(true)} />+ </>+ )}+ </Stack>++ <DeleteTemplateDialog+ open={deleteOpen}+ templateId={id}+ templateLabel={template.name || id}+ onClose={() => setDeleteOpen(false)}+ onDeleted={() => navigate(LIST_URL)}+ />+ </Box>+ );+}++function InfoSection({ template }: { template: TemplateDetail }) {+ return (+ <Stack spacing={1}>+ <Typography+ variant="overline"+ sx={{ color: "text.secondary", display: "block" }}+ >+ Info+ </Typography>+ <InfoLine+ label="Owner"+ value={template.owner_name ?? template.owner_id}+ mono={!template.owner_name}+ />+ <InfoLine label="Revision" value={String(template.version)} />+ <InfoLine label="Size" value={formatBytes(template.size_bytes)} />+ <InfoLine label="Created" value={formatDateTime(template.created_at)} />+ <InfoLine label="Updated" value={formatDateTime(template.updated_at)} />+ </Stack>+ );+}++function InfoLine({+ label,+ value,+ mono,+}: {+ label: string;+ value: string | null | undefined;+ mono?: boolean;+}) {+ return (+ <Typography variant="body2" color="text.secondary">+ <strong>{label}:</strong>{" "}+ {value ? (+ <Box component="span" sx={mono ? MONO_SX : undefined}>+ {value}+ </Box>+ ) : (+ <Box component="span" sx={{ color: "text.secondary" }}>+ {EM_DASH}+ </Box>+ )}+ </Typography>+ );+}++function DocumentSection({+ template,+ canMutate,+ onSaved,+}: {+ template: TemplateDetail;+ canMutate: boolean;+ onSaved: (updated: TemplateDetail) => void;+}) {+ const [name, setName] = useState(template.name);+ const [description, setDescription] = useState(template.description);+ const [kind, setKind] = useState(template.kind);+ const [content, setContent] = useState(template.content);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [exportError, setExportError] = useState<string | null>(null);+ const [copied, setCopied] = useState(false);+ // Only while the document is editable — a reader cannot act on the findings.+ const { result: validation, checking } = useTemplateValidation(content, {+ enabled: canMutate,+ });++ const dirty = useMemo(+ () =>+ name !== template.name ||+ description !== template.description ||+ kind !== template.kind ||+ content !== template.content,+ [name, description, kind, content, template],+ );++ const handleSave = async () => {+ setSaving(true);+ setError(null);+ try {+ const updated = await updateTemplate(template.id, {+ name,+ description,+ kind,+ content,+ });+ onSaved(updated);+ setContent(updated.content);+ } catch (e) {+ setError(e instanceof Error ? e.message : "Failed to save");+ } finally {+ setSaving(false);+ }+ };++ // Both of these go back to the server for the document rather than using the+ // copy on screen, so what you download is what is stored even if the editor+ // has unsaved edits in it.+ const withStoredDocument = async (use: (text: string) => Promise<void> | void) => {+ setExportError(null);+ setCopied(false);+ try {+ await use(await fetchTemplateContent(template.id));+ } catch (e) {+ setExportError(e instanceof Error ? e.message : "Failed to fetch document");+ }+ };++ const handleCopy = () =>+ withStoredDocument(async (text) => {+ // Absent outside a secure context, where the bare property access would+ // read as "failed to fetch document" rather than the truth.+ if (!navigator.clipboard) {+ throw new Error("Copying needs a secure connection (HTTPS).");+ }+ await navigator.clipboard.writeText(text);+ setCopied(true);+ });++ const handleDownload = () =>+ withStoredDocument((text) => {+ const url = URL.createObjectURL(+ new Blob([text], { type: "application/x-yaml" }),+ );+ const a = document.createElement("a");+ a.href = url;+ a.download = templateFilename(template.name);+ document.body.appendChild(a);+ a.click();+ a.remove();+ // The click only queues the download; revoking in the same tick can pull+ // the blob out from under a browser that has not read it yet.+ setTimeout(() => URL.revokeObjectURL(url), 60_000);+ });++ return (+ <Stack spacing={2}>+ <Stack direction="row" alignItems="center" spacing={1}>+ <Typography+ variant="overline"+ sx={{ color: "text.secondary", flexGrow: 1 }}+ >+ Document+ </Typography>+ <Button size="small" startIcon={<ContentCopy />} onClick={handleCopy}>+ Copy+ </Button>+ <Button size="small" startIcon={<Download />} onClick={handleDownload}>+ Download+ </Button>+ </Stack>+ {exportError && <Alert severity="error">{exportError}</Alert>}+ {copied && <Alert severity="success">Document copied to the clipboard.</Alert>}+ {!canMutate && (+ // Said outright rather than left to the greyed-out fields. Every+ // template on the server is visible to everyone, so reading someone+ // else's is the ordinary case here, not the exception it is for the+ // resources next door — and a disabled field on its own only tells you+ // something is wrong once you have already tried to type in it.+ <Alert severity="info">+ This template belongs to {template.owner_name ?? "another user"}. You+ can copy or download it; only its owner or an admin can change it.+ </Alert>+ )}+ <TextField+ label="Name"+ value={name}+ onChange={(e) => setName(e.target.value)}+ disabled={!canMutate || saving}+ />+ <TextField+ label="Description"+ value={description}+ onChange={(e) => setDescription(e.target.value)}+ disabled={!canMutate || saving}+ multiline+ minRows={2}+ helperText="Shown in the catalogue, and searched alongside the name."+ />+ <TextField+ label="Kind"+ value={kind}+ onChange={(e) => setKind(e.target.value)}+ disabled={!canMutate || saving}+ sx={{ maxWidth: 320 }}+ />+ <TextField+ label="Document"+ value={content}+ onChange={(e) => setContent(e.target.value)}+ disabled={!canMutate || saving}+ multiline+ minRows={16}+ slotProps={{ input: { sx: { fontFamily: "monospace" } } }}+ helperText="Saving a changed document bumps the revision."+ />+ <TemplateFindings result={validation} checking={checking} />+ {error && <Alert severity="error">{error}</Alert>}+ <Box>+ <Button+ variant="contained"+ onClick={handleSave}+ disabled={!canMutate || !dirty || saving || !!validation?.blocked}+ startIcon={saving ? <CircularProgress size={16} /> : undefined}+ >+ Save+ </Button>+ </Box>+ </Stack>+ );+}++function DangerSection({ onDelete }: { onDelete: () => void }) {+ return (+ <Stack spacing={1}>+ <Typography+ variant="overline"+ sx={{ color: "error.main", display: "block" }}+ >+ Danger zone+ </Typography>+ <Button+ variant="outlined"+ color="error"+ startIcon={<DeleteOutline />}+ onClick={onDelete}+ sx={{ alignSelf: "flex-start" }}+ >+ Delete template+ </Button>+ </Stack>+ );+}diff --git a/gateway/src/pages/resources/TemplateFindings.tsx b/gateway/src/pages/resources/TemplateFindings.tsxnew file mode 100644index 000000000..6ab4b6161--- /dev/null+++ b/gateway/src/pages/resources/TemplateFindings.tsx@@ -0,0 +1,52 @@+import { Alert, AlertTitle, Box } from "@mui/material";+import type { TemplateValidation } from "../../data/api";++/**+ * What the checker made of the document.+ *+ * Most of it is advice: the registry stores documents in shapes this server+ * may not understand, so the form reports and the person decides. The one+ * exception is a document that is not YAML at all, which the server refuses —+ * said plainly here rather than left to a failed upload to explain.+ */+export default function TemplateFindings({+ result,+ checking,+}: {+ result: TemplateValidation | null;+ checking: boolean;+}) {+ if (checking || result === null) return null;+ if (result.errors.length === 0 && result.warnings.length === 0) return null;++ return (+ <Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>+ {result.errors.length > 0 && (+ <Alert severity="error">+ <AlertTitle>+ {result.errors.length === 1+ ? "This does not look like a valid template"+ : `${result.errors.length} problems with this template`}+ </AlertTitle>+ <Box component="ul" sx={{ m: 0, pl: 2.5 }}>+ {result.errors.map((f, i) => (+ <li key={`${f.code}-${f.subject ?? i}`}>{f.message}</li>+ ))}+ </Box>+ {result.blocked+ ? "This cannot be uploaded until it parses."+ : "You can still upload it — the registry stores documents it does not understand — but check this is what you meant."}+ </Alert>+ )}+ {result.warnings.length > 0 && (+ <Alert severity="warning">+ <Box component="ul" sx={{ m: 0, pl: 2.5 }}>+ {result.warnings.map((f, i) => (+ <li key={`${f.code}-${f.subject ?? i}`}>{f.message}</li>+ ))}+ </Box>+ </Alert>+ )}+ </Box>+ );+}diff --git a/gateway/src/pages/resources/TemplatesTab.tsx b/gateway/src/pages/resources/TemplatesTab.tsxnew file mode 100644index 000000000..5572686cb--- /dev/null+++ b/gateway/src/pages/resources/TemplatesTab.tsx@@ -0,0 +1,134 @@+import { Alert, Box, Chip, CircularProgress } from "@mui/material";+import type { GridColDef } from "@mui/x-data-grid";+import { useEffect, useMemo, useState } from "react";+import { useNavigate } from "react-router";+import DataTable from "../../components/DataTable";+import type { TemplateSummary } from "../../data/api";+import { useTemplates } from "../../data/hooks";+import ResourceFiltersBar from "./ResourceFiltersBar";+import { formatBytes } from "./templateFormat";+import { formatDate } from "../../theme/hootFormat";++interface Props {+ refreshKey: number;+}++export default function TemplatesTab({ refreshKey }: Props) {+ const navigate = useNavigate();+ const { data: templates, loading, error, refetch } = useTemplates();+ const [search, setSearch] = useState("");+ const [ownerId, setOwnerId] = useState<string>("");+ const [kind, setKind] = useState<string>("");++ useEffect(() => {+ refetch();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [refreshKey]);++ const owners = useMemo(() => {+ const m = new Map<string, string>();+ for (const t of templates ?? []) {+ m.set(t.owner_id, t.owner_name ?? t.owner_id);+ }+ return [...m.entries()].map(([id, name]) => ({ id, name }));+ }, [templates]);++ // Kinds are free text on the server, so the filter offers whatever is+ // actually in the registry rather than a list this page would have to grow.+ const kinds = useMemo(() => {+ const seen = new Set((templates ?? []).map((t) => t.kind));+ return [...seen].sort().map((k) => ({ value: k, label: k }));+ }, [templates]);++ const filtered = useMemo(() => {+ const q = search.trim().toLowerCase();+ return (templates ?? []).filter((t) => {+ if (ownerId && t.owner_id !== ownerId) return false;+ if (kind && t.kind !== kind) return false;+ if (+ q &&+ !t.name.toLowerCase().includes(q) &&+ !t.description.toLowerCase().includes(q)+ ) {+ return false;+ }+ return true;+ });+ }, [templates, search, ownerId, kind]);++ const columns = useMemo<GridColDef<TemplateSummary>[]>(+ () => [+ { field: "name", headerName: "Name", flex: 1, minWidth: 180 },+ {+ field: "description",+ headerName: "Description",+ flex: 2,+ minWidth: 260,+ },+ {+ field: "kind",+ headerName: "Kind",+ width: 110,+ renderCell: ({ value }) => (+ <Chip size="small" variant="outlined" label={value as string} />+ ),+ },+ {+ field: "owner_name",+ headerName: "Owner",+ width: 150,+ renderCell: ({ value, row }) => value ?? row.owner_id,+ },+ { field: "version", headerName: "Rev", width: 70, type: "number" },+ {+ field: "size_bytes",+ headerName: "Size",+ width: 90,+ valueFormatter: (value) => formatBytes(value as number),+ },+ {+ field: "updated_at",+ headerName: "Updated",+ width: 116,+ valueFormatter: (value) => formatDate(value as string),+ },+ ],+ [],+ );++ return (+ <Box+ sx={{ display: "flex", flexDirection: "column", flexGrow: 1, minHeight: 0 }}+ >+ <ResourceFiltersBar+ search={search}+ onSearchChange={setSearch}+ ownerId={ownerId}+ onOwnerChange={setOwnerId}+ owners={owners}+ typeFilter={kind}+ onTypeChange={setKind}+ types={kinds}+ typeLabel="Kind"+ />++ {error && (+ <Alert severity="error" sx={{ mb: 2 }}>+ {error}+ </Alert>+ )}++ {loading ? (+ <CircularProgress />+ ) : (+ <DataTable+ rows={filtered}+ columns={columns}+ fillHeight+ onRowClick={(params) => navigate(`/resources/templates/${params.id}`)}+ sx={{ "& .MuiDataGrid-row": { cursor: "pointer" } }}+ />+ )}+ </Box>+ );+}diff --git a/gateway/src/pages/resources/templateFormat.ts b/gateway/src/pages/resources/templateFormat.tsnew file mode 100644index 000000000..2668216b8--- /dev/null+++ b/gateway/src/pages/resources/templateFormat.ts@@ -0,0 +1,23 @@+/**+ * Mirrors `TEMPLATE_MAX_BYTES` on the server, whose default this matches.+ *+ * A guess, deliberately: the server is the authority and refuses an oversize+ * upload with a 413 either way. This only exists so a user who picks a huge+ * file is told before it is read into memory rather than after a round trip.+ * A server configured with a larger limit is not blocked by this — the check+ * only runs on the file picker, and the text area is not capped.+ */+export const MAX_DOCUMENT_BYTES = 1024 * 1024;++/** A byte count as a person would read it. */+export function formatBytes(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+}++/** The filename a downloaded template lands as. */+export function templateFilename(name: string): string {+ const safe = name.trim().replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");+ return `${safe || "template"}.yaml`;+}diff --git a/gateway/src/pages/resources/useTemplateValidation.ts b/gateway/src/pages/resources/useTemplateValidation.tsnew file mode 100644index 000000000..963033db9--- /dev/null+++ b/gateway/src/pages/resources/useTemplateValidation.ts@@ -0,0 +1,47 @@+import { useEffect, useRef, useState } from "react";+import { type TemplateValidation, validateTemplate } from "../../data/api";++/**+ * Check a document as it is edited, debounced.+ *+ * Advisory throughout: the server accepts an upload whatever comes back, and a+ * check that cannot be reached must never be the reason a form refuses to+ * submit — so a failed request clears the findings rather than inventing one.+ */+export function useTemplateValidation(+ content: string,+ { enabled = true }: { enabled?: boolean } = {},+): { result: TemplateValidation | null; checking: boolean } {+ const [result, setResult] = useState<TemplateValidation | null>(null);+ const [checking, setChecking] = useState(false);+ // Only the newest request may write the result; a slow earlier one landing+ // late would otherwise describe a document that is no longer on screen.+ const latest = useRef(0);++ useEffect(() => {+ if (!enabled || content.trim().length === 0) {+ setResult(null);+ setChecking(false);+ return;+ }++ const token = ++latest.current;+ setChecking(true);+ const timer = setTimeout(() => {+ validateTemplate(content)+ .then((r) => {+ if (token === latest.current) setResult(r);+ })+ .catch(() => {+ if (token === latest.current) setResult(null);+ })+ .finally(() => {+ if (token === latest.current) setChecking(false);+ });+ }, 400);++ return () => clearTimeout(timer);+ }, [content, enabled]);++ return { result, checking };+}