Skip to content

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

Add template installs: which template and revision made an agent or room

Simon Flack2468fedeb709
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index 74928165a..08be6d324 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -1353,6 +1353,106 @@ class Template(TenantScoped, Base):
)
+class TemplateInstall(TenantScoped, Base):
+ """One run of a template whose source the server vouches for: which
+ template, at which revision, and what it was run with.
+
+ ``source`` is ``official`` for a template that comes with Switch
+ (``template_id`` is its ``official:`` id, which nobody can save under) or
+ ``saved`` for a stored template (``template_id`` is its row's id, kept
+ after the row is deleted). ``inputs`` and ``builtins`` are what the
+ document was rendered with, so a later revision can be rendered the same
+ way to see what it would set. Written only by the server, when it runs a
+ template; nothing a caller sends names one.
+ """
+
+ __tablename__ = "template_installs"
+ __table_args__ = (
+ UniqueConstraint("id", "tenant_id", name="uq_template_installs_id_tenant"),
+ CheckConstraint(
+ "source IN ('official', 'saved')", name="ck_template_installs_source"
+ ),
+ Index("ix_template_installs_tenant_template", "tenant_id", "template_id"),
+ )
+
+ id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)
+ owner_id: Mapped[str] = mapped_column(Text, ForeignKey("users.id"), nullable=False)
+ source: Mapped[str] = mapped_column(Text, nullable=False)
+ template_id: Mapped[str] = mapped_column(Text, nullable=False)
+ template_name: Mapped[str] = mapped_column(Text, nullable=False)
+ revision: Mapped[int] = mapped_column(Integer, nullable=False)
+ inputs: Mapped[dict] = mapped_column(JSONB, nullable=False)
+ builtins: Mapped[dict] = mapped_column(JSONB, nullable=False)
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), server_default=func.now(), nullable=False
+ )
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True),
+ server_default=func.now(),
+ onupdate=func.now(),
+ nullable=False,
+ )
+
+
+class TemplateInstallResource(TenantScoped, Base):
+ """An agent or room a template install created, under the key the
+ template gives it, with a fingerprint of each value the template set.
+
+ A fingerprint still equal to the value's own is a value nobody has
+ changed since the template set it, which an update may replace; one that
+ differs was changed by someone, and is left as they made it. Exactly one
+ of ``agent_id`` and ``room_id`` is set, and the row goes with it.
+ """
+
+ __tablename__ = "template_install_resources"
+ __table_args__ = (
+ ForeignKeyConstraint(
+ ["tenant_id", "install_id"],
+ ["template_installs.tenant_id", "template_installs.id"],
+ name="fk_template_install_resources_install",
+ ondelete="CASCADE",
+ ),
+ ForeignKeyConstraint(
+ ["tenant_id", "agent_id"],
+ ["agents.tenant_id", "agents.id"],
+ name="fk_template_install_resources_agent",
+ ondelete="CASCADE",
+ ),
+ ForeignKeyConstraint(
+ ["tenant_id", "room_id"],
+ ["rooms.tenant_id", "rooms.id"],
+ name="fk_template_install_resources_room",
+ ondelete="CASCADE",
+ ),
+ CheckConstraint(
+ "(agent_id IS NULL) <> (room_id IS NULL)",
+ name="ck_template_install_resources_one_resource",
+ ),
+ Index(
+ "uq_template_install_resources_agent",
+ "tenant_id",
+ "agent_id",
+ unique=True,
+ postgresql_where=text("agent_id IS NOT NULL"),
+ ),
+ Index(
+ "uq_template_install_resources_room",
+ "tenant_id",
+ "room_id",
+ unique=True,
+ postgresql_where=text("room_id IS NOT NULL"),
+ ),
+ Index("ix_template_install_resources_install", "tenant_id", "install_id"),
+ )
+
+ id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)
+ install_id: Mapped[str] = mapped_column(Text, nullable=False)
+ key: Mapped[str] = mapped_column(Text, nullable=False)
+ agent_id: Mapped[str | None] = mapped_column(Text, nullable=True)
+ room_id: Mapped[str | None] = mapped_column(Text, nullable=True)
+ fingerprints: Mapped[dict] = mapped_column(JSONB, nullable=False)
+
+
# ── Packages ──────────────────────────────────────────────────────────────────
diff --git a/core/switch_core/db/stores/template_install_store.py b/core/switch_core/db/stores/template_install_store.py
new file mode 100644
index 000000000..02f923673
--- /dev/null
+++ b/core/switch_core/db/stores/template_install_store.py
@@ -0,0 +1,158 @@
+from dataclasses import dataclass
+from typing import Any
+
+from sqlalchemy import select, update
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from switch_core.db.models import (
+ TemplateInstall,
+ TemplateInstallResource,
+ require_tenant_id,
+)
+
+
+@dataclass(frozen=True)
+class NewInstallResource:
+ """An agent or room a run created, as its install records it."""
+
+ key: str
+ agent_id: str | None
+ room_id: str | None
+ fingerprints: dict[str, str]
+
+
+class TemplateInstallStore:
+ async def create(
+ self,
+ session: AsyncSession,
+ *,
+ owner_id: str,
+ source: str,
+ template_id: str,
+ template_name: str,
+ revision: int,
+ inputs: dict[str, Any],
+ builtins: dict[str, str],
+ resources: list[NewInstallResource],
+ ) -> TemplateInstall:
+ install = TemplateInstall(
+ owner_id=owner_id,
+ source=source,
+ template_id=template_id,
+ template_name=template_name,
+ revision=revision,
+ inputs=inputs,
+ builtins=builtins,
+ )
+ session.add(install)
+ await session.flush()
+ for resource in resources:
+ session.add(
+ TemplateInstallResource(
+ install_id=install.id,
+ key=resource.key,
+ agent_id=resource.agent_id,
+ room_id=resource.room_id,
+ fingerprints=resource.fingerprints,
+ )
+ )
+ await session.flush()
+ return install
+
+ async def of_template(
+ self, session: AsyncSession, template_id: str
+ ) -> list[TemplateInstall]:
+ """Every install of a template in this tenant, oldest first."""
+ result = await session.execute(
+ select(TemplateInstall)
+ .where(
+ TemplateInstall.tenant_id == require_tenant_id(),
+ TemplateInstall.template_id == template_id,
+ )
+ .order_by(TemplateInstall.created_at, TemplateInstall.id)
+ )
+ return list(result.scalars())
+
+ async def resources(
+ self, session: AsyncSession, install_id: str
+ ) -> list[TemplateInstallResource]:
+ result = await session.execute(
+ select(TemplateInstallResource)
+ .where(
+ TemplateInstallResource.tenant_id == require_tenant_id(),
+ TemplateInstallResource.install_id == install_id,
+ )
+ .order_by(TemplateInstallResource.key)
+ )
+ return list(result.scalars())
+
+ async def for_agent(
+ self, session: AsyncSession, agent_id: str
+ ) -> tuple[TemplateInstall, TemplateInstallResource] | None:
+ """The install that created an agent, and the agent's entry in it."""
+ row = (
+ await session.execute(
+ select(TemplateInstall, TemplateInstallResource)
+ .join(
+ TemplateInstallResource,
+ (TemplateInstallResource.install_id == TemplateInstall.id)
+ & (TemplateInstallResource.tenant_id == TemplateInstall.tenant_id),
+ )
+ .where(
+ TemplateInstallResource.tenant_id == require_tenant_id(),
+ TemplateInstallResource.agent_id == agent_id,
+ )
+ )
+ ).one_or_none()
+ if row is None:
+ return None
+ return row[0], row[1]
+
+ async def agents_installed_from(
+ self, session: AsyncSession, template_id: str, key: str
+ ) -> set[str]:
+ """The agents created under `key` by any install of `template_id`."""
+ result = await session.execute(
+ select(TemplateInstallResource.agent_id)
+ .join(
+ TemplateInstall,
+ (TemplateInstallResource.install_id == TemplateInstall.id)
+ & (TemplateInstallResource.tenant_id == TemplateInstall.tenant_id),
+ )
+ .where(
+ TemplateInstall.tenant_id == require_tenant_id(),
+ TemplateInstall.template_id == template_id,
+ TemplateInstallResource.key == key,
+ TemplateInstallResource.agent_id.is_not(None),
+ )
+ )
+ return {agent_id for agent_id in result.scalars() if agent_id is not None}
+
+ async def set_fingerprints(
+ self, session: AsyncSession, resource_id: str, fingerprints: dict[str, str]
+ ) -> None:
+ await session.execute(
+ update(TemplateInstallResource)
+ .where(
+ TemplateInstallResource.tenant_id == require_tenant_id(),
+ TemplateInstallResource.id == resource_id,
+ )
+ .values(fingerprints=fingerprints)
+ )
+
+ async def move_to_revision(
+ self, session: AsyncSession, install_id: str, *, from_revision: int, to: int
+ ) -> bool:
+ """Move an install to revision `to`, only while it is still at
+ `from_revision`: of two servers updating it at once, one moves it and
+ the other learns it lost. True when this call moved it."""
+ result = await session.execute(
+ update(TemplateInstall)
+ .where(
+ TemplateInstall.tenant_id == require_tenant_id(),
+ TemplateInstall.id == install_id,
+ TemplateInstall.revision == from_revision,
+ )
+ .values(revision=to)
+ )
+ return bool(result.rowcount) # type: ignore[attr-defined]
diff --git a/core/switch_core/migrations/versions/a4c1e7b93d20_template_installs.py b/core/switch_core/migrations/versions/a4c1e7b93d20_template_installs.py
new file mode 100644
index 000000000..16a564dc9
--- /dev/null
+++ b/core/switch_core/migrations/versions/a4c1e7b93d20_template_installs.py
@@ -0,0 +1,166 @@
+"""template installs: which template, at which revision, made an agent or room
+
+``template_installs`` holds one row for each template run whose source the
+server vouches for: an official template, or a saved one, by id, with the
+revision it was at and the inputs it was rendered with.
+``template_install_resources`` links each agent and room the run created to
+it, under the key the template gives it, with a fingerprint of each value
+the template set, so an update can tell a value nobody changed from one
+somebody did.
+
+Expand only: a release from before this revision never reads either table.
+
+The row-level-security DDL 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.
+
+Revision ID: a4c1e7b93d20
+Revises: f68b679599ab
+Create Date: 2026-10-26 10:00:00.000000
+
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+from sqlalchemy.dialects.postgresql import JSONB
+
+revision: str = "a4c1e7b93d20"
+down_revision: str | None = "f68b679599ab"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+expand_only: bool = True
+
+REQUIRE_TENANT_FUNCTION_NAME = "require_tenant_id"
+POLICY_NAME = "tenant_isolation"
+
+_PREDICATE = f'"tenant_id" = (SELECT {REQUIRE_TENANT_FUNCTION_NAME}())'
+
+
+def _create_policy(table: str) -> str:
+ return (
+ f'CREATE POLICY {POLICY_NAME} ON "{table}"\n'
+ f" FOR ALL\n"
+ f" USING ({_PREDICATE})\n"
+ f" WITH CHECK ({_PREDICATE})"
+ )
+
+
+def upgrade() -> None:
+ op.create_table(
+ "template_installs",
+ sa.Column("tenant_id", sa.Text(), nullable=False),
+ sa.Column("id", sa.Text(), nullable=False),
+ sa.Column("owner_id", sa.Text(), nullable=False),
+ sa.Column("source", sa.Text(), nullable=False),
+ sa.Column("template_id", sa.Text(), nullable=False),
+ sa.Column("template_name", sa.Text(), nullable=False),
+ sa.Column("revision", sa.Integer(), nullable=False),
+ sa.Column("inputs", JSONB(), nullable=False),
+ sa.Column("builtins", JSONB(), nullable=False),
+ sa.Column(
+ "created_at",
+ sa.DateTime(timezone=True),
+ server_default=sa.text("now()"),
+ nullable=False,
+ ),
+ sa.Column(
+ "updated_at",
+ sa.DateTime(timezone=True),
+ server_default=sa.text("now()"),
+ nullable=False,
+ ),
+ sa.ForeignKeyConstraint(
+ ["tenant_id"], ["tenants.id"], name="fk_template_installs_tenant"
+ ),
+ sa.ForeignKeyConstraint(["owner_id"], ["users.id"]),
+ sa.CheckConstraint(
+ "source IN ('official', 'saved')", name="ck_template_installs_source"
+ ),
+ sa.PrimaryKeyConstraint("id"),
+ sa.UniqueConstraint("id", "tenant_id", name="uq_template_installs_id_tenant"),
+ )
+ op.create_index(
+ "ix_template_installs_tenant_template",
+ "template_installs",
+ ["tenant_id", "template_id"],
+ )
+ op.create_table(
+ "template_install_resources",
+ sa.Column("tenant_id", sa.Text(), nullable=False),
+ sa.Column("id", sa.Text(), nullable=False),
+ sa.Column("install_id", sa.Text(), nullable=False),
+ sa.Column("key", sa.Text(), nullable=False),
+ sa.Column("agent_id", sa.Text(), nullable=True),
+ sa.Column("room_id", sa.Text(), nullable=True),
+ sa.Column("fingerprints", JSONB(), nullable=False),
+ sa.ForeignKeyConstraint(
+ ["tenant_id"], ["tenants.id"], name="fk_template_install_resources_tenant"
+ ),
+ sa.ForeignKeyConstraint(
+ ["tenant_id", "install_id"],
+ ["template_installs.tenant_id", "template_installs.id"],
+ name="fk_template_install_resources_install",
+ ondelete="CASCADE",
+ ),
+ sa.ForeignKeyConstraint(
+ ["tenant_id", "agent_id"],
+ ["agents.tenant_id", "agents.id"],
+ name="fk_template_install_resources_agent",
+ ondelete="CASCADE",
+ ),
+ sa.ForeignKeyConstraint(
+ ["tenant_id", "room_id"],
+ ["rooms.tenant_id", "rooms.id"],
+ name="fk_template_install_resources_room",
+ ondelete="CASCADE",
+ ),
+ sa.CheckConstraint(
+ "(agent_id IS NULL) <> (room_id IS NULL)",
+ name="ck_template_install_resources_one_resource",
+ ),
+ sa.PrimaryKeyConstraint("id"),
+ )
+ op.create_index(
+ "uq_template_install_resources_agent",
+ "template_install_resources",
+ ["tenant_id", "agent_id"],
+ unique=True,
+ postgresql_where=sa.text("agent_id IS NOT NULL"),
+ )
+ op.create_index(
+ "uq_template_install_resources_room",
+ "template_install_resources",
+ ["tenant_id", "room_id"],
+ unique=True,
+ postgresql_where=sa.text("room_id IS NOT NULL"),
+ )
+ op.create_index(
+ "ix_template_install_resources_install",
+ "template_install_resources",
+ ["tenant_id", "install_id"],
+ )
+ for table in ("template_installs", "template_install_resources"):
+ op.execute(f'ALTER TABLE "{table}" ENABLE ROW LEVEL SECURITY')
+ op.execute(_create_policy(table))
+
+
+def downgrade() -> None:
+ for table in ("template_install_resources", "template_installs"):
+ op.execute(f'DROP POLICY IF EXISTS {POLICY_NAME} ON "{table}"')
+ op.drop_index(
+ "ix_template_install_resources_install",
+ table_name="template_install_resources",
+ )
+ op.drop_index(
+ "uq_template_install_resources_room", table_name="template_install_resources"
+ )
+ op.drop_index(
+ "uq_template_install_resources_agent", table_name="template_install_resources"
+ )
+ op.drop_table("template_install_resources")
+ op.drop_index(
+ "ix_template_installs_tenant_template", table_name="template_installs"
+ )
+ op.drop_table("template_installs")
diff --git a/core/tests/switch_core/db/stores/test_template_install_store.py b/core/tests/switch_core/db/stores/test_template_install_store.py
new file mode 100644
index 000000000..dce55b8b4
--- /dev/null
+++ b/core/tests/switch_core/db/stores/test_template_install_store.py
@@ -0,0 +1,196 @@
+"""Template installs against real Postgres: what a run records, what goes
+with its agent, and two servers moving the same install at once."""
+
+from __future__ import annotations
+
+import pytest
+from sqlalchemy import delete, select
+from sqlalchemy.exc import IntegrityError
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import (
+ Agent,
+ ApiKey,
+ Client,
+ TemplateInstallResource,
+ User,
+)
+from switch_core.db.stores.template_install_store import (
+ NewInstallResource,
+ TemplateInstallStore,
+)
+
+_STORE = TemplateInstallStore()
+
+
+async def _agent(session: AsyncSession, name: str) -> Agent:
+ owner = User(
+ id=f"owner-{name}", name=name, email=f"{name}@example.test", role="user"
+ )
+ session.add(owner)
+ await session.flush()
+ client = Client(transport_user_id=f"@{name}:test", display_name=name, type="agent")
+ key = ApiKey(
+ user_id=owner.id,
+ key_hash=f"hash-{name}",
+ encrypted_key="",
+ label="unused fixture",
+ type="agent",
+ )
+ session.add_all([client, key])
+ await session.flush()
+ agent = Agent(
+ name=name,
+ description="test agent",
+ agent_type="session_addressable",
+ connector_type="claude",
+ integration_profile={},
+ client_id=client.id,
+ api_key_id=key.id,
+ owner_id=owner.id,
+ )
+ session.add(agent)
+ await session.flush()
+ return agent
+
+
+async def _install(session: AsyncSession, agent: Agent, *, revision: int = 1):
+ return await _STORE.create(
+ session,
+ owner_id=agent.owner_id,
+ source="official",
+ template_id="official:switch-buddy",
+ template_name="switch-buddy",
+ revision=revision,
+ inputs={"agent_name": agent.name},
+ builtins={"$creator": "max"},
+ resources=[
+ NewInstallResource(
+ key="buddy",
+ agent_id=agent.id,
+ room_id=None,
+ fingerprints={"instructions": "abc"},
+ )
+ ],
+ )
+
+
+async def test_an_agent_is_found_by_the_install_that_made_it(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ async with session_factory() as session:
+ agent = await _agent(session, "switch-buddy-max")
+ install = await _install(session, agent, revision=3)
+ await session.commit()
+
+ async with session_factory() as session:
+ found = await _STORE.for_agent(session, agent.id)
+ assert found is not None
+ got, resource = found
+ assert (got.id, got.template_id, got.revision) == (
+ install.id,
+ "official:switch-buddy",
+ 3,
+ )
+ assert (resource.key, resource.fingerprints) == (
+ "buddy",
+ {"instructions": "abc"},
+ )
+ assert await _STORE.agents_installed_from(
+ session, "official:switch-buddy", "buddy"
+ ) == {agent.id}
+ assert await _STORE.for_agent(session, "someone-else") is None
+
+
+async def test_the_record_goes_with_its_agent(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ async with session_factory() as session:
+ agent = await _agent(session, "switch-buddy-max")
+ install = await _install(session, agent)
+ await session.commit()
+
+ async with session_factory() as session:
+ await session.execute(delete(Agent).where(Agent.id == agent.id))
+ await session.commit()
+
+ async with session_factory() as session:
+ assert await _STORE.resources(session, install.id) == []
+
+
+async def test_an_agent_belongs_to_one_install_at_most(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ async with session_factory() as session:
+ agent = await _agent(session, "switch-buddy-max")
+ await _install(session, agent)
+ await session.commit()
+
+ async with session_factory() as session:
+ with pytest.raises(IntegrityError):
+ await _install(session, agent)
+
+
+async def test_a_resource_is_an_agent_or_a_room_never_both_or_neither(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ async with session_factory() as session:
+ agent = await _agent(session, "switch-buddy-max")
+ install = await _install(session, agent)
+ await session.commit()
+
+ async with session_factory() as session:
+ session.add(
+ TemplateInstallResource(
+ install_id=install.id,
+ key="nothing",
+ agent_id=None,
+ room_id=None,
+ fingerprints={},
+ )
+ )
+ with pytest.raises(IntegrityError):
+ await session.flush()
+
+
+async def test_of_two_servers_moving_an_install_only_one_does(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ async with session_factory() as session:
+ agent = await _agent(session, "switch-buddy-max")
+ install = await _install(session, agent, revision=1)
+ await session.commit()
+
+ async with session_factory() as session:
+ assert await _STORE.move_to_revision(session, install.id, from_revision=1, to=2)
+ await session.commit()
+ async with session_factory() as session:
+ assert not await _STORE.move_to_revision(
+ session, install.id, from_revision=1, to=2
+ )
+ await session.commit()
+
+ async with session_factory() as session:
+ (got,) = await _STORE.of_template(session, "official:switch-buddy")
+ assert got.revision == 2
+
+
+async def test_fingerprints_are_replaced_whole(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ async with session_factory() as session:
+ agent = await _agent(session, "switch-buddy-max")
+ install = await _install(session, agent)
+ (resource,) = await _STORE.resources(session, install.id)
+ await _STORE.set_fingerprints(session, resource.id, {"description": "d"})
+ await session.commit()
+
+ async with session_factory() as session:
+ stored = (
+ await session.execute(
+ select(TemplateInstallResource.fingerprints).where(
+ TemplateInstallResource.id == resource.id
+ )
+ )
+ ).scalar_one()
+ assert stored == {"description": "d"}