"""Procedural memory: versioned prompts and SOPs with labels (``production`` for deploy and rollback), behind a provider-agnostic ``PromptRegistry`` interface. ``LocalPromptRegistry`` keeps versions in ``prompt_versions`` (RLS). A Langfuse-backed registry (Phase 15) implements the same four methods with Langfuse prompt management: ``get`` -> ``langfuse.get_prompt(name, label=...)``, ``create`` -> ``create_prompt``, ``set_label`` -> ``update_prompt(name, version, new_labels=[...])``. Versions are immutable; a label points at exactly one version per name (setting it moves it). Rollback = set ``production`` on an older version. """ from __future__ import annotations import re import uuid from dataclasses import dataclass from datetime import datetime from typing import Any, Protocol from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession from core.db.session import Database from core.memory.models import PromptVersion from core.tools.preview import sha256_hex PRODUCTION = "production" NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_.-]{0,199}$") LABEL_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,39}$") MAX_BODY = 20_000 class PromptError(ValueError): pass @dataclass(frozen=True) class PromptRecord: name: str version: int body: str labels: tuple[str, ...] created_by: str created_at: datetime | None checksum: str def as_dict(self) -> dict[str, Any]: return { "name": self.name, "version": self.version, "body": self.body, "labels": list(self.labels), "created_by": self.created_by, "created_at": self.created_at, "checksum": self.checksum, } class PromptRegistry(Protocol): async def get( self, tenant_id: uuid.UUID, name: str, label: str = PRODUCTION ) -> PromptRecord | None: ... async def create( self, tenant_id: uuid.UUID, name: str, body: str, *, actor: str, labels: tuple[str, ...] = (), ) -> PromptRecord: ... async def set_label( self, tenant_id: uuid.UUID, name: str, version: int, label: str ) -> PromptRecord: ... async def versions( self, tenant_id: uuid.UUID, name: str | None = None ) -> list[PromptRecord]: ... def _record(row: PromptVersion) -> PromptRecord: return PromptRecord( name=row.name, version=row.version, body=row.body, labels=tuple(row.labels or ()), created_by=row.created_by, created_at=row.created_at, checksum=row.checksum, ) def _check(name: str, labels: tuple[str, ...] = ()) -> None: if not NAME_RE.match(name): raise PromptError("prompt names are lowercase letters, digits, '.', '_' or '-'") for label in labels: if not LABEL_RE.match(label) or label == "latest": raise PromptError(f"invalid label {label!r}") # Session-level operations (used by the gateway tool and by LocalPromptRegistry). async def get_prompt(s: AsyncSession, name: str, label: str = PRODUCTION) -> PromptRecord | None: q = select(PromptVersion).where(PromptVersion.name == name) if label == "latest": q = q.order_by(PromptVersion.version.desc()) else: q = q.where(PromptVersion.labels.contains([label])) row = (await s.execute(q.limit(1))).scalar_one_or_none() if row is None: return None if sha256_hex(row.body) != row.checksum: raise PromptError(f"prompt {name} v{row.version} failed its checksum") return _record(row) async def create_prompt( s: AsyncSession, tenant_id: uuid.UUID, name: str, body: str, *, actor: str, labels: tuple[str, ...] = (), ) -> PromptRecord: _check(name, labels) if not body.strip() or len(body) > MAX_BODY: raise PromptError(f"prompt body must be 1-{MAX_BODY} characters") # Serialize version numbering per (tenant, name). await s.execute(select(func.pg_advisory_xact_lock(func.hashtext(f"prompt:{tenant_id}:{name}")))) latest = ( await s.execute(select(func.max(PromptVersion.version)).where(PromptVersion.name == name)) ).scalar_one() row = PromptVersion( tenant_id=tenant_id, name=name, version=int(latest or 0) + 1, body=body, labels=[], meta={}, checksum=sha256_hex(body), created_by=actor[:120], ) s.add(row) await s.flush() for label in labels: await set_prompt_label(s, name, row.version, label) await s.refresh(row) return _record(row) async def set_prompt_label(s: AsyncSession, name: str, version: int, label: str) -> PromptRecord: _check(name, (label,)) rows = list( (await s.execute(select(PromptVersion).where(PromptVersion.name == name))).scalars() ) target = next((r for r in rows if r.version == version), None) if target is None: raise PromptError(f"prompt {name} has no version {version}") for r in rows: if r is not target and label in (r.labels or []): r.labels = [x for x in r.labels if x != label] if label not in (target.labels or []): target.labels = [*(target.labels or []), label] await s.flush() return _record(target) async def list_prompts(s: AsyncSession, name: str | None = None) -> list[PromptRecord]: q = select(PromptVersion).order_by(PromptVersion.name, PromptVersion.version.desc()) if name is not None: q = q.where(PromptVersion.name == name) return [_record(r) for r in (await s.execute(q)).scalars()] class LocalPromptRegistry: def __init__(self, db: Database) -> None: self.db = db async def get( self, tenant_id: uuid.UUID, name: str, label: str = PRODUCTION ) -> PromptRecord | None: async with self.db.session(tenant_id=tenant_id) as s: return await get_prompt(s, name, label) async def create( self, tenant_id: uuid.UUID, name: str, body: str, *, actor: str, labels: tuple[str, ...] = (), ) -> PromptRecord: async with self.db.session(tenant_id=tenant_id) as s, s.begin(): return await create_prompt(s, tenant_id, name, body, actor=actor, labels=labels) async def set_label( self, tenant_id: uuid.UUID, name: str, version: int, label: str ) -> PromptRecord: async with self.db.session(tenant_id=tenant_id) as s, s.begin(): return await set_prompt_label(s, name, version, label) async def versions(self, tenant_id: uuid.UUID, name: str | None = None) -> list[PromptRecord]: async with self.db.session(tenant_id=tenant_id) as s: return await list_prompts(s, name)