"""Observability tables (migration 0012; RLS forced): security signals and alerts.""" from __future__ import annotations import uuid from typing import Any from sqlalchemy import CheckConstraint, Index, Integer, String, Text, UniqueConstraint from sqlalchemy.dialects.postgresql import JSONB, UUID from sqlalchemy.orm import Mapped, mapped_column from core.db.base import Base, TenantMixin, TimestampMixin, new_id class SecuritySignal(TenantMixin, TimestampMixin, Base): """A heuristic signal on inbound untrusted text (e.g. ``injection``). Signals feed routing hints and alerting only; they never grant or remove a permission. ``detail`` holds rule names and the event source, never the text itself.""" __tablename__ = "security_signals" __table_args__ = (Index("ix_security_signals_kind_at", "tenant_id", "kind", "created_at"),) id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=new_id) run_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True) kind: Mapped[str] = mapped_column(String(40), nullable=False) score: Mapped[int] = mapped_column(Integer, nullable=False, default=0) detail: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False, default=dict) class Alert(TenantMixin, TimestampMixin, Base): """One alert per (tenant, dedupe key): a sweep that finds the same condition in the same window does not alert twice.""" __tablename__ = "alerts" __table_args__ = ( UniqueConstraint("tenant_id", "dedupe_key", name="uq_alerts_tenant_dedupe"), CheckConstraint("severity IN ('info', 'warning', 'critical')", name="severity"), CheckConstraint("status IN ('open', 'acknowledged')", name="status"), ) id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=new_id) kind: Mapped[str] = mapped_column(String(40), nullable=False) severity: Mapped[str] = mapped_column(String(10), nullable=False) message: Mapped[str] = mapped_column(Text, nullable=False) detail: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False, default=dict) dedupe_key: Mapped[str] = mapped_column(String(200), nullable=False) status: Mapped[str] = mapped_column(String(15), nullable=False, default="open") delivered: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False, default=dict)