Coverage for app / db / postgres / models.py: 100%
923 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1from uuid import uuid4
3from sqlalchemy import (
4 JSON,
5 BigInteger,
6 Boolean,
7 CheckConstraint,
8 Column,
9 Date,
10 DateTime,
11 Enum,
12 Float,
13 ForeignKey,
14 Index,
15 Integer,
16 Numeric,
17 String,
18 Table,
19 Text,
20 UniqueConstraint,
21 text,
22)
23from sqlalchemy.dialects.postgresql import UUID
24from sqlalchemy.orm import declarative_base, relationship
26from app.util import cost_profiles, knowledge_categories
27from app.util.time import aware_utcnow
29from .enums import (
30 AgentEnum,
31 DashboardEnum,
32 EvaluationEnum,
33 GenerationEnum,
34 GovernanceEnum,
35 HistoryEnum,
36 MessageEnum,
37 PermissionEnum,
38 ReviewEnum,
39 RuleEnum,
40 SchedulerEnum,
41 SimulationEnum,
42 UsageEnum,
43)
44from .mixin import (
45 ClonableMixin,
46 DateMixin,
47 FKMixin,
48 GenerationMixin,
49 OwnableMixin,
50 RunnableMixin,
51 SystemMixin,
52 ownership_constraint,
53)
55Base = declarative_base()
58# -- Users --
61class User(DateMixin.Updated, Base):
62 """
63 Local representation of an Auth0 user.
64 Auth0 is the source of truth for authentication.
65 """
67 __tablename__ = "users"
69 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
71 # Auth0 user identifier (e.g. "auth0|abc123")
72 auth0_id = Column(String(255), unique=True, nullable=False, index=True)
74 email = Column(String(255), nullable=False, index=True)
75 email_verified = Column(Boolean, default=False)
77 name = Column(String(255), nullable=True)
78 picture = Column(String(1024), nullable=True)
80 is_active = Column(Boolean, default=True)
81 is_superuser = Column(Boolean, default=False)
82 # Platform roles assigned in Auth0 (app/services/platform_roles.py), kept
83 # in step on every request whose identity carries them.
84 platform_roles = Column(JSON, nullable=False, default=list, server_default="[]")
86 organisations = relationship(
87 "UserOrganisation", back_populates="user", cascade="all, delete-orphan"
88 )
89 projects = relationship(
90 "UserProject", back_populates="user", cascade="all, delete-orphan"
91 )
94# -- Organisations --
95class Organisation(DateMixin.Created, Base):
96 __tablename__ = "organisations"
98 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
100 name = Column(String(255), nullable=False, unique=True)
102 # Optional mapping to Auth0 Organizations
103 auth0_org_id = Column(String(255), unique=True, nullable=True)
105 #: The code finance files this organisation's spend under (migration
106 #: 100): on every row of the finance export, frozen into each statement.
107 cost_centre = Column(String(64), nullable=True)
109 members = relationship(
110 "UserOrganisation", back_populates="organisation", cascade="all, delete-orphan"
111 )
113 projects = relationship(
114 "Project",
115 primaryjoin="Project.owner_organisation_id == Organisation.id",
116 foreign_keys="[Project.owner_organisation_id]",
117 viewonly=True,
118 )
121class UserOrganisation(FKMixin.Role, DateMixin.Joined, Base):
122 __tablename__ = "user_organisations"
124 user_id = Column(
125 UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), primary_key=True
126 )
127 organisation_id = Column(
128 UUID(as_uuid=True),
129 ForeignKey("organisations.id", ondelete="CASCADE"),
130 primary_key=True,
131 )
133 #: A member's level in each access area (``app/services/access.py``),
134 #: e.g. ``{"agents": "editor", "governance": "reader"}``. Ignored for an
135 #: admin, who is an editor everywhere.
136 access = Column(JSON, nullable=True)
138 user = relationship("User", back_populates="organisations")
139 organisation = relationship("Organisation", back_populates="members")
140 role = relationship("Role")
143# -- Projects --
146class Project(OwnableMixin.Resource, GenerationMixin.Tagged, DateMixin.Created, Base):
147 __tablename__ = "projects"
149 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
151 name = Column(String(255), nullable=False)
152 description = Column(Text)
153 #: The code finance files this project's spend under (migration 100) —
154 #: its rows of its organisation's finance export carry it.
155 cost_centre = Column(String(64), nullable=True)
157 members = relationship(
158 "UserProject", back_populates="project", cascade="all, delete-orphan"
159 )
161 __table_args__ = (
162 UniqueConstraint(
163 "owner_user_id",
164 "owner_organisation_id",
165 "owner_project_id",
166 "name",
167 name="uq_owner_project_name",
168 ),
169 ownership_constraint("projects"),
170 # Projects are one level deep: a person's or an organisation's,
171 # never another project's (``app/services/workspace.py``).
172 CheckConstraint("owner_project_id IS NULL", name="ck_projects_not_nested"),
173 )
176class UserProject(FKMixin.Role, DateMixin.Joined, Base):
177 __tablename__ = "user_projects"
179 user_id = Column(
180 UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), primary_key=True
181 )
182 project_id = Column(
183 UUID(as_uuid=True),
184 ForeignKey("projects.id", ondelete="CASCADE"),
185 primary_key=True,
186 )
188 #: As ``UserOrganisation.access``.
189 access = Column(JSON, nullable=True)
191 user = relationship("User", back_populates="projects")
192 project = relationship("Project", back_populates="members")
193 role = relationship("Role")
196# -- Roles & Permissions --
197role_permissions = Table(
198 "role_permissions",
199 Base.metadata,
200 Column("role_id", ForeignKey("roles.id", ondelete="CASCADE"), primary_key=True),
201 Column(
202 "permission_id",
203 ForeignKey("permissions.id", ondelete="CASCADE"),
204 primary_key=True,
205 ),
206)
209class Role(Base):
210 __tablename__ = "roles"
212 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
213 name = Column(String(100), unique=True, nullable=False)
214 description = Column(Text)
216 permissions = relationship(
217 "Permission",
218 secondary=role_permissions,
219 back_populates="roles",
220 )
223class Permission(Base):
224 __tablename__ = "permissions"
226 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
227 permission_code = Column(
228 Enum(PermissionEnum.Code, name="permission_code_enum"),
229 unique=True,
230 nullable=False,
231 )
232 description = Column(Text)
234 roles = relationship(
235 "Role",
236 secondary=role_permissions,
237 back_populates="permissions",
238 )
241class MembershipInvite(DateMixin.Created, Base):
242 """A single-use link that admits one person to an organisation.
244 The stack sends no email, so an admin creates the invite and passes the
245 link on themselves. Only a SHA-256 of the token is stored: the token is
246 shown once, when the invite is made, and a copy of this table cannot be
247 turned back into working links. The invite names the email it is for,
248 and only a signed-in user with that email can accept it, so a forwarded
249 link admits nobody else.
251 ``organisation_id`` and ``project_id`` follow the ownership pattern —
252 exactly one is set — so project invites need no migration when projects
253 gain membership management. See ``app/services/membership.py``.
254 """
256 __tablename__ = "membership_invites"
258 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
259 organisation_id = Column(
260 UUID(as_uuid=True),
261 ForeignKey("organisations.id", ondelete="CASCADE"),
262 nullable=True,
263 index=True,
264 )
265 project_id = Column(
266 UUID(as_uuid=True),
267 ForeignKey("projects.id", ondelete="CASCADE"),
268 nullable=True,
269 index=True,
270 )
271 #: Lower-cased: the address the invite admits.
272 email = Column(String(255), nullable=False)
273 role_id = Column(UUID(as_uuid=True), ForeignKey("roles.id"), nullable=False)
274 #: The access areas the invitee will join with (``access.py``).
275 access = Column(JSON, nullable=True)
276 token_hash = Column(String(64), nullable=False, unique=True)
277 created_by_user_id = Column(
278 UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True
279 )
280 expires_at = Column(DateTime, nullable=False)
281 accepted_at = Column(DateTime, nullable=True)
282 accepted_by_user_id = Column(
283 UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True
284 )
285 revoked_at = Column(DateTime, nullable=True)
286 revoked_by_user_id = Column(
287 UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True
288 )
290 role = relationship("Role")
292 __table_args__ = (
293 CheckConstraint(
294 "(organisation_id IS NOT NULL)::int + (project_id IS NOT NULL)::int = 1",
295 name="ck_membership_invites_one_scope",
296 ),
297 )
300# -- Resource version history (audit trail) --
303class ResourceVersion(DateMixin.Created, Base):
304 """One immutable snapshot of a resource's editable fields.
306 Supersedes the old ``audit_logs`` table, which only recorded a bare
307 action label with no snapshot/diff content. ``resource_id`` is a soft
308 reference (no FK, same reasoning as ``LLMArtifact.ai_model_id``) —
309 history must outlive the resource itself, since a deleted resource's
310 history is exactly when it matters most. ``resource_type`` +
311 ``resource_id`` is the lookup key; ``version_number`` is 1-based and
312 monotonic per resource, like a git commit sequence.
313 """
315 __tablename__ = "resource_versions"
317 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
319 resource_type = Column(
320 Enum(HistoryEnum.ResourceType, name="resource_version_type_enum"),
321 nullable=False,
322 index=True,
323 )
324 resource_id = Column(UUID(as_uuid=True), nullable=False, index=True)
325 version_number = Column(Integer, nullable=False)
327 action = Column(
328 Enum(HistoryEnum.Action, name="resource_version_action_enum"),
329 nullable=False,
330 )
332 # Full serialisable snapshot of the resource's own fields (post-redaction).
333 snapshot = Column(JSON, nullable=False)
335 # Composite/child state at this point in time (e.g. an agent's toolkit/
336 # skillset/repository grants) — see app/services/history.py.
337 children_snapshot = Column(JSON, nullable=True)
339 # Field names that changed vs. the previous version — precomputed at
340 # write time so list views don't recompute a full diff per row.
341 changed_fields = Column(JSON, nullable=False, default=list)
343 actor_user_id = Column(
344 UUID(as_uuid=True),
345 ForeignKey("users.id", ondelete="SET NULL"),
346 nullable=True,
347 index=True,
348 )
350 # The generative invocation responsible for this version, when there was
351 # one. Set on the ``created`` version of every resource a generative flow
352 # persists, and on any later version a flow writes. Null means a human
353 # made this edit by hand. Reading it back gives the flow, the arguments
354 # and the model — see ``GenerationRun``.
355 generation_id = Column(
356 UUID(as_uuid=True),
357 ForeignKey("generation_runs.id", ondelete="SET NULL"),
358 nullable=True,
359 index=True,
360 )
362 # Who wrote a version no person made (``HistoryEnum.Origin``): ``release``
363 # when a CHAIN-R release changed the resource. Null for every version a
364 # person or a generative flow wrote.
365 origin = Column(String(16), nullable=True)
367 __table_args__ = (
368 UniqueConstraint(
369 "resource_type",
370 "resource_id",
371 "version_number",
372 name="uq_resource_version_number",
373 ),
374 Index(
375 "ix_resource_versions_resource",
376 "resource_type",
377 "resource_id",
378 "version_number",
379 ),
380 )
383# -- Generative invocations --
386class GenerationRun(DateMixin.Created, Base):
387 """One invocation of a generative flow, with the arguments it was given.
389 ``is_ai_generated`` on a resource says *that* it was generated; this row
390 says *how*. It is written when the flow is invoked — before the user has
391 accepted anything — so a proposal the user rejected is still on record,
392 and a flow that failed is too.
394 ``target_resource_type``/``target_resource_id`` are soft references (no
395 FK, same reasoning as ``ResourceVersion.resource_id``): the invocation
396 must outlive whatever it produced. Resources point back the other way
397 through ``GenerationMixin.Tagged.generation_id``, which *is* a real FK
398 because a generation run is never deleted.
399 """
401 __tablename__ = "generation_runs"
403 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
405 flow = Column(
406 Enum(GenerationEnum.Flow, name="generation_flow_enum"),
407 nullable=False,
408 index=True,
409 )
410 status = Column(
411 Enum(GenerationEnum.Status, name="generation_status_enum"),
412 nullable=False,
413 default=GenerationEnum.Status.proposed,
414 server_default=GenerationEnum.Status.proposed,
415 index=True,
416 )
418 # The request body that drove the invocation, post-redaction. The whole
419 # point of the row: "what exactly was asked for?"
420 arguments = Column(JSON, nullable=False, default=dict)
422 # Which model answered. ``ai_model_id`` is a soft reference to svc-ai's
423 # llm_models.id (same reasoning as ``LLMArtifact.ai_model_id``); provider
424 # and model_name are denormalised so the row still reads correctly after
425 # a model is deregistered or renamed upstream.
426 ai_model_id = Column(UUID(as_uuid=True), nullable=True, index=True)
427 provider = Column(String(128), nullable=True)
428 model_name = Column(String(255), nullable=True)
430 # What the invocation was building, once known. For agent setup this is
431 # the agent; for dashboard setup, the board. Null while a proposal is
432 # still unapplied.
433 target_resource_type = Column(
434 Enum(HistoryEnum.ResourceType, name="resource_version_type_enum"),
435 nullable=True,
436 index=True,
437 )
438 target_resource_id = Column(UUID(as_uuid=True), nullable=True, index=True)
440 # Non-fatal problems the flow reported (dropped widgets, hallucinated ids
441 # filtered out). Kept because "why is this board missing a tile?" is
442 # answered here and nowhere else.
443 warnings = Column(JSON, nullable=True)
445 # Populated when status becomes ``failed``.
446 error = Column(Text, nullable=True)
448 # For a flow that runs in the background (knowledge setup): the proposal
449 # it produced, kept so the person can come back to it, and where a run
450 # still ``running`` has got to — ``{stage, updated_at, …counts, message}``.
451 proposal = Column(JSON, nullable=True)
452 progress = Column(JSON, nullable=True)
454 actor_user_id = Column(
455 UUID(as_uuid=True),
456 ForeignKey("users.id", ondelete="SET NULL"),
457 nullable=True,
458 index=True,
459 )
460 #: The workspace the flow was invoked in (``app/services/workspace.py``)
461 #: — where its output is created. Neither set: the actor's Personal.
462 workspace_organisation_id = Column(UUID(as_uuid=True), nullable=True, index=True)
463 workspace_project_id = Column(UUID(as_uuid=True), nullable=True, index=True)
465 applied_at = Column(DateTime, nullable=True)
467 # Arguments can carry a free-text description but never credentials; the
468 # flows redact before writing. Declared for symmetry with the resource
469 # models so ``build_snapshot`` behaves if this ever gains history itself.
470 AUDIT_EXCLUDED_FIELDS = set()
472 __table_args__ = (
473 Index(
474 "ix_generation_runs_target",
475 "target_resource_type",
476 "target_resource_id",
477 ),
478 )
481# -- Agents --
484class Agent(
485 OwnableMixin.Resource,
486 ClonableMixin,
487 SystemMixin,
488 GenerationMixin.Tagged,
489 DateMixin.Created,
490 Base,
491):
492 __tablename__ = "agents"
494 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
496 name = Column(String(255), nullable=False)
497 description = Column(Text)
499 agent_type = Column(
500 Enum(AgentEnum.Type, name="agent_type_enum"),
501 nullable=False,
502 default=AgentEnum.Type.skill_based,
503 server_default=AgentEnum.Type.skill_based,
504 )
506 # Lucide icon name and a tailwind-ish accent key, both chosen in the UI.
507 # Same presentation contract as Dashboard: unset means the surface falls
508 # back to its default glyph and a neutral tone.
509 icon = Column(String(64), nullable=True)
510 accent = Column(String(32), nullable=True)
512 system_prompt = Column(Text, nullable=True)
513 tools = Column(JSON, nullable=True) # legacy / raw tool schemas
514 config = Column(JSON, nullable=True) # agent-level override
516 # Soft reference to svc-ai's llm_models.id — no FK constraint
517 ai_model_id = Column(UUID(as_uuid=True), nullable=True)
519 # Check a chat request's scope before starting, and ask the person a few
520 # structured questions when it is ambiguous (svc-ai's ``__clarify__``
521 # node). New agents do; agents that predate migration 71 keep answering
522 # straight away until their owner turns it on, so an upgrade does not
523 # change a live agent's behaviour — or its evaluation baselines.
524 clarify_scope = Column(
525 Boolean, nullable=False, default=True, server_default="false"
526 )
528 # How much pipeline work a turn does (cost-control plan, B2): a key from
529 # ``app/util/cost_profiles.py``, sent to svc-ai on every request
530 # (``app/services/agent_spec.py``), which decides what it changes. Every
531 # agent is ``thorough`` — the pipeline as it always ran — until a
532 # cheaper profile has been measured and chosen.
533 cost_profile = Column(
534 String(32),
535 nullable=False,
536 default=cost_profiles.DEFAULT.value,
537 server_default=cost_profiles.DEFAULT.value,
538 )
540 conversations = relationship(
541 "Conversation",
542 back_populates="agent",
543 cascade="all, delete-orphan",
544 )
545 industries = relationship(
546 "ResourceIndustry", secondary="agent_industries", back_populates="agents"
547 )
548 roles = relationship(
549 "ResourceRole", secondary="agent_roles", back_populates="agents"
550 )
551 __table_args__ = (
552 UniqueConstraint(
553 "owner_user_id",
554 "owner_organisation_id",
555 "owner_project_id",
556 "name",
557 name="uq_owner_agent_name",
558 ),
559 ownership_constraint("agents", allow_system=True),
560 )
563class AgentMemory(FKMixin.Agent.Child, DateMixin.Created, Base):
564 __tablename__ = "agent_memory"
566 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
568 role = Column(String(32), nullable=False) # system / user / assistant
569 content = Column(Text, nullable=False)
571 created_at = Column(DateTime, default=aware_utcnow)
574# -- Conversation --
575class Conversation(
576 OwnableMixin.LLMArtifact, OwnableMixin.Resource, DateMixin.Created, Base
577):
578 __tablename__ = "conversations"
580 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
582 total_input_tokens = Column(
583 Integer,
584 nullable=False,
585 default=0,
586 doc="Sum of system + user tokens",
587 )
589 total_output_tokens = Column(
590 Integer,
591 nullable=False,
592 default=0,
593 doc="Sum of assistant tokens",
594 )
596 total_tokens = Column(
597 Integer,
598 nullable=False,
599 default=0,
600 doc="Cached total_input_tokens + total_output_tokens",
601 )
603 #: The workspace it was had in (``app/services/workspace.py``): a
604 #: conversation is its person's, but listed under the workspace whose
605 #: agent it was with. Neither set: their personal workspace.
606 workspace_organisation_id = Column(UUID(as_uuid=True), nullable=True, index=True)
607 workspace_project_id = Column(UUID(as_uuid=True), nullable=True, index=True)
609 agent = relationship(
610 "Agent",
611 back_populates="conversations",
612 )
614 messages = relationship(
615 "ChatMessage",
616 back_populates="conversation",
617 order_by="ChatMessage.sent_at",
618 cascade="all, delete-orphan",
619 lazy="selectin",
620 )
622 __table_args__ = (
623 CheckConstraint(
624 "(ai_model_id IS NOT NULL AND agent_id IS NULL) OR (ai_model_id IS NULL AND agent_id IS NOT NULL)",
625 name="ck_conversation_single_parent",
626 ),
627 ownership_constraint("conversations"),
628 )
631class ChatMessage(FKMixin.Conversation.Child, DateMixin.Sent, Base):
632 __tablename__ = "chat_messages"
634 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
636 role = Column(
637 Enum(MessageEnum.Role, name="message_role_enum"),
638 nullable=False,
639 index=True,
640 )
642 status = Column(
643 Enum(
644 MessageEnum.Status,
645 name="message_status_enum",
646 values_callable=lambda enum_cls: [member.value for member in enum_cls],
647 ),
648 nullable=False,
649 server_default=MessageEnum.Status.COMPLETED.value,
650 doc="Outcome of this turn: completed, blocked by a policy rule, or "
651 "errored — lets a failed/blocked exchange still be recorded for "
652 "History/Activity instead of being silently dropped.",
653 )
655 content = Column(
656 Text,
657 nullable=False,
658 )
660 token_count = Column(
661 Integer,
662 nullable=False,
663 doc="Token count for this message only",
664 )
666 trace = Column(
667 JSON,
668 nullable=True,
669 doc="Execution trace for assistant messages (graph_plan/node_start/node_end/tool_call events)",
670 )
672 meta = Column(
673 JSON,
674 nullable=True,
675 doc="Request/response metadata: token_count, temperature, output_format, output_schema",
676 )
678 #: The governed turn this message was part of
679 #: (``rule_engine.new_invocation_id``), on the user's message and the
680 #: answer alike — the id the usage ledger, the review queue, the
681 #: governance activity log and svc-ai's traces carry for the same turn,
682 #: and so the key of the answer's decision record. Null on system
683 #: messages and on turns stored before migration 91 that no rule ran on.
684 invocation_id = Column(UUID(as_uuid=True), nullable=True, index=True)
686 conversation = relationship(
687 "Conversation",
688 back_populates="messages",
689 )
691 segments = relationship(
692 "ChatMessageSegment",
693 back_populates="message",
694 order_by="ChatMessageSegment.sequence",
695 cascade="all, delete-orphan",
696 lazy="selectin",
697 )
700class ChatMessageSegment(Base):
701 """Per-worker output segment for multi-agent skill executions."""
703 __tablename__ = "chat_message_segments"
705 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
707 message_id = Column(
708 UUID(as_uuid=True),
709 ForeignKey("chat_messages.id", ondelete="CASCADE"),
710 nullable=False,
711 index=True,
712 )
714 worker_slug = Column(String(255), nullable=False)
715 content = Column(Text, nullable=False)
716 sequence = Column(Integer, nullable=False, doc="Execution order within the message")
718 message = relationship("ChatMessage", back_populates="segments")
721# -- Knowledge --
724class Knowledge(
725 OwnableMixin.Resource,
726 SystemMixin,
727 GenerationMixin.Provenance,
728 DateMixin.Created,
729 Base,
730):
731 __tablename__ = "knowledge"
733 # Excluded from resource-version snapshots — may hold credentials.
734 AUDIT_EXCLUDED_FIELDS = {"source_config"}
736 #: Source types whose ``source_config`` holds no secrets and so belongs in
737 #: the edit history: a website's URLs and crawl settings are exactly what
738 #: an audit of "what could this agent read" needs to see change.
739 AUDITABLE_SOURCE_CONFIG_TYPES = frozenset({"web"})
741 @classmethod
742 def audit_excluded_fields_for(cls, resource) -> set[str]:
743 if getattr(resource, "source_type", None) in cls.AUDITABLE_SOURCE_CONFIG_TYPES:
744 return set()
745 return cls.AUDIT_EXCLUDED_FIELDS
747 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
749 name = Column(String(255), nullable=False)
750 description = Column(Text)
752 source_type = Column(String(50), nullable=False) # file, web, db, api
753 source_config = Column(JSON, nullable=False) # urls, paths, creds
755 __table_args__ = (
756 UniqueConstraint(
757 "owner_user_id",
758 "owner_organisation_id",
759 "owner_project_id",
760 "name",
761 name="uq_owner_knowledge_name",
762 ),
763 ownership_constraint("knowledge", allow_system=True),
764 )
767class KnowledgeDocument(FKMixin.Knowledge.Child, DateMixin.Created, Base):
768 __tablename__ = "knowledge_documents"
770 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
772 # Filename for an upload; the canonical page URL for a website source,
773 # hence the length (migration 65).
774 source_id = Column(String(2048), nullable=False)
775 folder_path = Column(String(500), nullable=False, server_default="", index=True)
776 document_metadata = Column(JSON, nullable=True)
778 # Every per-source figure reads a source's documents (migration 111):
779 # without it, each was a scan of every source's.
780 __table_args__ = (Index("ix_knowledge_documents_knowledge_id", "knowledge_id"),)
783class KnowledgeCrawl(FKMixin.Knowledge.Child, DateMixin.Created, Base):
784 """One crawl of a website knowledge source — scheduled, manual, or the
785 first one after its URLs were set.
787 At most one per source is ``running`` at a time, enforced by a partial
788 unique index rather than a check-then-insert: the scheduler and a
789 "Refresh now" click can race, and only the database can settle it.
790 """
792 __tablename__ = "knowledge_crawls"
794 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
796 #: ``web_crawl.Trigger`` — a string, as the vocabulary lives in code.
797 trigger = Column(String(16), nullable=False)
798 #: ``web_crawl.CrawlStatus``.
799 status = Column(String(16), nullable=False)
800 actor_user_id = Column(
801 UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True
802 )
803 started_at = Column(DateTime, nullable=False, default=aware_utcnow)
804 finished_at = Column(DateTime, nullable=True)
806 pages_fetched = Column(Integer, nullable=False, default=0, server_default="0")
807 pages_new = Column(Integer, nullable=False, default=0, server_default="0")
808 pages_changed = Column(Integer, nullable=False, default=0, server_default="0")
809 pages_unchanged = Column(Integer, nullable=False, default=0, server_default="0")
810 pages_failed = Column(Integer, nullable=False, default=0, server_default="0")
811 pages_gone = Column(Integer, nullable=False, default=0, server_default="0")
812 # Pages removed because they aged out of the source's ``max_age_days``.
813 pages_expired = Column(Integer, nullable=False, default=0, server_default="0")
814 # What the crawl's embeddings cost, as svc-ai measured it — the only
815 # record of a built-in source's crawl cost, which no user's ledger holds.
816 usage = Column(JSON, nullable=True)
817 #: Why the crawl stopped short, if it did — a page limit, or a failure.
818 note = Column(Text, nullable=True)
820 __table_args__ = (
821 Index("ix_knowledge_crawls_knowledge_started", "knowledge_id", "started_at"),
822 Index(
823 "uq_knowledge_crawls_one_running",
824 "knowledge_id",
825 unique=True,
826 postgresql_where=text("status = 'running'"),
827 ),
828 )
831class KnowledgePageVersion(FKMixin.Knowledge.Child, DateMixin.Created, Base):
832 """One snapshot of one page of a website source.
834 Written only when the page's extracted text changes, so the versions of a
835 page are exactly the moments it said something different. Immutable: the
836 audit trail of what an agent could have read, and when. Only the newest
837 is indexed for retrieval; the rest are kept for the record.
838 """
840 __tablename__ = "knowledge_page_versions"
842 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
843 document_id = Column(
844 UUID(as_uuid=True),
845 ForeignKey("knowledge_documents.id", ondelete="CASCADE"),
846 nullable=False,
847 )
848 # SET NULL: a crawl row is bookkeeping; the snapshot is the record.
849 crawl_id = Column(
850 UUID(as_uuid=True),
851 ForeignKey("knowledge_crawls.id", ondelete="SET NULL"),
852 nullable=True,
853 )
854 version_number = Column(Integer, nullable=False)
856 url = Column(String(2048), nullable=False)
857 title = Column(String(1024), nullable=True)
858 content_hash = Column(String(64), nullable=False)
859 http_status = Column(Integer, nullable=True)
860 etag = Column(String(512), nullable=True)
861 last_modified = Column(String(128), nullable=True)
862 fetched_at = Column(DateTime, nullable=False, default=aware_utcnow)
864 #: MinIO objects: the extracted markdown (what was indexed) and the raw
865 #: HTML as served (what the site actually said). HTML is absent for
866 #: documents such as PDFs, whose text is all that is kept.
867 markdown_object = Column(String(1024), nullable=False)
868 html_object = Column(String(1024), nullable=True)
869 size_bytes = Column(Integer, nullable=False, default=0, server_default="0")
871 __table_args__ = (
872 UniqueConstraint(
873 "document_id", "version_number", name="uq_knowledge_page_version"
874 ),
875 Index("ix_knowledge_page_versions_document", "document_id"),
876 )
879class KnowledgeRepository(
880 OwnableMixin.Resource,
881 SystemMixin,
882 GenerationMixin.Provenance,
883 DateMixin.Created,
884 Base,
885):
886 """A named collection of knowledge bases (sources).
888 Repositories let users logically group sources of different kinds
889 (files, graphs, web, databases, APIs) and attach the whole collection
890 to an agent instead of granting each source individually.
891 """
893 __tablename__ = "knowledge_repositories"
895 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
897 name = Column(String(255), nullable=False)
898 description = Column(Text)
900 # Lucide icon name and a tailwind-ish accent key, both chosen in the UI.
901 # Same presentation contract as Dashboard and Agent: unset means the
902 # surface falls back to its default glyph and a neutral tone.
903 icon = Column(String(64), nullable=True)
904 accent = Column(String(32), nullable=True)
906 # What kind of knowledge it holds, which decides how an agent uses it: a
907 # key from ``app/util/knowledge_categories.py``, sent to svc-ai with each
908 # of its knowledge bases. A source belongs to repositories of one
909 # category only (``services/knowledge/repositories.require_one_category``),
910 # so each knowledge base reaches an agent as exactly one. ``domain`` is
911 # how every repository was used before categories existed.
912 category = Column(
913 String(16),
914 nullable=False,
915 default=knowledge_categories.DEFAULT.value,
916 server_default=knowledge_categories.DEFAULT.value,
917 )
919 members = relationship(
920 "RepositoryKnowledge",
921 back_populates="repository",
922 cascade="all, delete-orphan",
923 )
925 __table_args__ = (
926 UniqueConstraint(
927 "owner_user_id",
928 "owner_organisation_id",
929 "owner_project_id",
930 "name",
931 name="uq_owner_knowledge_repository_name",
932 ),
933 ownership_constraint("knowledge_repositories", allow_system=True),
934 )
937class RepositoryKnowledge(Base):
938 """Junction: a knowledge base that belongs to a repository."""
940 __tablename__ = "repository_knowledge"
942 repository_id = Column(
943 UUID(as_uuid=True),
944 ForeignKey("knowledge_repositories.id", ondelete="CASCADE"),
945 primary_key=True,
946 nullable=False,
947 )
948 knowledge_id = Column(
949 UUID(as_uuid=True),
950 ForeignKey("knowledge.id", ondelete="CASCADE"),
951 primary_key=True,
952 nullable=False,
953 )
955 repository = relationship("KnowledgeRepository", back_populates="members")
956 knowledge = relationship("Knowledge")
958 # The primary key leads with the repository; "which repositories hold
959 # this source" needs its own (migration 111).
960 __table_args__ = (Index("ix_repository_knowledge_knowledge_id", "knowledge_id"),)
963class AgentRepository(Base):
964 """Junction: a knowledge repository granted to an agent for retrieval.
966 At inference time the repository expands to its member knowledge bases,
967 so agents can be granted a whole collection in one attachment.
968 """
970 __tablename__ = "agent_repositories"
972 agent_id = Column(
973 UUID(as_uuid=True),
974 ForeignKey("agents.id", ondelete="CASCADE"),
975 primary_key=True,
976 nullable=False,
977 )
978 repository_id = Column(
979 UUID(as_uuid=True),
980 ForeignKey("knowledge_repositories.id", ondelete="CASCADE"),
981 primary_key=True,
982 nullable=False,
983 )
984 # Per-agent overrides applied to every member KB (e.g. top_k, depth)
985 config = Column(JSON, nullable=True)
987 agent = relationship("Agent")
988 repository = relationship("KnowledgeRepository")
990 # The primary key leads with the agent; "which agents hold this
991 # repository" needs its own (migration 111).
992 __table_args__ = (Index("ix_agent_repositories_repository_id", "repository_id"),)
995class KnowledgeCitation(Base):
996 """One knowledge source an answer cited — the record of *use*.
998 A grant says what an agent may retrieve from (reach); this says what an
999 answer a person received actually cited, so a source's page can say how
1000 often it is used, by which agents, and which of its documents
1001 (``app/services/knowledge/citations.py``, ``docs/guides/knowledge.md``).
1002 Written once, when the answer is stored, from exactly the sources it
1003 stores (``meta.cited_sources``): a withheld, blocked or failed answer
1004 cites nothing and writes nothing. Migration 110 backfilled the answers
1005 stored before it whose documents name their source.
1007 Not a user-creatable resource: nothing edits these rows, so they carry
1008 no ``ResourceVersion`` history and no ownership constraint. Stamped with
1009 the workspace the conversation was had in exactly as the usage ledger is
1010 (``Workspace.ledger_stamp``), so ``Workspace.stamped`` reads it.
1012 The answer's own row: deleting the conversation (or the message) deletes
1013 its citations, and counts are of answers on record. Deleting the source
1014 deletes them too; a document deleted since leaves its row, unnamed.
1015 """
1017 __tablename__ = "knowledge_citations"
1019 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
1021 message_id = Column(
1022 UUID(as_uuid=True),
1023 ForeignKey("chat_messages.id", ondelete="CASCADE"),
1024 nullable=False,
1025 index=True,
1026 )
1027 #: The governed turn (``chat_messages.invocation_id``): the key of the
1028 #: answer's decision record.
1029 invocation_id = Column(UUID(as_uuid=True), nullable=True, index=True)
1030 knowledge_id = Column(
1031 UUID(as_uuid=True),
1032 ForeignKey("knowledge.id", ondelete="CASCADE"),
1033 nullable=False,
1034 )
1035 #: The document or page cited; null for a source cited whole (a graph's
1036 #: facts) or a document deleted since.
1037 document_id = Column(
1038 UUID(as_uuid=True),
1039 ForeignKey("knowledge_documents.id", ondelete="SET NULL"),
1040 nullable=True,
1041 index=True,
1042 )
1043 #: The agent that answered; null once it is deleted.
1044 agent_id = Column(
1045 UUID(as_uuid=True),
1046 ForeignKey("agents.id", ondelete="SET NULL"),
1047 nullable=True,
1048 )
1049 #: Who asked — the conversation's person. No FK, as on the ledger.
1050 owner_user_id = Column(UUID(as_uuid=True), nullable=True, index=True)
1051 owner_organisation_id = Column(UUID(as_uuid=True), nullable=True)
1052 owner_project_id = Column(UUID(as_uuid=True), nullable=True)
1053 workspace_user_id = Column(UUID(as_uuid=True), nullable=True)
1054 #: How it was cited: the retrieval tool or citation kind svc-ai named.
1055 tool = Column(String(32), nullable=True)
1056 #: When the answer was given (its ``sent_at``).
1057 cited_at = Column(DateTime, nullable=False, default=aware_utcnow)
1059 __table_args__ = (
1060 # An answer cites a document once. Partial, and only for documents:
1061 # a document deleted since leaves its row with no document, and two
1062 # such rows of one answer and source must not refuse the deletion.
1063 # A source cited whole is recorded once per answer by the writer,
1064 # which writes each answer's rows once; counts are of distinct
1065 # answers either way.
1066 Index(
1067 "uq_knowledge_citations_document",
1068 "message_id",
1069 "knowledge_id",
1070 "document_id",
1071 unique=True,
1072 postgresql_where=text("document_id IS NOT NULL"),
1073 ),
1074 Index("ix_knowledge_citations_knowledge_cited", "knowledge_id", "cited_at"),
1075 Index("ix_knowledge_citations_agent_cited", "agent_id", "cited_at"),
1076 Index(
1077 "ix_knowledge_citations_ws_org_cited",
1078 "owner_organisation_id",
1079 "cited_at",
1080 ),
1081 Index(
1082 "ix_knowledge_citations_ws_project_cited", "owner_project_id", "cited_at"
1083 ),
1084 Index("ix_knowledge_citations_ws_user_cited", "workspace_user_id", "cited_at"),
1085 )
1088class KnowledgeTurn(Base):
1089 """One answered turn of an agent with knowledge: what it asked of that
1090 knowledge, and what the knowledge lacked — the retrieval record.
1092 The citations record says which sources an answer cited (*use*); this
1093 says what a turn's knowledge gave and failed to give: a search that kept
1094 nothing that bore on the request, a gap the quality check named that the
1095 knowledge did not hold, a file the person named that no source has, or
1096 an answer the web gave while the knowledge was not searched (its cited
1097 web hosts). What says which knowledge to add
1098 (``app/services/knowledge/retrievals.py``, ``docs/guides/knowledge.md``).
1099 Each source's part is a :class:`KnowledgeRetrieval`.
1101 Written once, when the answer is stored, from svc-ai's report
1102 (``app/util/knowledge_report.py``). The person's words in it (the
1103 request as searched, the gaps, the files named) are redacted as the
1104 input was, kept for none of a withheld answer, and cleared after
1105 ``KNOWLEDGE_TURN_TEXT_RETENTION_DAYS`` (``KnowledgeTurnRetentionJob``);
1106 the counts stay. Not a user-creatable resource: no history, no
1107 ownership constraint. Stamped as the usage ledger is
1108 (``Workspace.ledger_stamp``). Deleting the answer deletes it.
1109 """
1111 __tablename__ = "knowledge_turns"
1113 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
1114 #: The answer: one record each.
1115 message_id = Column(
1116 UUID(as_uuid=True),
1117 ForeignKey("chat_messages.id", ondelete="CASCADE"),
1118 nullable=False,
1119 )
1120 #: The governed turn: the key of the answer's decision record.
1121 invocation_id = Column(UUID(as_uuid=True), nullable=True, index=True)
1122 agent_id = Column(
1123 UUID(as_uuid=True),
1124 ForeignKey("agents.id", ondelete="SET NULL"),
1125 nullable=True,
1126 )
1127 #: Who asked — the conversation's person. No FK, as on the ledger.
1128 owner_user_id = Column(UUID(as_uuid=True), nullable=True, index=True)
1129 owner_organisation_id = Column(UUID(as_uuid=True), nullable=True)
1130 owner_project_id = Column(UUID(as_uuid=True), nullable=True)
1131 workspace_user_id = Column(UUID(as_uuid=True), nullable=True)
1132 #: The request as retrieval searched for it, redacted; null for a
1133 #: withheld answer, and once its retention has passed.
1134 query = Column(Text, nullable=True)
1135 #: Triage judged that the request needs current information.
1136 live = Column(Boolean, nullable=False, default=False, server_default="false")
1137 #: Triage's grade of the request (``prompts.TaskComplexity``), if any.
1138 complexity = Column(String(16), nullable=True)
1139 #: The input profile of the turn's knowledge mix (svc-ai
1140 #: ``knowledge.mix.PROFILES``: ``lookup``, ``current`` …), if the turn
1141 #: recorded one: which kinds of knowledge the request searched, and why.
1142 profile = Column(String(24), nullable=True)
1143 #: The knowledge was searched (by retrieval, or the agent's own tools).
1144 searched = Column(Boolean, nullable=False, default=False, server_default="false")
1145 #: The judge ruled out everything the search found.
1146 nothing_relevant = Column(
1147 Boolean, nullable=False, default=False, server_default="false"
1148 )
1149 #: Searched and did not serve the request
1150 #: (``KnowledgeReport.came_up_short``): what a recommendation counts.
1151 came_up_short = Column(
1152 Boolean, nullable=False, default=False, server_default="false"
1153 )
1154 #: What the quality check found missing that the knowledge did not hold,
1155 #: and the files named that no source has: redacted; null as ``query``.
1156 #: ``none_as_null``: None is SQL NULL, never JSON ``null``, so a cleared
1157 #: record reads as cleared (``IS NULL``).
1158 gaps = Column(JSON(none_as_null=True), nullable=True)
1159 unresolved = Column(JSON(none_as_null=True), nullable=True)
1160 #: The hosts of the web pages the answer cited (from its stored
1161 #: sources, so none for a withheld answer).
1162 web_hosts = Column(JSON(none_as_null=True), nullable=True)
1163 #: The knowledge bases this turn did not search, by id.
1164 scoped_out = Column(JSON(none_as_null=True), nullable=True)
1165 #: When the answer was given (its ``sent_at``).
1166 asked_at = Column(DateTime, nullable=False, default=aware_utcnow)
1168 sources = relationship(
1169 "KnowledgeRetrieval", back_populates="turn", cascade="all, delete-orphan"
1170 )
1172 __table_args__ = (
1173 UniqueConstraint("message_id", name="uq_knowledge_turns_message"),
1174 Index("ix_knowledge_turns_agent_asked", "agent_id", "asked_at"),
1175 Index("ix_knowledge_turns_ws_org_asked", "owner_organisation_id", "asked_at"),
1176 Index("ix_knowledge_turns_ws_project_asked", "owner_project_id", "asked_at"),
1177 Index("ix_knowledge_turns_ws_user_asked", "workspace_user_id", "asked_at"),
1178 )
1181class KnowledgeRetrieval(Base):
1182 """What one knowledge source gave one turn: passages found, kept for
1183 the agent, ruled out by the relevance judge or left out by the turn's
1184 window, and the agent's own searches of it. Read beside the citations
1185 record, it says what a source is retrieved for and how often that is
1186 used (``app/services/knowledge/stats.py``). Stamped, and deleted, with
1187 its :class:`KnowledgeTurn`; deleting the source deletes it too."""
1189 __tablename__ = "knowledge_retrievals"
1191 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
1192 turn_id = Column(
1193 UUID(as_uuid=True),
1194 ForeignKey("knowledge_turns.id", ondelete="CASCADE"),
1195 nullable=False,
1196 )
1197 knowledge_id = Column(
1198 UUID(as_uuid=True),
1199 ForeignKey("knowledge.id", ondelete="CASCADE"),
1200 nullable=False,
1201 )
1202 agent_id = Column(
1203 UUID(as_uuid=True),
1204 ForeignKey("agents.id", ondelete="SET NULL"),
1205 nullable=True,
1206 )
1207 owner_user_id = Column(UUID(as_uuid=True), nullable=True)
1208 owner_organisation_id = Column(UUID(as_uuid=True), nullable=True)
1209 owner_project_id = Column(UUID(as_uuid=True), nullable=True)
1210 workspace_user_id = Column(UUID(as_uuid=True), nullable=True)
1211 #: Its kind as it was searched (``app/util/knowledge_categories.py``).
1212 category = Column(String(16), nullable=True)
1213 #: Its role in the turn's knowledge mix (svc-ai ``knowledge.mix.Role``:
1214 #: ``primary``, ``supporting`` or ``method``), if the turn recorded one.
1215 role = Column(String(16), nullable=True)
1216 found = Column(Integer, nullable=False, default=0, server_default="0")
1217 kept = Column(Integer, nullable=False, default=0, server_default="0")
1218 ruled_out = Column(Integer, nullable=False, default=0, server_default="0")
1219 out_of_window = Column(Integer, nullable=False, default=0, server_default="0")
1220 tool_searches = Column(Integer, nullable=False, default=0, server_default="0")
1221 asked_at = Column(DateTime, nullable=False, default=aware_utcnow)
1223 turn = relationship("KnowledgeTurn", back_populates="sources")
1225 __table_args__ = (
1226 UniqueConstraint(
1227 "turn_id", "knowledge_id", name="uq_knowledge_retrievals_turn_knowledge"
1228 ),
1229 Index("ix_knowledge_retrievals_knowledge_asked", "knowledge_id", "asked_at"),
1230 Index(
1231 "ix_knowledge_retrievals_ws_org_asked", "owner_organisation_id", "asked_at"
1232 ),
1233 Index(
1234 "ix_knowledge_retrievals_ws_project_asked", "owner_project_id", "asked_at"
1235 ),
1236 Index("ix_knowledge_retrievals_ws_user_asked", "workspace_user_id", "asked_at"),
1237 )
1240class KnowledgeRecommendationDismissal(Base):
1241 """A workspace setting a knowledge recommendation aside: this kind, about
1242 this subject, while its evidence stays as it was
1243 (``app/services/knowledge/recommendations``).
1245 ``fingerprint`` is what the evidence read when it was set aside. A
1246 recommendation whose evidence has moved on (more questions unanswered,
1247 a source's settings changed) has a new one and shows again. One row per
1248 workspace, kind and subject: setting it aside again replaces it.
1250 A source map suggestion is set aside the same way (``map_suggestion``,
1251 the repository and the source as its subject).
1253 Not a resource: no edit history. ``workspace_key`` is the workspace's
1254 key, as on a notification, with no foreign key; ``dismissed_by_user_id``
1255 goes null when its person is deleted.
1256 """
1258 __tablename__ = "knowledge_recommendation_dismissals"
1259 __table_args__ = (
1260 UniqueConstraint(
1261 "workspace_key",
1262 "kind",
1263 "subject",
1264 name="uq_knowledge_recommendation_dismissals_subject",
1265 ),
1266 )
1268 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
1269 #: The workspace it was set aside in (``Workspace.key``).
1270 workspace_key = Column(String(80), nullable=False)
1271 #: The recommendation's kind, a registered key.
1272 kind = Column(String(48), nullable=False)
1273 #: What it was about: an id, a site, or two ids.
1274 subject = Column(String(200), nullable=False)
1275 fingerprint = Column(String(64), nullable=False)
1276 dismissed_by_user_id = Column(
1277 UUID(as_uuid=True),
1278 ForeignKey("users.id", ondelete="SET NULL"),
1279 nullable=True,
1280 index=True,
1281 )
1282 dismissed_at = Column(DateTime, nullable=False, default=aware_utcnow)
1285# -- Skills --
1288class Skill(
1289 OwnableMixin.Resource,
1290 ClonableMixin,
1291 SystemMixin,
1292 GenerationMixin.Provenance,
1293 DateMixin.Created,
1294 Base,
1295):
1296 __tablename__ = "skills"
1298 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
1300 name = Column(String(255), nullable=False)
1301 description = Column(Text)
1302 tags = Column(JSON, nullable=False, default=list)
1304 # AgentGraphConfig stored as JSON — defines the subagent graph workflow
1305 graph_definition = Column(JSON, nullable=False)
1307 __table_args__ = (
1308 UniqueConstraint(
1309 "owner_user_id",
1310 "owner_organisation_id",
1311 "owner_project_id",
1312 "name",
1313 name="uq_owner_skill_name",
1314 ),
1315 ownership_constraint("skills", allow_system=True),
1316 )
1319class SkillRun(Base):
1320 """One standalone run of a skill — a skill used as a structured workflow.
1322 A skill used to be reachable only as the body of an agent turn, where its
1323 result is a chat message. Run on its own, it takes typed inputs and
1324 produces typed outputs, and this row is the record of one such run: what
1325 was asked, under which revision, what each node did and what came back.
1327 Written ``running`` before the work is handed to a worker, and finished
1328 in place. Immutable after that — a record of something that happened, not
1329 a resource anyone edits — so it has no version trail of its own; the
1330 skill revision it ran under is ``skill_version``.
1332 ``skill_id`` is ``SET NULL`` and the name is denormalised: a run is most
1333 worth reading when somebody is asking what a since-deleted skill did.
1334 Runs belong to the user who started them, as conversations do — a shared
1335 skill is shared, the inputs somebody gave it are not.
1336 """
1338 __tablename__ = "skill_runs"
1340 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
1342 skill_id = Column(
1343 UUID(as_uuid=True), ForeignKey("skills.id", ondelete="SET NULL"), nullable=True
1344 )
1345 skill_name = Column(String(255), nullable=False)
1346 #: ``ResourceVersion.version`` of the skill when the run started — the
1347 #: graph it actually ran, diffable against today's.
1348 skill_version = Column(Integer, nullable=True)
1349 user_id = Column(
1350 UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False
1351 )
1352 #: The workspace the run was started in (``app/services/workspace.py``) —
1353 #: whose rules govern it and whose spend it is. Neither set: the user's
1354 #: personal workspace.
1355 workspace_organisation_id = Column(UUID(as_uuid=True), nullable=True)
1356 workspace_project_id = Column(UUID(as_uuid=True), nullable=True)
1358 #: ``SkillRunEnum.Status``, stored as a string.
1359 status = Column(String(16), nullable=False)
1361 #: What the user typed, if anything. A skill with a form needs no prompt.
1362 prompt = Column(Text, nullable=True)
1363 #: The task text svc-ai was given, after policy rules ran over it.
1364 task = Column(Text, nullable=True)
1365 #: Form values, validated and coerced against the run schema, after
1366 #: policy redaction.
1367 inputs = Column(JSON, nullable=False, default=dict)
1369 #: The final answer (after audit redaction).
1370 output = Column(Text, nullable=True)
1371 #: The skill's declared ``interface.outputs``, projected from final state.
1372 outputs = Column(JSON, nullable=True)
1373 #: Every user-visible state variable at the end of the run.
1374 state = Column(JSON, nullable=True)
1375 #: What each node did, in order — see ``services/skill_runs/steps.py``.
1376 steps = Column(JSON, nullable=True)
1377 citations = Column(JSON, nullable=True)
1378 #: Policy and audit trace frames, both phases (``build_turn_rule_trace``).
1379 rule_trace = Column(JSON, nullable=True)
1380 #: Things the reader should know that are not failures.
1381 warnings = Column(JSON, nullable=True)
1382 error = Column(Text, nullable=True)
1384 input_tokens = Column(Integer, nullable=False, default=0, server_default="0")
1385 output_tokens = Column(Integer, nullable=False, default=0, server_default="0")
1386 latency_ms = Column(Integer, nullable=True)
1387 #: What svc-ai measured across every segment of the run (a run that
1388 #: paused and resumed is several). None when nothing could be priced.
1389 cost_usd = Column(Numeric(precision=14, scale=8), nullable=True)
1390 llm_calls = Column(Integer, nullable=False, default=0, server_default="0")
1391 unpriced_calls = Column(Integer, nullable=False, default=0, server_default="0")
1392 #: Per-model rows: provider, model, calls, tokens, cost.
1393 cost_detail = Column(JSON, nullable=True)
1394 #: While ``awaiting_input``: what the run paused on — the kind
1395 #: (clarification or approval), the questions or the work to approve, and
1396 #: svc-ai's ``thread_id`` to resume it. Kept afterwards as the record of
1397 #: what was asked; the answer is in ``responses``.
1398 interrupt = Column(JSON, nullable=True)
1399 #: Every answer given to a pause, in order: kind, answers / approval,
1400 #: feedback, when and by whom.
1401 responses = Column(JSON, nullable=True)
1402 #: Shared with this run's ``governance_events``, ledger rows and svc-ai's
1403 #: traces (see ``ChatMessage.invocation_id``). A UUID like theirs since
1404 #: migration 91; it was text.
1405 invocation_id = Column(UUID(as_uuid=True), nullable=True, index=True)
1407 started_at = Column(DateTime, nullable=False, default=aware_utcnow)
1408 finished_at = Column(DateTime, nullable=True)
1410 __table_args__ = (
1411 Index("ix_skill_runs_skill_user_started", "skill_id", "user_id", "started_at"),
1412 )
1415# -- Tools --
1418# -- Custom Workers --
1421class CustomWorker(
1422 OwnableMixin.Resource, GenerationMixin.Provenance, DateMixin.Created, Base
1423):
1424 """A user-built worker agent — the atomic reasoning unit for skill graphs.
1426 The contract is deliberately small: name + prompt, optionally cloning a
1427 builtin (``base_worker``), overriding the model, toggling the general
1428 toolset, and attaching MCP servers. On create the worker is registered
1429 in svc-ai's WorkerAgentDefinition registry under ``definition_name`` so
1430 it is referencable as a skill-graph ``agent_name`` like any builtin.
1431 """
1433 __tablename__ = "custom_workers"
1435 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
1437 name = Column(String(255), nullable=False)
1438 description = Column(Text, nullable=True)
1440 # Name of the AgentDefinition this worker clones; null = built from scratch
1441 base_worker = Column(String(255), nullable=True)
1442 role = Column(String(100), nullable=True)
1443 system_prompt = Column(Text, nullable=True)
1444 tags = Column(JSON, nullable=True)
1446 # Optional model override: {provider, model, temperature, max_tokens}
1447 model_overrides = Column(JSON, nullable=True)
1449 # Single toggle for the full general toolset (per-tool selection is
1450 # deliberately not part of the worker contract)
1451 tools_enabled = Column(Boolean, nullable=False, default=True)
1453 # MCPServer row UUIDs (as strings) whose tools this worker loads
1454 mcp_server_ids = Column(JSON, nullable=False, default=list)
1456 # Typed interface (skill graph schema v3). Each entry is a FieldSpec
1457 # {name, type, description, required, default, values, items}.
1458 # input_schema — values a skill node binds into this worker
1459 # output_schema — when non-empty the worker returns a schema-validated
1460 # dict, so downstream nodes / conditional edges can
1461 # address single fields ({node_id.field}).
1462 input_schema = Column(JSON, nullable=False, default=list)
1463 output_schema = Column(JSON, nullable=False, default=list)
1465 # Registered name in svc-ai's WorkerAgentDefinition registry
1466 definition_name = Column(String(255), nullable=True)
1468 __table_args__ = (ownership_constraint("custom_workers"),)
1471# -- MCP Servers --
1474class MCPServer(OwnableMixin.Resource, DateMixin.Created, Base):
1475 """User-configured MCP (Model Context Protocol) server connection."""
1477 __tablename__ = "mcp_servers"
1479 # Excluded from resource-version snapshots — may hold credentials.
1480 AUDIT_EXCLUDED_FIELDS = {"connection_config"}
1482 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
1484 name = Column(String(255), nullable=False)
1485 description = Column(Text, nullable=True)
1487 # Reference to a built-in template key (e.g. "github", "filesystem"); null = fully custom
1488 template_key = Column(String(100), nullable=True)
1490 # "stdio" | "http" | "sse"
1491 connection_type = Column(String(20), nullable=False)
1493 # Stores command/args/env for stdio, or url/headers for http/sse
1494 connection_config = Column(JSON, nullable=False, default=dict)
1496 # Cached list of tool names discovered from the server (nullable until first probe)
1497 tools_cache = Column(JSON, nullable=True)
1499 is_active = Column(Boolean, default=True, nullable=False)
1501 __table_args__ = (
1502 UniqueConstraint(
1503 "owner_user_id",
1504 "owner_organisation_id",
1505 "owner_project_id",
1506 "name",
1507 name="uq_owner_mcp_server_name",
1508 ),
1509 ownership_constraint("mcp_servers"),
1510 )
1513# -- Toolkits --
1516class Toolkit(
1517 OwnableMixin.Resource, GenerationMixin.Provenance, DateMixin.Created, Base
1518):
1519 """A named collection of MCP servers.
1521 Toolkits let users group an agent's MCP servers together and attach the
1522 whole bundle to an agent in one step — the same pattern Skillset uses
1523 for skills, and KnowledgeRepository uses for knowledge bases. This is
1524 the sole mechanism for granting an MCP server to an agent — there is no
1525 direct agent_mcp_servers grant.
1527 Built-in tools are deliberately not part of this: they are platform
1528 capabilities bound to every agent by svc-ai, not grants to administer.
1529 A toolkit that could also list them was an indirection whose entries
1530 never reached an invocation.
1531 """
1533 __tablename__ = "toolkits"
1535 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
1537 name = Column(String(255), nullable=False)
1538 description = Column(Text)
1540 mcp_servers = relationship(
1541 "ToolkitMCPServer", back_populates="toolkit", cascade="all, delete-orphan"
1542 )
1544 __table_args__ = (
1545 UniqueConstraint(
1546 "owner_user_id",
1547 "owner_organisation_id",
1548 "owner_project_id",
1549 "name",
1550 name="uq_owner_toolkit_name",
1551 ),
1552 ownership_constraint("toolkits"),
1553 )
1556class ToolkitMCPServer(Base):
1557 """Junction: an MCP server that belongs to a toolkit."""
1559 __tablename__ = "toolkit_mcp_servers"
1561 toolkit_id = Column(
1562 UUID(as_uuid=True),
1563 ForeignKey("toolkits.id", ondelete="CASCADE"),
1564 primary_key=True,
1565 nullable=False,
1566 )
1567 mcp_server_id = Column(
1568 UUID(as_uuid=True),
1569 ForeignKey("mcp_servers.id", ondelete="CASCADE"),
1570 primary_key=True,
1571 nullable=False,
1572 )
1574 toolkit = relationship("Toolkit", back_populates="mcp_servers")
1575 mcp_server = relationship("MCPServer")
1578class AgentToolkit(Base):
1579 """Junction: a toolkit granted to an agent.
1581 At inference time the toolkit expands to its member tools and MCP
1582 servers — the sole path for either to reach an agent.
1583 """
1585 __tablename__ = "agent_toolkits"
1587 agent_id = Column(
1588 UUID(as_uuid=True),
1589 ForeignKey("agents.id", ondelete="CASCADE"),
1590 primary_key=True,
1591 nullable=False,
1592 )
1593 toolkit_id = Column(
1594 UUID(as_uuid=True),
1595 ForeignKey("toolkits.id", ondelete="CASCADE"),
1596 primary_key=True,
1597 nullable=False,
1598 )
1599 # Per-agent overrides applied to every member of the toolkit
1600 config = Column(JSON, nullable=True)
1602 agent = relationship("Agent")
1603 toolkit = relationship("Toolkit")
1606# -- Skillsets --
1609class Skillset(
1610 OwnableMixin.Resource,
1611 ClonableMixin,
1612 SystemMixin,
1613 GenerationMixin.Provenance,
1614 DateMixin.Created,
1615 Base,
1616):
1617 """A named collection of skills.
1619 Skillsets let users group an agent's skills together and attach the
1620 whole bundle to an agent in one step — the same pattern
1621 KnowledgeRepository uses for knowledge bases, and Toolkit uses for
1622 tools/MCP servers. This is the sole mechanism for granting a skill to
1623 an agent — there is no direct agent_skills grant. Workers are
1624 deliberately not a member type here: a worker isn't granted to an agent
1625 directly, it's a building block a skill's graph references by name.
1626 """
1628 __tablename__ = "skillsets"
1630 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
1632 name = Column(String(255), nullable=False)
1633 description = Column(Text)
1635 skills = relationship(
1636 "SkillsetSkill", back_populates="skillset", cascade="all, delete-orphan"
1637 )
1639 __table_args__ = (
1640 UniqueConstraint(
1641 "owner_user_id",
1642 "owner_organisation_id",
1643 "owner_project_id",
1644 "name",
1645 name="uq_owner_skillset_name",
1646 ),
1647 ownership_constraint("skillsets", allow_system=True),
1648 )
1651class SkillsetSkill(Base):
1652 """Junction: a skill that belongs to a skillset."""
1654 __tablename__ = "skillset_skills"
1656 skillset_id = Column(
1657 UUID(as_uuid=True),
1658 ForeignKey("skillsets.id", ondelete="CASCADE"),
1659 primary_key=True,
1660 nullable=False,
1661 )
1662 skill_id = Column(
1663 UUID(as_uuid=True),
1664 ForeignKey("skills.id", ondelete="CASCADE"),
1665 primary_key=True,
1666 nullable=False,
1667 )
1669 skillset = relationship("Skillset", back_populates="skills")
1670 skill = relationship("Skill")
1673class AgentSkillset(Base):
1674 """Junction: a skillset granted to an agent.
1676 At inference time the skillset expands to its member skills — the sole
1677 path for a skill to reach an agent.
1678 """
1680 __tablename__ = "agent_skillsets"
1682 agent_id = Column(
1683 UUID(as_uuid=True),
1684 ForeignKey("agents.id", ondelete="CASCADE"),
1685 primary_key=True,
1686 nullable=False,
1687 )
1688 skillset_id = Column(
1689 UUID(as_uuid=True),
1690 ForeignKey("skillsets.id", ondelete="CASCADE"),
1691 primary_key=True,
1692 nullable=False,
1693 )
1694 # Per-agent overrides applied to every member of the skillset
1695 config = Column(JSON, nullable=True)
1697 agent = relationship("Agent")
1698 skillset = relationship("Skillset")
1701# Industry
1702class ResourceIndustry(DateMixin.Created, Base):
1703 __tablename__ = "resource_industries"
1705 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
1706 name = Column(String(255), unique=True, nullable=False)
1708 agents = relationship(
1709 "Agent", secondary="agent_industries", back_populates="industries"
1710 )
1713agent_industries = Table(
1714 "agent_industries",
1715 Base.metadata,
1716 Column("agent_id", UUID(as_uuid=True), ForeignKey("agents.id", ondelete="CASCADE")),
1717 Column(
1718 "industry_id",
1719 UUID(as_uuid=True),
1720 ForeignKey("resource_industries.id", ondelete="CASCADE"),
1721 ),
1722)
1725# Role
1728class ResourceRole(DateMixin.Created, Base):
1729 __tablename__ = "resource_roles"
1731 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
1732 name = Column(String(255), unique=True, nullable=False)
1734 agents = relationship("Agent", secondary="agent_roles", back_populates="roles")
1737agent_roles = Table(
1738 "agent_roles",
1739 Base.metadata,
1740 Column("agent_id", UUID(as_uuid=True), ForeignKey("agents.id", ondelete="CASCADE")),
1741 Column(
1742 "role_id",
1743 UUID(as_uuid=True),
1744 ForeignKey("resource_roles.id", ondelete="CASCADE"),
1745 ),
1746)
1749# -- Evaluation --
1752class Experiment(
1753 OwnableMixin.Resource,
1754 SystemMixin,
1755 GenerationMixin.Tagged,
1756 DateMixin.Created,
1757 Base,
1758):
1759 """An evaluation: one dataset, one scoring mechanism, one or more variants.
1761 The recipe, not an execution — a run of it is an :class:`ExperimentBatch`.
1762 The three things it names are the three things it owns: *what* is asked
1763 (``dataset_id``), *how* an answer is judged (``scorer``, ``scorer_config``,
1764 ``judge``) and *who* answers (its variants). Nothing else on the platform
1765 decides any of those, which is what makes two runs of one evaluation
1766 comparable and a regression verdict meaningful.
1768 The table keeps its historical name: ``experiment`` is a Postgres enum
1769 label on ``resource_versions`` and cannot be dropped.
1770 """
1772 __tablename__ = "experiments"
1774 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
1776 name = Column(String(255), nullable=False)
1777 description = Column(Text, nullable=True)
1779 status = Column(
1780 Enum(EvaluationEnum.Status, name="evaluation_status_enum"),
1781 nullable=False,
1782 default=EvaluationEnum.Status.draft,
1783 server_default=EvaluationEnum.Status.draft,
1784 )
1786 # The dataset every run of this evaluation asks. RESTRICT rather than
1787 # CASCADE: deleting a dataset must not silently take evaluations and
1788 # their run history with it — the API answers 409 naming them.
1789 dataset_id = Column(
1790 UUID(as_uuid=True),
1791 ForeignKey("test_suites.id", ondelete="RESTRICT"),
1792 nullable=False,
1793 index=True,
1794 )
1796 # How every cell of every run is judged. A column, not a config key: it
1797 # is the evaluation's identity, and a report filters on it.
1798 scorer = Column(
1799 Enum(EvaluationEnum.Scorer, name="evaluation_scorer_enum"),
1800 nullable=False,
1801 default=EvaluationEnum.Scorer.manual,
1802 server_default=EvaluationEnum.Scorer.manual,
1803 )
1804 # The scorer's settings — threshold, criteria, case sensitivity, and
1805 # which of a case's expectations it enforces.
1806 scorer_config = Column(JSON, nullable=True)
1807 # The grading model for the ``llm`` scorer; svc-ai's default when None.
1808 judge = Column(JSON, nullable=True)
1810 # Extension point for what has no column yet: regression tolerances,
1811 # concurrency, the optimiser's state and the promotion log.
1812 config = Column(JSON, nullable=True)
1814 dataset = relationship("TestSuite", back_populates="evaluations")
1815 variants = relationship(
1816 "ExperimentVariant", back_populates="experiment", cascade="all, delete-orphan"
1817 )
1818 runs = relationship(
1819 "ExperimentRun", back_populates="experiment", cascade="all, delete-orphan"
1820 )
1821 batches = relationship(
1822 "ExperimentBatch",
1823 back_populates="experiment",
1824 cascade="all, delete-orphan",
1825 order_by="ExperimentBatch.created_at.desc()",
1826 )
1828 __table_args__ = (
1829 UniqueConstraint(
1830 "owner_user_id",
1831 "owner_organisation_id",
1832 "owner_project_id",
1833 "name",
1834 name="uq_owner_experiment_name",
1835 ),
1836 # A built-in experiment (the platform benchmark, migration 89) has no
1837 # owner, and only a built-in one may.
1838 ownership_constraint("experiments", allow_system=True),
1839 )
1842class ExperimentVariant(DateMixin.Created, Base):
1843 """A named variant (prompt + config) within an experiment."""
1845 __tablename__ = "experiment_variants"
1847 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
1849 experiment_id = Column(
1850 UUID(as_uuid=True),
1851 ForeignKey("experiments.id", ondelete="CASCADE"),
1852 nullable=False,
1853 index=True,
1854 )
1856 name = Column(String(255), nullable=False)
1857 prompt = Column(Text, nullable=True)
1858 config = Column(JSON, nullable=True) # model/agent overrides for this variant
1860 experiment = relationship("Experiment", back_populates="variants")
1861 runs = relationship(
1862 "ExperimentRun", back_populates="variant", cascade="all, delete-orphan"
1863 )
1866class ExperimentRun(RunnableMixin.Run, DateMixin.Created, Base):
1867 """One scored (target, case) cell — of an evaluation or of a dataset run.
1869 This was two tables. ``TestCaseResult`` recorded a dataset run's cell and
1870 this recorded an evaluation's, for the same ``_execute_matrix`` call at
1871 different arity — so per-case regression only ever worked on one of them
1872 and leaderboards, promotion gates and reports only on the other. A user
1873 picked the surface by which feature they wanted rather than by which
1874 question they were asking.
1875 """
1877 __tablename__ = "experiment_runs"
1879 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
1881 # Nullable since the fold: a dataset run belongs to a batch and a suite,
1882 # not to an experiment. The batch is the grouping that always exists.
1883 experiment_id = Column(
1884 UUID(as_uuid=True),
1885 ForeignKey("experiments.id", ondelete="CASCADE"),
1886 nullable=True,
1887 index=True,
1888 )
1889 variant_id = Column(
1890 UUID(as_uuid=True),
1891 ForeignKey("experiment_variants.id", ondelete="SET NULL"),
1892 nullable=True,
1893 index=True,
1894 )
1896 # Groups the runs produced by one execution of the variant x case matrix.
1897 # Without it a re-run is indistinguishable from the original, so scores
1898 # could not be compared between executions.
1899 #
1900 # Still no FK, even though ``experiment_batches`` now exists: batch
1901 # summaries used to live on ``Experiment.config`` capped at the twenty most
1902 # recent, while the runs themselves were never trimmed, so rows predating
1903 # the table legitimately point at a batch whose summary is gone. A
1904 # constraint would reject exactly the historical data it was meant to
1905 # protect.
1906 batch_id = Column(UUID(as_uuid=True), nullable=True, index=True)
1908 # The stored case this cell scored, when it came from a dataset rather than
1909 # from inline cases. A real column rather than a key inside ``input``
1910 # because per-case regression matches on it, and matching on a JSON field
1911 # cannot use an index.
1912 test_case_id = Column(
1913 UUID(as_uuid=True),
1914 ForeignKey("test_cases.id", ondelete="CASCADE"),
1915 nullable=True,
1916 index=True,
1917 )
1919 input = Column(JSON, nullable=True)
1920 output = Column(Text, nullable=True)
1922 score = Column(JSON, nullable=True) # float 0.0–1.0 per scorer
1923 score_reason = Column(Text, nullable=True)
1924 scorer = Column(
1925 Enum(EvaluationEnum.Scorer, name="evaluation_scorer_enum"),
1926 nullable=True,
1927 )
1928 # The scorer's verdict. Distinct from the score: a scorer may grade without
1929 # deciding (``manual``), and a failed invocation is a failure whatever the
1930 # score says.
1931 passed = Column(Boolean, nullable=True)
1933 run_metadata = Column(JSON, nullable=True)
1935 experiment = relationship("Experiment", back_populates="runs")
1936 variant = relationship("ExperimentVariant", back_populates="runs")
1937 test_case = relationship("TestCase", back_populates="results")
1940class ExperimentBatch(RunnableMixin.Run, DateMixin.Created, Base):
1941 """One execution of a (target x case) matrix — the platform's only run row.
1943 An evaluation's batch runs several variants over a dataset; a dataset's own
1944 run is the same thing with one target and no variants. ``TestSuiteRun`` was
1945 that second case in its own table, which is why regression verdicts existed
1946 only there and leaderboards, promotion gates and cross-experiment reporting
1947 only here.
1949 Batches lived on ``Experiment.config['batches']`` as JSON, capped at the
1950 twenty most recent. That was fine for the progress bar it existed to feed
1951 and useless for anything else: a question like "which experiments in this
1952 project scored below 0.7 last month" cannot be asked of a JSON array
1953 embedded in another table's column, so every cross-experiment figure had to
1954 be assembled in Python from rows that had already been loaded.
1956 The display payloads — the full aggregate and the ranked leaderboard —
1957 stay JSON, because nothing filters on them. The figures a report actually
1958 groups, filters and orders by are columns.
1959 """
1961 __tablename__ = "experiment_batches"
1963 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
1965 # The evaluation this is a run of. NULL only for an unsaved Quick try — a
1966 # comparison persisted before the user has decided whether to keep it,
1967 # adopted by an evaluation on save and purged by ``quick_try_retention``
1968 # otherwise. Every read path scopes by evaluation, so an unowned batch is
1969 # invisible until it is adopted.
1970 experiment_id = Column(
1971 UUID(as_uuid=True),
1972 ForeignKey("experiments.id", ondelete="CASCADE"),
1973 nullable=True,
1974 index=True,
1975 )
1976 #: Who started the run — the person its calls are governed and ledgered
1977 #: as when the evaluation belongs to an organisation or project.
1978 started_by_user_id = Column(UUID(as_uuid=True), nullable=True)
1980 # Which dataset was asked, and which revision of it and of the evaluation
1981 # was in force — so a result resolves to the exact configuration that
1982 # produced it, the way an agent turn resolves to an agent version. Soft
1983 # references, like ``batch_id`` on a cell: a run outlives what it ran.
1984 dataset_id = Column(UUID(as_uuid=True), nullable=True)
1985 dataset_version = Column(Integer, nullable=True)
1986 evaluation_version = Column(Integer, nullable=True)
1988 label = Column(String(255), nullable=True)
1990 # -- what was asked for --
1991 # Soft references: a variant can be deleted while the batch that scored it
1992 # stays on record, which is exactly when the record matters.
1993 variant_ids = Column(JSON, nullable=True)
1994 dataset = Column(JSON, nullable=True)
1995 config = Column(JSON, nullable=True) # per-batch scorer/concurrency overrides
1997 # -- progress, while it runs --
1998 completed = Column(Integer, nullable=False, default=0, server_default="0")
1999 total = Column(Integer, nullable=False, default=0, server_default="0")
2001 # -- results --
2002 summary = Column(JSON, nullable=True) # the full aggregate
2003 leaderboard = Column(JSON, nullable=True) # ranked variant rows
2004 error = Column(Text, nullable=True)
2006 # -- the regression verdict --
2007 #
2008 # How this run compared to the last comparable one. The headline is JSON
2009 # because nothing filters on its reasons; the verdict is a column because
2010 # "show me what regressed" is exactly the question a report asks — the same
2011 # split the summary and its reporting columns take.
2012 regression = Column(JSON, nullable=True)
2013 regression_verdict = Column(String(32), nullable=True, index=True)
2014 #: Which revision of each agent this run evaluated, per variant:
2015 #: ``{variant_id: {"agent_id": str, "agent_version": int | None}}``. What
2016 #: lets a result be read as evidence about a version — "has the agent in
2017 #: production been evaluated?" — rather than about an agent in general.
2018 #: NULL on runs recorded before migration 75.
2019 target_versions = Column(JSON, nullable=True)
2021 # -- the reporting columns --
2022 #
2023 # Denormalised out of ``summary`` on purpose. They are nullable because a
2024 # batch has none of them until it finishes, and a cancelled batch may never
2025 # get them at all — a report must be able to tell "scored zero" from "never
2026 # produced a score".
2027 scorer = Column(
2028 Enum(EvaluationEnum.Scorer, name="evaluation_scorer_enum"),
2029 nullable=True,
2030 )
2031 mean_score = Column(Float, nullable=True)
2032 pass_rate = Column(Float, nullable=True)
2033 total_cases = Column(Integer, nullable=True)
2034 errors = Column(Integer, nullable=True)
2035 mean_latency_ms = Column(Integer, nullable=True)
2036 total_tokens = Column(Integer, nullable=True)
2037 duration_ms = Column(Integer, nullable=True)
2039 experiment = relationship("Experiment", back_populates="batches")
2041 __table_args__ = (
2042 # The experiment page asks for "this experiment's batches, newest
2043 # first" on every poll.
2044 Index(
2045 "ix_experiment_batches_experiment_created", "experiment_id", "created_at"
2046 ),
2047 # Reporting asks across experiments over a time window, and almost
2048 # always only about batches that finished.
2049 Index("ix_experiment_batches_status_created", "status", "created_at"),
2050 # A dataset page asks "every run over these cases, whichever
2051 # evaluation made it, newest first".
2052 Index("ix_experiment_batches_dataset_created", "dataset_id", "created_at"),
2053 )
2056class TestSuite(
2057 OwnableMixin.Resource,
2058 ClonableMixin,
2059 GenerationMixin.Tagged,
2060 SystemMixin,
2061 DateMixin.Created,
2062 Base,
2063):
2064 """A dataset: the cases an evaluation asks, and nothing about how.
2066 Data only. It carries no scorer, no target and no runs of its own —
2067 those belong to the evaluations that reference it (``Experiment``), so
2068 the same cases can be graded and re-run by many evaluations and every
2069 one of them says exactly what it did. A web-search prompt set, a refund
2070 tone set, a regression set: each is a dataset.
2072 ``is_system`` marks the platform's **gold datasets** — standard
2073 benchmarks (hallucination, tool use, political neutrality …) every user
2074 can run their own experiments on and copy into a dataset of their own
2075 (``app.services.system_resources.datasets``).
2077 The table keeps its historical name: ``test_suite`` is a Postgres enum
2078 label on ``resource_versions`` and cannot be dropped.
2079 """
2081 __tablename__ = "test_suites"
2083 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
2085 name = Column(String(255), nullable=False)
2086 description = Column(Text, nullable=True)
2088 status = Column(
2089 Enum(EvaluationEnum.Status, name="evaluation_status_enum"),
2090 nullable=False,
2091 default=EvaluationEnum.Status.draft,
2092 server_default=EvaluationEnum.Status.draft,
2093 )
2095 # What every good answer in this dataset must do — "cite the policy
2096 # section", "never promise a refund date" — as ``[{text, gate}]`` items
2097 # (``services/evaluation/criteria.py``). Inherited by each case, which
2098 # adds its own. Criteria are part of the data, never of an experiment's
2099 # scorer: otherwise two experiments could grade the same cases against two
2100 # different ideas of correct, and neither result says so.
2101 criteria = Column(JSON, nullable=True)
2103 # The mean score a model or agent must reach on this dataset to count as
2104 # passing it; None is the platform default (``evidence.pass_mark_of``).
2105 # Not a grading setting — it does not change how any answer is scored,
2106 # only what the dataset's owner asks of a result — so it belongs to the
2107 # data: the bar depends on the use case the cases stand for.
2108 pass_mark = Column(Float, nullable=True)
2110 # Extension point. Grading and targets used to live here and no longer
2111 # do; a dataset that carries settings about how it is judged is a dataset
2112 # that grades the same cases two ways depending on who runs it.
2113 config = Column(JSON, nullable=True)
2115 test_cases = relationship(
2116 "TestCase", back_populates="test_suite", cascade="all, delete-orphan"
2117 )
2118 # Passive on purpose: deleting a dataset with evaluations is refused by
2119 # the API (the FK is RESTRICT), never cascaded.
2120 evaluations = relationship("Experiment", back_populates="dataset")
2122 __table_args__ = (
2123 UniqueConstraint(
2124 "owner_user_id",
2125 "owner_organisation_id",
2126 "owner_project_id",
2127 "name",
2128 name="uq_owner_test_suite_name",
2129 ),
2130 ownership_constraint("test_suites", allow_system=True),
2131 CheckConstraint(
2132 "pass_mark IS NULL OR (pass_mark >= 0 AND pass_mark <= 1)",
2133 name="ck_test_suites_pass_mark_range",
2134 ),
2135 )
2138class TestCase(DateMixin.Created, Base):
2139 """One case of a dataset: a question, and what a correct answer looks like.
2141 A case is the data and its label. The data is the question and the
2142 *situation* it arrives in. The label is everything that says what a good
2143 answer is: the reference answer, criteria in words, graded example
2144 answers, and mechanical checks (format, must / must not contain,
2145 pattern). It never says how strictly to judge (that is the experiment's
2146 scorer) or who answers (that is a variant).
2147 """
2149 __tablename__ = "test_cases"
2151 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
2153 test_suite_id = Column(
2154 UUID(as_uuid=True),
2155 ForeignKey("test_suites.id", ondelete="CASCADE"),
2156 nullable=False,
2157 index=True,
2158 )
2160 name = Column(String(255), nullable=True)
2161 input = Column(JSON, nullable=False) # prompt / structured input
2162 expected_output = Column(Text, nullable=True) # the reference answer
2163 # What a good answer to *this* question must do, as ``[{text, gate}]``
2164 # items — added to the dataset's own criteria, never replacing them.
2165 criteria = Column(JSON, nullable=True)
2166 # What the agent should *do*: ``answer``, ``clarify`` (question back
2167 # rather than guess) or ``decline``. None is "not stated". Graded as a
2168 # must-pass criterion (``criteria.BEHAVIOURS``). A string, not a Postgres
2169 # enum: the vocabulary is a registry in code, and enum labels cannot be
2170 # removed.
2171 expected_behaviour = Column(String(16), nullable=True)
2172 # Answers graded in advance: ``[{"output", "score", "note"}]``. They
2173 # anchor an LLM judge's scale — "this is a 0.3, and why" is steadier
2174 # evidence than any adjective in the criteria.
2175 examples = Column(JSON, nullable=True)
2176 # What correct looks like beyond the reference text: ``format`` (text,
2177 # json, markdown), ``schema``, ``must_contain``, ``must_not_contain``,
2178 # ``pattern``. Scorers read these when their own config is silent.
2179 expectation = Column(JSON, nullable=True)
2180 # The situation the question arrives in: ``history`` (prior turns) and
2181 # ``variables``. Capability — knowledge, tools — is a variant's, never a
2182 # case's, which is why this is not called "context".
2183 situation = Column(JSON, nullable=True)
2184 tags = Column(JSON, nullable=True)
2185 #: The governed turn this case was made from ("Add to dataset" on its
2186 #: decision record), or None for a case written by hand. Provenance, not
2187 #: content: it is not part of a dataset's content version
2188 #: (``dataset_versions.CASE_FIELDS``).
2189 source_invocation_id = Column(UUID(as_uuid=True), nullable=True, index=True)
2191 test_suite = relationship("TestSuite", back_populates="test_cases")
2192 results = relationship(
2193 "ExperimentRun", back_populates="test_case", cascade="all, delete-orphan"
2194 )
2197# -- Simulations --
2200class SimulationWorld(
2201 OwnableMixin.Resource, GenerationMixin.Tagged, DateMixin.Created, Base
2202):
2203 """A game-theoretic simulation environment with defined rules and logic."""
2205 __tablename__ = "simulation_worlds"
2207 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
2209 name = Column(String(255), nullable=False)
2210 description = Column(Text, nullable=True)
2212 status = Column(
2213 Enum(SimulationEnum.Status, name="simulation_status_enum"),
2214 nullable=False,
2215 default=SimulationEnum.Status.draft,
2216 server_default=SimulationEnum.Status.draft,
2217 )
2219 rules = Column(
2220 JSON, nullable=True
2221 ) # game-theoretic rules governing agent interactions
2222 logic = Column(JSON, nullable=True) # world constraints and environment logic
2224 scenarios = relationship(
2225 "SimulationScenario", back_populates="world", cascade="all, delete-orphan"
2226 )
2227 simulations = relationship(
2228 "Simulation", back_populates="world", cascade="all, delete-orphan"
2229 )
2231 __table_args__ = (
2232 UniqueConstraint(
2233 "owner_user_id",
2234 "owner_organisation_id",
2235 "owner_project_id",
2236 "name",
2237 name="uq_owner_simulation_world_name",
2238 ),
2239 ownership_constraint("simulation_worlds"),
2240 )
2243class SimulationScenario(DateMixin.Created, Base):
2244 """A named evaluation scenario within a simulation world."""
2246 __tablename__ = "simulation_scenarios"
2248 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
2250 world_id = Column(
2251 UUID(as_uuid=True),
2252 ForeignKey("simulation_worlds.id", ondelete="CASCADE"),
2253 nullable=False,
2254 index=True,
2255 )
2257 name = Column(String(255), nullable=False)
2258 description = Column(Text, nullable=True)
2260 strategy = Column(
2261 Enum(SimulationEnum.Strategy, name="simulation_strategy_enum"),
2262 nullable=False,
2263 default=SimulationEnum.Strategy.custom,
2264 server_default=SimulationEnum.Strategy.custom,
2265 )
2267 tags = Column(JSON, nullable=True) # list of string tags
2268 config = Column(JSON, nullable=True) # scenario-specific parameters
2270 status = Column(
2271 Enum(SimulationEnum.Status, name="simulation_status_enum"),
2272 nullable=False,
2273 default=SimulationEnum.Status.draft,
2274 server_default=SimulationEnum.Status.draft,
2275 )
2277 world = relationship("SimulationWorld", back_populates="scenarios")
2278 simulations = relationship("Simulation", back_populates="scenario")
2281class UploadedFile(OwnableMixin.Resource, DateMixin.Created, Base):
2282 """A document parsed for chat and kept in a workspace's library, to be
2283 attached again in any chat there.
2285 Owned like any resource, by the workspace it was uploaded in (migration
2286 88): a person's Personal library, or an organisation's or project's,
2287 shared by its members. Who uploaded it is the actor on its ``created``
2288 edit-history version — the uploader of a shared document is not its
2289 owner, and leaving or deleting their account leaves it with the team.
2291 The text stays out of the edit history (``HISTORY_EXCLUDED_FIELDS``): a
2292 deleted document's words go with it. ``content_sha256`` names exactly
2293 which text each version described.
2295 Its text is read after the upload has answered (migration 108): docling
2296 takes minutes on a long PDF, past what the proxy and Cloudflare wait for
2297 one request. ``status`` says how far that got.
2299 The file as uploaded is kept in the object store (migration 109,
2300 ``object_key``), so it can be opened again; one uploaded before then
2301 has its text only.
2302 """
2304 __tablename__ = "uploaded_files"
2306 #: The text, and where the original is stored: plumbing, not something
2307 #: an edit changes.
2308 HISTORY_EXCLUDED_FIELDS = frozenset({"content", "object_key"})
2310 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
2311 name = Column(String(512), nullable=False)
2312 content = Column(Text, nullable=False)
2313 mime_type = Column(String(255), nullable=True)
2314 content_sha256 = Column(String(64), nullable=True)
2315 #: ``UploadEnum.Status``, stored as a string.
2316 status = Column(String(16), nullable=False, server_default="ready")
2317 #: Why no text could be read, when ``failed``. Never an exception's text.
2318 error = Column(Text, nullable=True)
2319 #: Where the original is stored (``uploads.object_key``); null when it
2320 #: was uploaded before originals were kept.
2321 object_key = Column(String(512), nullable=True)
2322 size_bytes = Column(BigInteger, nullable=True)
2324 __table_args__ = (ownership_constraint("uploaded_files"),)
2327class Simulation(RunnableMixin.Run, DateMixin.Created, Base):
2328 """An execution of an agent cluster within a simulation world and scenario."""
2330 __tablename__ = "simulations"
2332 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
2334 world_id = Column(
2335 UUID(as_uuid=True),
2336 ForeignKey("simulation_worlds.id", ondelete="CASCADE"),
2337 nullable=False,
2338 index=True,
2339 )
2340 scenario_id = Column(
2341 UUID(as_uuid=True),
2342 ForeignKey("simulation_scenarios.id", ondelete="SET NULL"),
2343 nullable=True,
2344 index=True,
2345 )
2347 name = Column(String(255), nullable=True)
2348 description = Column(Text, nullable=True)
2350 agent_ids = Column(JSON, nullable=True) # list of agent UUIDs forming the cluster
2351 results = Column(JSON, nullable=True) # aggregated simulation outcomes and metrics
2352 run_metadata = Column(JSON, nullable=True)
2354 world = relationship("SimulationWorld", back_populates="simulations")
2355 scenario = relationship("SimulationScenario", back_populates="simulations")
2358# -- Rules --
2361class Rule(
2362 OwnableMixin.Resource,
2363 ClonableMixin,
2364 GenerationMixin.Provenance,
2365 SystemMixin,
2366 DateMixin.Updated,
2367 Base,
2368):
2369 """
2370 A governance rule — in the Access, Input or Output layer — that controls
2371 LLM behaviour across agents, models, skills, and workers.
2373 ``conditions`` and ``actions`` are stored as JSON arrays of condition/action
2374 blocks to support the visual rule builder without a rigid schema.
2376 Condition block: {"field": str, "operator": str, "value": Any}
2377 Action block: {"type": str, ...params}
2379 A **built-in** rule (``is_system``) governs nobody. The engine loads only
2380 the rules a user owns, so a built-in is a definition users adopt: they
2381 create a rule of their own from it, scoped and tuned as they need, and
2382 that rule records which built-in it was based on and which release of it
2383 (``based_on_rule_id`` / ``based_on_version``).
2384 """
2386 __tablename__ = "rules"
2388 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
2390 name = Column(String(255), nullable=False)
2391 description = Column(Text, nullable=True)
2393 #: Where in a request the rule acts (``app/services/rules/layers.py``).
2394 layer = Column(
2395 Enum(RuleEnum.Layer, name="rule_layer_enum"),
2396 nullable=False,
2397 index=True,
2398 )
2400 # Scope: which resource category this rule applies to
2401 scope_type = Column(
2402 Enum(RuleEnum.Scope, name="rule_scope_enum"),
2403 nullable=False,
2404 default=RuleEnum.Scope.global_,
2405 )
2406 # Optional UUID of the specific scoped resource (agent, model, skill, worker)
2407 scope_id = Column(UUID(as_uuid=True), nullable=True, index=True)
2409 # Condition and action blocks — flexible JSON arrays
2410 conditions = Column(JSON, nullable=False, default=list)
2411 actions = Column(JSON, nullable=False, default=list)
2413 is_active = Column(Boolean, nullable=False, default=True)
2414 priority = Column(Integer, nullable=False, default=0)
2416 # The built-in this rule was created from, and the release of it — the
2417 # built-in's version number then. A copy is independent: later releases
2418 # of the built-in do not reach it, and the version says which one it
2419 # started from. SET NULL, though a built-in is never deleted.
2420 based_on_rule_id = Column(
2421 UUID(as_uuid=True),
2422 ForeignKey("rules.id", ondelete="SET NULL"),
2423 nullable=True,
2424 index=True,
2425 )
2426 based_on_version = Column(Integer, nullable=True)
2428 # Applies in every project of the person or organisation that owns it,
2429 # whether or not the project declares it (``app/services/inheritance.py``).
2430 # Set by a governance editor of the owner; a project's own rule has no
2431 # projects to require it of, and a built-in governs nobody.
2432 required_for_projects = Column(
2433 Boolean, nullable=False, default=False, server_default=text("false")
2434 )
2436 __table_args__ = (
2437 ownership_constraint("rules", allow_system=True),
2438 CheckConstraint(
2439 "NOT required_for_projects OR (owner_project_id IS NULL AND NOT is_system)",
2440 name="ck_rules_required_parent",
2441 ),
2442 Index(
2443 "ix_rules_required_org",
2444 "owner_organisation_id",
2445 postgresql_where=text("required_for_projects"),
2446 ),
2447 Index(
2448 "ix_rules_required_user",
2449 "owner_user_id",
2450 postgresql_where=text("required_for_projects"),
2451 ),
2452 )
2455# -- Workspace inheritance --
2458class WorkspaceInheritance(Base):
2459 """A project's declaration that it inherits from its parent — the
2460 person or organisation that owns it — by reference: one resource
2461 (``resource_id``), or every resource of a kind (``resource_id`` NULL),
2462 future ones included. ``kind`` is a key of
2463 ``app/services/inheritance.py``'s registry.
2465 ``resource_id`` is a soft reference, as ``ResourceVersion``'s is: it
2466 spans several tables, and a declaration whose resource has gone is
2467 inert, because inheriting also requires the parent to own the row.
2468 Declaring or withdrawing is a change to the project, and versions it.
2469 """
2471 __tablename__ = "workspace_inheritance"
2473 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
2474 project_id = Column(
2475 UUID(as_uuid=True),
2476 ForeignKey("projects.id", ondelete="CASCADE"),
2477 nullable=False,
2478 index=True,
2479 )
2480 kind = Column(String(32), nullable=False)
2481 resource_id = Column(UUID(as_uuid=True), nullable=True)
2482 declared_by_user_id = Column(
2483 UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True
2484 )
2485 created_at = Column(DateTime, nullable=False, default=aware_utcnow)
2487 __table_args__ = (
2488 # Two partial indexes, because Postgres treats NULLs as distinct: a
2489 # plain unique (project_id, kind, resource_id) would admit any
2490 # number of whole-kind declarations.
2491 Index(
2492 "uq_ws_inherit_class",
2493 "project_id",
2494 "kind",
2495 unique=True,
2496 postgresql_where=text("resource_id IS NULL"),
2497 ),
2498 Index(
2499 "uq_ws_inherit_instance",
2500 "project_id",
2501 "kind",
2502 "resource_id",
2503 unique=True,
2504 postgresql_where=text("resource_id IS NOT NULL"),
2505 ),
2506 Index("ix_ws_inherit_resource", "kind", "resource_id"),
2507 )
2510# -- Dashboards --
2513class Dashboard(
2514 OwnableMixin.Resource,
2515 ClonableMixin,
2516 GenerationMixin.Tagged,
2517 SystemMixin,
2518 DateMixin.Updated,
2519 Base,
2520):
2521 """A user-composed board of widgets.
2523 Every owner has at most one ``is_home`` dashboard — the board shown by
2524 default. The rest are specialist boards the user creates and orders
2525 themselves. Placement lives on the widgets; a dashboard carries only its
2526 identity and presentation.
2528 A **built-in** board (``is_system``) is one row every user opens. Its
2529 platform tiles fetch the viewer's own data when drawn, so each user sees
2530 their own figures on it; its cached tiles (feeds, generated text) are the
2531 same for everyone, which is why only tiles holding nobody's data may go
2532 on one (``WidgetRenderer.stores_user_content``).
2533 """
2535 __tablename__ = "dashboards"
2537 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
2539 name = Column(String(255), nullable=False)
2540 description = Column(Text, nullable=True)
2542 # Lucide icon name and a tailwind-ish accent key, both chosen in the UI.
2543 icon = Column(String(64), nullable=True)
2544 accent = Column(String(32), nullable=True)
2546 is_home = Column(Boolean, nullable=False, default=False, server_default="false")
2547 position = Column(Integer, nullable=False, default=0, server_default="0")
2549 widgets = relationship(
2550 "DashboardWidget",
2551 back_populates="dashboard",
2552 cascade="all, delete-orphan",
2553 order_by="DashboardWidget.position",
2554 )
2556 __table_args__ = (
2557 # Unique board name, and at most one home board, per owner. Both are
2558 # three partial indexes rather than one composite constraint: SQL
2559 # treats NULLs as distinct, so a UNIQUE over all three owner columns
2560 # never fires for a user-owned row (where the org and project columns
2561 # are both NULL) and would enforce nothing at all.
2562 Index(
2563 "uq_dashboard_name_user",
2564 "owner_user_id",
2565 "name",
2566 unique=True,
2567 postgresql_where=text("owner_user_id IS NOT NULL"),
2568 ),
2569 Index(
2570 "uq_dashboard_name_organisation",
2571 "owner_organisation_id",
2572 "name",
2573 unique=True,
2574 postgresql_where=text("owner_organisation_id IS NOT NULL"),
2575 ),
2576 Index(
2577 "uq_dashboard_name_project",
2578 "owner_project_id",
2579 "name",
2580 unique=True,
2581 postgresql_where=text("owner_project_id IS NOT NULL"),
2582 ),
2583 Index(
2584 "uq_dashboard_home_user",
2585 "owner_user_id",
2586 unique=True,
2587 postgresql_where=text("is_home AND owner_user_id IS NOT NULL"),
2588 ),
2589 Index(
2590 "uq_dashboard_home_organisation",
2591 "owner_organisation_id",
2592 unique=True,
2593 postgresql_where=text("is_home AND owner_organisation_id IS NOT NULL"),
2594 ),
2595 Index(
2596 "uq_dashboard_home_project",
2597 "owner_project_id",
2598 unique=True,
2599 postgresql_where=text("is_home AND owner_project_id IS NOT NULL"),
2600 ),
2601 ownership_constraint("dashboards", allow_system=True),
2602 )
2605class DashboardWidget(DateMixin.Updated, Base):
2606 """One tile on a dashboard.
2608 ``config`` is the per-type payload validated by that type's renderer
2609 (see ``app.services.dashboards.widgets``). Dynamic types additionally use
2610 ``refresh_interval_seconds`` plus the ``cache_*`` columns to hold the last
2611 generated result, so a board loads instantly from cache and regenerates
2612 only once the cached value has aged past its interval.
2613 """
2615 __tablename__ = "dashboard_widgets"
2617 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
2619 dashboard_id = Column(
2620 UUID(as_uuid=True),
2621 ForeignKey("dashboards.id", ondelete="CASCADE"),
2622 nullable=False,
2623 index=True,
2624 )
2626 widget_type = Column(
2627 Enum(DashboardEnum.WidgetType, name="dashboard_widget_type_enum"),
2628 nullable=False,
2629 )
2631 title = Column(String(255), nullable=True)
2632 config = Column(JSON, nullable=False, default=dict)
2634 # Grid placement, in react-grid-layout units.
2635 x = Column(Integer, nullable=False, default=0, server_default="0")
2636 y = Column(Integer, nullable=False, default=0, server_default="0")
2637 w = Column(Integer, nullable=False, default=4, server_default="4")
2638 h = Column(Integer, nullable=False, default=4, server_default="4")
2640 # Ordering fallback for clients that render a list rather than a grid.
2641 position = Column(Integer, nullable=False, default=0, server_default="0")
2643 # -- Dynamic-widget cache -------------------------------------------------
2644 #
2645 # NULL interval means "never auto-refresh"; static types leave all of
2646 # these untouched.
2647 refresh_interval_seconds = Column(Integer, nullable=True)
2649 cache_status = Column(
2650 Enum(DashboardEnum.RefreshStatus, name="dashboard_refresh_status_enum"),
2651 nullable=False,
2652 default=DashboardEnum.RefreshStatus.empty,
2653 server_default=DashboardEnum.RefreshStatus.empty,
2654 )
2655 cache_payload = Column(JSON, nullable=True)
2656 cache_error = Column(Text, nullable=True)
2657 cached_at = Column(DateTime, nullable=True)
2659 dashboard = relationship("Dashboard", back_populates="widgets")
2662# -- Governance usage ledger --
2665class GovernanceUsage(Base):
2666 """One row per governed LLM invocation — the counter rate limits read.
2668 Policy rules can cap *how often* and *how much* an owner may invoke, and
2669 both questions need a number that exists before svc-ai is called. svc-ai
2670 owns the authoritative per-invocation record (``LLMInvocation``), but
2671 reading it would put a synchronous cross-service hop in front of every
2672 governed request and make a svc-ai outage a governance failure. So
2673 svc-core keeps its own append-only ledger, local to the database the rule
2674 engine already queries.
2676 Deliberately not a user-creatable resource: nothing edits these rows, so
2677 they carry no ``ResourceVersion`` history and no ownership constraint.
2678 They *are* the audit evidence — an immutable record of what was spent
2679 against which policy scope.
2681 ``estimated_cost_usd`` is derived at write time from the invoked model's
2682 per-token price (see ``app.services.usage.estimate_cost``) and stored
2683 rather than recomputed, because a model's price can change afterwards and
2684 a cap must be judged against what the call cost *then*. It is nullable:
2685 a model whose price svc-ai does not publish yields no estimate, and a
2686 cost cap says so rather than silently reading it as zero.
2687 """
2689 __tablename__ = "governance_usage"
2691 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
2693 # Whose quota this counts against. No FK: the ledger outlives the user
2694 # row for the same reason history does — it is most valuable afterwards.
2695 # Null for work no person started (a scheduled crawl of an
2696 # organisation's source, migration 99): its workspace stamp is what a
2697 # budget counts it by, and it is no member's own spend.
2698 owner_user_id = Column(UUID(as_uuid=True), nullable=True, index=True)
2700 # The resource category and instance the invocation was scoped to, mirroring
2701 # how a rule's scope is matched, so a per-agent limit counts only that
2702 # agent's invocations.
2703 scope_type = Column(
2704 Enum(RuleEnum.Scope, name="rule_scope_enum", create_type=False),
2705 nullable=False,
2706 default=RuleEnum.Scope.global_,
2707 )
2708 scope_id = Column(UUID(as_uuid=True), nullable=True, index=True)
2710 # Who the invoked resource belonged to, stamped alongside the resource
2711 # itself. ``scope_type`` records what *ran*, so no row will ever carry
2712 # ``project`` or ``organisation`` there — yet a cap at either level has to
2713 # count everything underneath it. These are the axis it counts on. No FK:
2714 # the ledger is audit evidence and outlives the project it describes, for
2715 # the same reason history does.
2716 owner_project_id = Column(UUID(as_uuid=True), nullable=True)
2717 owner_organisation_id = Column(UUID(as_uuid=True), nullable=True)
2718 #: The person whose workspace it happened in — set for their personal
2719 #: workspace and their personal projects, so a personal rule's quota can
2720 #: count that workspace's traffic whoever is invoking
2721 #: (``app/services/workspace.py``). A project row also carries its
2722 #: organisation, so an organisation's quota counts its projects.
2723 workspace_user_id = Column(UUID(as_uuid=True), nullable=True)
2725 execution_type = Column(String(32), nullable=True)
2726 # Soft reference to svc-ai's llm_models.id — no FK across services.
2727 ai_model_id = Column(UUID(as_uuid=True), nullable=True)
2729 input_tokens = Column(Integer, nullable=False, default=0, server_default="0")
2730 output_tokens = Column(Integer, nullable=False, default=0, server_default="0")
2731 estimated_cost_usd = Column(Numeric(precision=14, scale=8), nullable=True)
2732 #: Wall-clock duration of the invocation, measured around the svc-ai call.
2733 #: Nullable: a turn recorded by a path that does not time itself, or one
2734 #: whose timing was lost, has no measurement — and a statistic that read
2735 #: that as "instant" would make the model look faster than it is.
2736 latency_ms = Column(Integer, nullable=True)
2738 #: Whether the invocation succeeded. Failures are recorded too — an
2739 #: error rate is one of the figures a dashboard slices by agent or model,
2740 #: and a ledger that only held successes could never produce one.
2741 #:
2742 #: Quotas deliberately do *not* count these. ``UsageWindow`` filters to
2743 #: ``ok`` rows, so a rate limit and a cost cap judge exactly what they
2744 #: judged before this column existed: work the user actually got. Counting
2745 #: failures would let a provider outage consume somebody's hourly
2746 #: allowance, which is the "refusing on a number that was never real"
2747 #: failure ``record_usage`` is written to avoid.
2748 outcome = Column(
2749 Enum(UsageEnum.Outcome, name="usage_outcome_enum"),
2750 nullable=False,
2751 default=UsageEnum.Outcome.ok,
2752 server_default=UsageEnum.Outcome.ok.name,
2753 )
2755 #: The resource this spend is attributed to (``UsageEnum.Source``) — the
2756 #: thing whose cost monitoring counts it, which is not always what ran:
2757 #: a dashboard tile runs as the agent it borrows. Null on rows written
2758 #: before migration 69 that could not be attributed (dashboard and
2759 #: evaluation rows); agent, model and skill rows were backfilled.
2760 source_type = Column(String(32), nullable=True)
2761 source_id = Column(UUID(as_uuid=True), nullable=True)
2762 #: How many model calls svc-ai metered for this invocation, and how many
2763 #: of those it could not price. ``unpriced_calls > 0`` makes
2764 #: ``estimated_cost_usd`` a lower bound; both are 0 on unmetered rows.
2765 llm_calls = Column(Integer, nullable=False, default=0, server_default="0")
2766 unpriced_calls = Column(Integer, nullable=False, default=0, server_default="0")
2767 #: What a spending limit takes the unpriced calls to have cost: their
2768 #: tokens at the catalogue's dearest rates, as svc-ai's ceiling counts
2769 #: them (migration 95). Kept apart from ``estimated_cost_usd``, which is
2770 #: what was measured and what spend figures show; a cost cap reads both,
2771 #: so an unpriced model cannot spend round it. Null when every call was
2772 #: priced, and on rows before migration 95.
2773 unpriced_estimate_usd = Column(Numeric(14, 8), nullable=True)
2774 #: The governed turn this row is the spend of — the id its messages,
2775 #: governance activity, review flags and svc-ai's traces carry (see
2776 #: ``ChatMessage.invocation_id``). Null for spend that is no one turn's
2777 #: (generation, retrieval, indexing) and rows before migration 91.
2778 invocation_id = Column(UUID(as_uuid=True), nullable=True, index=True)
2780 occurred_at = Column(DateTime, nullable=False, default=aware_utcnow, index=True)
2782 __table_args__ = (
2783 Index(
2784 "ix_governance_usage_owner_source_occurred",
2785 "owner_user_id",
2786 "source_type",
2787 "source_id",
2788 "occurred_at",
2789 ),
2790 # The window query is always "this owner, since this instant", and a
2791 # rate limit runs before every governed invocation — so the composite
2792 # index is what keeps enforcement off a sequential scan as the ledger
2793 # grows.
2794 Index(
2795 "ix_governance_usage_owner_occurred",
2796 "owner_user_id",
2797 "occurred_at",
2798 ),
2799 Index(
2800 "ix_governance_usage_scope_occurred",
2801 "owner_user_id",
2802 "scope_type",
2803 "scope_id",
2804 "occurred_at",
2805 ),
2806 # A model's quota counts every turn the model answered
2807 # (``ModelScope.usage_filter``), a different access path from the
2808 # scoped quota windows.
2809 Index(
2810 "ix_governance_usage_model_occurred",
2811 "owner_user_id",
2812 "ai_model_id",
2813 "occurred_at",
2814 ),
2815 # Ownership-scoped quotas count by owner attribution rather than by
2816 # the resource that ran, so they need their own access paths.
2817 Index(
2818 "ix_governance_usage_project_occurred",
2819 "owner_user_id",
2820 "owner_project_id",
2821 "occurred_at",
2822 ),
2823 Index(
2824 "ix_governance_usage_organisation_occurred",
2825 "owner_user_id",
2826 "owner_organisation_id",
2827 "occurred_at",
2828 ),
2829 # A workspace's quota counts everyone's traffic there, so its window
2830 # cannot lead with the invoker.
2831 Index(
2832 "ix_governance_usage_ws_org_occurred",
2833 "owner_organisation_id",
2834 "occurred_at",
2835 ),
2836 Index(
2837 "ix_governance_usage_ws_project_occurred", "owner_project_id", "occurred_at"
2838 ),
2839 Index(
2840 "ix_governance_usage_ws_user_occurred", "workspace_user_id", "occurred_at"
2841 ),
2842 )
2845# -- Audit review queue --
2848class ReviewFlag(Base):
2849 """One invocation an audit rule asked a person to look at.
2851 ``flag_for_review`` used to record a trace event and nothing else: the flag
2852 was visible in a conversation's execution trace and nowhere a reviewer
2853 would ever look. This is where it lands, so "flag for review" means a
2854 queue somebody works through rather than a line in a log.
2856 Like :class:`GovernanceUsage` this is an audit artifact, not a
2857 user-creatable resource, so it carries no ``ResourceVersion`` history. The
2858 mutation a reviewer makes is recorded immutably on the row itself
2859 (``reviewed_by_user_id``, ``reviewed_at``, ``reviewer_note``), and the
2860 status is terminal — there is no reopen — which is what makes that single
2861 record sufficient rather than a trail.
2863 The rule identity is denormalised rather than joined. ``Rule.name`` is
2864 mutable and a rule can be deleted outright, and a flag that resolved to
2865 nothing would be exactly the evidence an audit needed; ``rule_version``
2866 pins which revision of the rule fired.
2867 """
2869 __tablename__ = "review_flags"
2871 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
2873 # Whose account the flagged invocation belongs to. No FK, like the rest of
2874 # the audit trail: the record outlives the user row.
2875 #: The user whose response was flagged, or whose evaluation regressed.
2876 #: Null for an organisation's or project's regression, which has no
2877 #: single one.
2878 owner_user_id = Column(UUID(as_uuid=True), nullable=True, index=True)
2879 #: Set when the flag is an organisation's or project's to review: raised
2880 #: by a rule it owns, or by a regression in an evaluation it owns. Its
2881 #: admins' queue holds it rather than the responding user's.
2882 owner_organisation_id = Column(
2883 UUID(as_uuid=True),
2884 ForeignKey("organisations.id", ondelete="CASCADE"),
2885 nullable=True,
2886 index=True,
2887 )
2888 owner_project_id = Column(
2889 UUID(as_uuid=True),
2890 ForeignKey("projects.id", ondelete="CASCADE"),
2891 nullable=True,
2892 index=True,
2893 )
2894 #: The organisation whose rule raised it, when it was raised in one of
2895 #: that organisation's projects: the flag is the project's to review, and
2896 #: the organisation's governance editors see it too.
2897 rule_organisation_id = Column(UUID(as_uuid=True), nullable=True, index=True)
2899 #: ``ReviewEnum.Kind`` — an audit rule's flag, or a regressed evaluation
2900 #: run. One queue for both: each is a governance signal that needs a
2901 #: person's decision, and a reviewer should not have to look in two places.
2902 kind = Column(
2903 String(16),
2904 nullable=False,
2905 default=ReviewEnum.Kind.rule.value,
2906 server_default=ReviewEnum.Kind.rule.value,
2907 index=True,
2908 )
2910 # -- what fired --
2911 rule_id = Column(UUID(as_uuid=True), nullable=True, index=True)
2912 rule_name = Column(String(255), nullable=True)
2913 rule_version = Column(Integer, nullable=True)
2914 scope_type = Column(
2915 Enum(RuleEnum.Scope, name="rule_scope_enum", create_type=False),
2916 nullable=True,
2917 )
2918 scope_id = Column(UUID(as_uuid=True), nullable=True)
2919 #: Who the rule addressed the flag to, from the action's ``reviewer`` param.
2920 reviewer = Column(String(255), nullable=True, index=True)
2922 # -- what was flagged --
2923 execution_type = Column(String(32), nullable=True)
2924 conversation_id = Column(UUID(as_uuid=True), nullable=True, index=True)
2925 agent_id = Column(UUID(as_uuid=True), nullable=True, index=True)
2926 ai_model_id = Column(UUID(as_uuid=True), nullable=True)
2927 #: The governed turn that was flagged (see ``ChatMessage.invocation_id``),
2928 #: so a flag opens the decision record of the answer it is about. Null for
2929 #: a regression, and for flags raised before migration 91.
2930 invocation_id = Column(UUID(as_uuid=True), nullable=True, index=True)
2931 #: Post-redaction excerpt of the flagged response, so the queue is legible
2932 #: without opening every conversation. Stored after audit rules have run,
2933 #: so a rule that redacts PII has already done so. For a regression, what
2934 #: moved (scores, broken cases).
2935 excerpt = Column(Text, nullable=True)
2936 #: The answer an Output rule withheld (``kind = withheld``), after every
2937 #: other Output rule ran on it — so redacted as they redacted it. Served
2938 #: only by the review queue, to those who may review the item: never on
2939 #: the decision record or in the data export, which the person it was
2940 #: withheld from can read (migration 107).
2941 withheld_text = Column(Text, nullable=True)
2942 #: A regression item's evaluation and run. Soft references like the rest
2943 #: of the audit trail — the record outlives both.
2944 experiment_id = Column(UUID(as_uuid=True), nullable=True, index=True)
2945 batch_id = Column(UUID(as_uuid=True), nullable=True)
2947 # -- review --
2948 status = Column(
2949 Enum(ReviewEnum.Status, name="review_status_enum"),
2950 nullable=False,
2951 default=ReviewEnum.Status.pending,
2952 server_default=ReviewEnum.Status.pending.value,
2953 index=True,
2954 )
2955 reviewed_by_user_id = Column(UUID(as_uuid=True), nullable=True)
2956 reviewed_at = Column(DateTime, nullable=True)
2957 reviewer_note = Column(Text, nullable=True)
2959 created_at = Column(DateTime, nullable=False, default=aware_utcnow, index=True)
2960 #: When retention lets this be purged. NULL means keep indefinitely — the
2961 #: default, because silently deleting audit evidence is the worse mistake.
2962 expires_at = Column(DateTime, nullable=True, index=True)
2964 __table_args__ = (
2965 # The queue is almost always read as "my pending flags, newest first".
2966 Index(
2967 "ix_review_flags_owner_status_created",
2968 "owner_user_id",
2969 "status",
2970 "created_at",
2971 ),
2972 )
2975class DecisionOutcome(Base):
2976 """A person's verdict on a governed turn — accepted, edited (with the
2977 corrected text) or rejected — and an optional business-outcome label.
2979 Append-only: a changed mind is a new row, and the newest is the turn's
2980 verdict, so the record keeps who said what and when. Read on the
2981 decision record (its ``outcome`` section) and beside each answer in the
2982 chat, counted by the monthly statement as verified decisions, and the
2983 source of the cases "Add to dataset" makes (``TestCase.source_invocation_id``).
2985 An audit artifact like ``ReviewFlag``: no history of its own (the rows
2986 are it), no FKs — it outlives the turn, the users and the flag it names.
2987 """
2989 __tablename__ = "decision_outcomes"
2991 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
2992 #: The turn (``ChatMessage.invocation_id`` / ``SkillRun.invocation_id``).
2993 invocation_id = Column(UUID(as_uuid=True), nullable=False, index=True)
2994 #: ``DecisionEnum.Kind``: an answer or a skill run.
2995 kind = Column(String(16), nullable=False)
2996 #: ``DecisionEnum.Verdict``.
2997 verdict = Column(String(16), nullable=False)
2998 #: The answer as it should have been, for ``edited``.
2999 corrected_text = Column(Text, nullable=True)
3000 #: The business outcome the team attached ("refund issued"). Free text
3001 #: until a per-workspace vocabulary exists.
3002 label = Column(String(120), nullable=True)
3003 #: Why — most useful on a rejection.
3004 note = Column(Text, nullable=True)
3005 #: ``DecisionEnum.OutcomeSource``: on the answer, or while resolving a
3006 #: review flag (``review_flag_id``).
3007 source = Column(String(16), nullable=False)
3008 review_flag_id = Column(UUID(as_uuid=True), nullable=True)
3009 #: Who gave the verdict, and whose turn it was.
3010 actor_user_id = Column(UUID(as_uuid=True), nullable=False, index=True)
3011 owner_user_id = Column(UUID(as_uuid=True), nullable=True, index=True)
3012 #: The workspace the turn happened in (its conversation's or run's), so
3013 #: an organisation's statement counts its own verdicts.
3014 workspace_organisation_id = Column(UUID(as_uuid=True), nullable=True)
3015 workspace_project_id = Column(UUID(as_uuid=True), nullable=True)
3016 created_at = Column(DateTime, nullable=False, default=aware_utcnow)
3019class DecisionReadLog(Base):
3020 """One read of a turn's decision record by somebody other than its owner.
3022 The record holds a person's whole question and answer, and a reviewer
3023 may open it through a flag on the turn (``review.may_review``). Each such
3024 read is appended here before the record is served — and the record is
3025 not served if it cannot be — so "who has looked at this conversation?"
3026 always has an answer. The owner's own reads are not logged. Shown on the
3027 record itself (its ``reads`` section) and exported with the owner's data.
3029 An audit artifact like ``ReviewFlag``: append-only, no history, no FKs —
3030 it outlives the users it names.
3031 """
3033 __tablename__ = "decision_reads"
3035 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
3036 #: The turn read (``ChatMessage.invocation_id`` / ``SkillRun.invocation_id``).
3037 invocation_id = Column(UUID(as_uuid=True), nullable=False, index=True)
3038 #: Whose turn it was.
3039 owner_user_id = Column(UUID(as_uuid=True), nullable=True, index=True)
3040 reader_user_id = Column(UUID(as_uuid=True), nullable=False, index=True)
3041 #: Why they could read it (``DecisionEnum.Access``) — ``reviewer`` today.
3042 access = Column(String(16), nullable=False)
3043 #: The flag that let them in.
3044 flag_id = Column(UUID(as_uuid=True), nullable=True)
3045 read_at = Column(DateTime, nullable=False, default=aware_utcnow)
3048class GovernanceEvent(Base):
3049 """One rule, evaluated once, against one invocation.
3051 The evidence that governance ran. ``GovernanceUsage`` records what an
3052 invocation *consumed* and ``ReviewFlag`` records what a rule asked a
3053 person to look at; this records the evaluation itself — every applicable
3054 rule, whether or not it matched, and what came of it.
3056 **Rules that did nothing are the point.** Until this table existed, a
3057 rule's effects were visible only as events inside a conversation's
3058 execution trace, and an action that had nothing to do emitted no event at
3059 all. So a redaction rule over a prompt containing no PII looked exactly
3060 like a rule that had never been evaluated — and "was this invocation
3061 governed, and by what?" is the first question an audit asks. Every
3062 applicable rule gets a row, with ``outcome`` separating *blocked*,
3063 *applied*, *ran and changed nothing* and *conditions did not hold*.
3065 **What was redacted is recorded as kinds and counts, never values.**
3066 ``detail`` holds ``{"redact_pii": {"redacted": {"email": 2, "card": 1}}}``,
3067 keyed by the action that ran (``governance_activity.detail_of``). Storing the
3068 matched text would put the exact strings a redaction rule exists to
3069 remove into a table that is kept longer than the conversation — the log
3070 of a redaction must not be a copy of what was redacted.
3072 Like its two siblings this is an audit artifact, not a user-creatable
3073 resource: nothing edits these rows, so they carry no ``ResourceVersion``
3074 history and no ownership constraint. The rule identity is denormalised
3075 (``rule_name``, ``rule_version``) and every reference is soft, because the
3076 record has to outlive the rule, the agent and the conversation — a rule
3077 that was deleted after it blocked somebody is exactly the case the log is
3078 kept for.
3079 """
3081 __tablename__ = "governance_events"
3083 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
3085 # Whose invocation was governed. No FK, like the rest of the audit trail.
3086 owner_user_id = Column(UUID(as_uuid=True), nullable=False, index=True)
3087 # The workspace it happened in, as the usage ledger stamps it, so a
3088 # workspace's reviewers see its activity whoever invoked.
3089 owner_organisation_id = Column(UUID(as_uuid=True), nullable=True, index=True)
3090 owner_project_id = Column(UUID(as_uuid=True), nullable=True, index=True)
3091 workspace_user_id = Column(UUID(as_uuid=True), nullable=True, index=True)
3093 # -- which rule --
3094 rule_id = Column(UUID(as_uuid=True), nullable=True, index=True)
3095 rule_name = Column(String(255), nullable=True)
3096 rule_version = Column(Integer, nullable=True)
3097 layer = Column(
3098 Enum(RuleEnum.Layer, name="rule_layer_enum", create_type=False),
3099 nullable=False,
3100 index=True,
3101 )
3102 scope_type = Column(
3103 Enum(RuleEnum.Scope, name="rule_scope_enum", create_type=False),
3104 nullable=True,
3105 )
3106 scope_id = Column(UUID(as_uuid=True), nullable=True)
3108 # -- what happened --
3109 phase = Column(
3110 Enum(GovernanceEnum.Phase, name="governance_phase_enum"),
3111 nullable=False,
3112 index=True,
3113 )
3114 outcome = Column(
3115 Enum(GovernanceEnum.Outcome, name="governance_outcome_enum"),
3116 nullable=False,
3117 index=True,
3118 )
3119 enforced_in = Column(
3120 Enum(GovernanceEnum.EnforcedIn, name="governance_enforced_in_enum"),
3121 nullable=False,
3122 default=GovernanceEnum.EnforcedIn.core,
3123 server_default=GovernanceEnum.EnforcedIn.core.name,
3124 )
3125 #: The action types that ran, in order. Empty when nothing did — a rule
3126 #: whose conditions did not hold never reached its actions.
3127 actions = Column(JSON, nullable=False, default=list)
3128 #: Per-action specifics: redaction kinds and counts, a block message, the
3129 #: quota figures a limit was judged against. Never the matched text.
3130 detail = Column(JSON, nullable=False, default=dict)
3132 # -- what was governed --
3133 #: One turn, across both phases. A conversation has many turns and the
3134 #: input and output passes are two separate evaluations, so neither
3135 #: ``conversation_id`` nor a timestamp groups "the rules that ran on *this
3136 #: message*" — which is how somebody monitoring policy activity reads the
3137 #: log. Minted once per request and carried on the evaluation context.
3138 #: Nullable: an evaluation from a path that does not mint one still
3139 #: records, and stands alone.
3140 invocation_id = Column(UUID(as_uuid=True), nullable=True, index=True)
3141 execution_type = Column(String(32), nullable=True, index=True)
3142 #: The turn's conversation and its assistant message. Both are filled in
3143 #: *after* the evaluation: the rules run before the turn is persisted, so
3144 #: neither id exists yet when the row is written. They are what lets the
3145 #: activity log open the exact message a rule ran on rather than the
3146 #: agent's chat at whatever it happens to be showing.
3147 conversation_id = Column(UUID(as_uuid=True), nullable=True, index=True)
3148 message_id = Column(UUID(as_uuid=True), nullable=True, index=True)
3149 agent_id = Column(UUID(as_uuid=True), nullable=True, index=True)
3150 ai_model_id = Column(UUID(as_uuid=True), nullable=True)
3152 created_at = Column(DateTime, nullable=False, default=aware_utcnow, index=True)
3154 __table_args__ = (
3155 # The log is almost always read as "my activity, newest first",
3156 # optionally narrowed to one outcome.
3157 Index(
3158 "ix_governance_events_owner_created",
3159 "owner_user_id",
3160 "created_at",
3161 ),
3162 # …and rendered grouped by turn, so the page's second query asks for
3163 # every event of a handful of invocations at once.
3164 Index(
3165 "ix_governance_events_owner_invocation",
3166 "owner_user_id",
3167 "invocation_id",
3168 ),
3169 )
3172# -- Scheduler --
3175class BackgroundEvent(Base):
3176 """One piece of work the platform did for an owner outside a request.
3178 ``scheduled_jobs`` says a job ran and what it came to across the whole
3179 platform ("refreshed 12 widgets"). That answers an operator; it does not
3180 answer a user asking what happened to *their* things while they were
3181 away — which board tile regenerated, which website was re-crawled and
3182 what changed, which flags retention deleted. This does, one row per
3183 subject, and the Activity page reads it.
3185 An audit artifact like ``governance_events``: append-only, soft
3186 references, the subject's name denormalised, because the record has to
3187 outlive the board or source it describes.
3188 """
3190 __tablename__ = "background_events"
3192 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
3194 #: Whose thing it was. Soft, and the feed reads by ``owner_user_id``;
3195 #: the other two are kept so a project- or organisation-owned subject is
3196 #: recorded rather than dropped.
3197 owner_user_id = Column(UUID(as_uuid=True), nullable=True)
3198 owner_project_id = Column(UUID(as_uuid=True), nullable=True)
3199 owner_organisation_id = Column(UUID(as_uuid=True), nullable=True)
3201 #: ``BackgroundEnum`` members, stored as strings.
3202 kind = Column(String(32), nullable=False)
3203 trigger = Column(String(16), nullable=False)
3204 status = Column(String(16), nullable=False)
3206 #: What it was done to, in the activity feed's resource vocabulary
3207 #: (``dashboard``, ``knowledge``) so the client can link it.
3208 subject_type = Column(String(32), nullable=True)
3209 subject_id = Column(UUID(as_uuid=True), nullable=True)
3210 subject_name = Column(String(255), nullable=True)
3212 #: One line: "Re-crawled 14 pages: 2 changed, 1 new".
3213 summary = Column(String(500), nullable=False)
3214 #: Figures behind the summary, per kind (page counts, widget type).
3215 detail = Column(JSON, nullable=True)
3216 #: Ids of the finer-grained records it points at (crawl, widget).
3217 reference = Column(JSON, nullable=True)
3218 error = Column(String(1000), nullable=True)
3220 started_at = Column(DateTime, nullable=True)
3221 finished_at = Column(DateTime, nullable=False, default=aware_utcnow)
3222 duration_ms = Column(Integer, nullable=True)
3224 __table_args__ = (
3225 Index("ix_background_events_owner_finished", "owner_user_id", "finished_at"),
3226 #: The retention purge reads across every owner by age, which the
3227 #: owner-led index above cannot serve (migration 72).
3228 Index("ix_background_events_finished", "finished_at"),
3229 )
3232class ScheduledJob(Base):
3233 """The last run of one background job — the scheduler's heartbeat.
3235 One row per registered job, upserted rather than appended. That is the
3236 deliberate difference from the audit tables above: this is *operational
3237 state*, not evidence about a user's data. An append-only run log would
3238 grow without bound and need a retention policy of its own, which would
3239 have to be enforced by… a scheduled job. One row per job answers the
3240 question anyone actually asks — "when did this last run, and did it
3241 work?" — without that circularity.
3243 Why it exists at all, when the jobs are idempotent and could schedule
3244 themselves from memory: "has the retention purge been running?" is an
3245 audit question, and a scheduler that could only be observed by reading
3246 logs is one nobody can answer it about. ``GET /monitoring/scheduler``
3247 serves these rows.
3249 The registry is the source of truth for which jobs exist; a row here is
3250 created the first time a job runs. A job removed from the registry leaves
3251 its row behind, which is the right way round — the record that it used to
3252 run outlives the code that ran it.
3253 """
3255 __tablename__ = "scheduled_jobs"
3257 #: The registry key, e.g. "dashboard_refresh". Natural primary key: there
3258 #: is exactly one of each job, and naming it by its key means a restart
3259 #: cannot orphan the row by minting a new id.
3260 key = Column(String(64), primary_key=True)
3262 #: When the last run started and finished. Both set together at the end of
3263 #: a run, so a row never claims a duration it did not measure.
3264 last_started_at = Column(DateTime, nullable=True)
3265 last_finished_at = Column(DateTime, nullable=True)
3266 last_duration_ms = Column(Integer, nullable=True)
3268 #: Outcome of the last run, and one line describing what it did — "12
3269 #: widgets refreshed", "3 flags purged". Free text on purpose: a job knows
3270 #: what is worth saying about itself, and a structured shape here would
3271 #: have to anticipate every job ever added.
3272 last_status = Column(
3273 Enum(SchedulerEnum.Status, name="scheduled_job_status_enum"),
3274 nullable=True,
3275 )
3276 last_detail = Column(String(500), nullable=True)
3277 #: Kept separately from ``last_detail`` and *not* cleared by a subsequent
3278 #: success: "this job is working now but failed at 03:00" is a different
3279 #: statement from "this job has never failed", and only one of them is
3280 #: worth waking somebody for.
3281 last_error = Column(String(1000), nullable=True)
3282 last_error_at = Column(DateTime, nullable=True)
3284 #: Cumulative counters, so a dashboard can show that a job is running at
3285 #: all rather than only that its most recent run went well.
3286 run_count = Column(Integer, nullable=False, default=0, server_default="0")
3287 failure_count = Column(Integer, nullable=False, default=0, server_default="0")
3290class SpendStatement(Base):
3291 """One workspace's statement for one finished calendar month (UTC):
3292 its spend and what governed it (cost-control plan A4.1, the monthly
3293 organisation statement of ``docs/business/mvp-roadmap.md``).
3295 Written once, an hour after the month ends, by the ``spend_statements``
3296 job (``app/services/statements``), and never changed: a statement is what
3297 the month came to as the platform recorded it, kept so finance and an
3298 audit read the same figures every time. ``content`` is the statement as
3299 served, aggregate figures only — no prompt, answer or person's name —
3300 with ``content_sha256`` over its canonical JSON.
3302 A record like ``DecisionReadLog``, not a user resource: no edit history,
3303 and no foreign keys — it outlives the workspace and everything it counts.
3304 ``workspace_key`` is its workspace (``Workspace.key``), unique with the
3305 month; the owner columns say whose data export holds it (a person's
3306 Personal workspace only).
3307 """
3309 __tablename__ = "spend_statements"
3310 __table_args__ = (
3311 UniqueConstraint(
3312 "workspace_key", "period_start", name="uq_spend_statement_month"
3313 ),
3314 )
3316 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
3317 workspace_key = Column(String(80), nullable=False, index=True)
3318 owner_user_id = Column(UUID(as_uuid=True), nullable=True, index=True)
3319 owner_organisation_id = Column(UUID(as_uuid=True), nullable=True)
3320 owner_project_id = Column(UUID(as_uuid=True), nullable=True)
3321 #: The month's first day.
3322 period_start = Column(Date, nullable=False)
3323 closed_at = Column(DateTime, nullable=False, default=aware_utcnow)
3324 #: ``statements.SCHEMA_VERSION`` when it was written.
3325 schema_version = Column(Integer, nullable=False)
3326 content = Column(JSON, nullable=False)
3327 content_sha256 = Column(String(64), nullable=False)
3330class Notification(Base):
3331 """Something a person should know about without having to look: a
3332 budget passing a threshold, a statement ready to read (cost-control plan
3333 A2, the in-app inbox).
3335 One row per recipient, written by the platform (``app/services/
3336 notifications``) and read in fe-core's inbox. ``kind`` is a registered
3337 kind; ``title`` and ``body`` are composed when it is written, from
3338 figures only — never a prompt, an answer or anyone else's spending by
3339 name. ``link`` is a page written against ``/user/…``; fe-core moves it
3340 into ``workspace_key``'s workspace. ``dedupe_key`` makes each alert once
3341 per recipient (a budget's threshold in one period, say).
3343 Not a resource: no edit history and no foreign keys. Read ones are
3344 deleted after ``notifications.RETENTION_DAYS``.
3345 """
3347 __tablename__ = "notifications"
3348 __table_args__ = (
3349 UniqueConstraint(
3350 "recipient_user_id", "dedupe_key", name="uq_notification_once"
3351 ),
3352 )
3354 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
3355 recipient_user_id = Column(UUID(as_uuid=True), nullable=False, index=True)
3356 kind = Column(String(32), nullable=False)
3357 #: The workspace it is about (``Workspace.key``), and its name then.
3358 workspace_key = Column(String(80), nullable=True)
3359 workspace_name = Column(String(255), nullable=True)
3360 title = Column(String(200), nullable=False)
3361 body = Column(Text, nullable=True)
3362 link = Column(String(500), nullable=True)
3363 #: The figures it was written from, for a page that wants them.
3364 data = Column(JSON, nullable=True)
3365 dedupe_key = Column(String(200), nullable=False)
3366 created_at = Column(DateTime, nullable=False, default=aware_utcnow, index=True)
3367 read_at = Column(DateTime, nullable=True)
3370class ScenarioRun(Base):
3371 """One scenario run (``app/services/scenarios``): a developer's scripted
3372 set of agent chats, run in a project of its own and kept for export.
3374 Written ``running`` before the work is handed to the runner's worker,
3375 with each turn's export appended to ``results`` as it finishes — so a run
3376 cut off by a restart keeps what it did — and finished in place. A record
3377 of something that happened, not a resource anyone edits: no version
3378 trail. The project it ran in is ``SET NULL``, so deleting that project
3379 by hand leaves the record readable.
3380 """
3382 __tablename__ = "scenario_runs"
3384 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
3385 user_id = Column(
3386 UUID(as_uuid=True),
3387 ForeignKey("users.id", ondelete="CASCADE"),
3388 nullable=False,
3389 index=True,
3390 )
3391 #: The scenario's own name, and the file as it was uploaded (validated).
3392 name = Column(String(120), nullable=False)
3393 scenario = Column(JSON, nullable=False)
3394 scenario_sha256 = Column(String(64), nullable=False)
3395 project_id = Column(
3396 UUID(as_uuid=True),
3397 ForeignKey("projects.id", ondelete="SET NULL"),
3398 nullable=True,
3399 )
3400 #: ``scenarios.runner.Status``, stored as a string.
3401 status = Column(String(16), nullable=False)
3402 #: ``{done, total, current}``: turns finished, turns in all, the one
3403 #: running now.
3404 progress = Column(JSON, nullable=False, default=dict)
3405 #: The export as far as it has got (``scenarios.export``); None until the
3406 #: run is provisioned.
3407 results = Column(JSON(none_as_null=True), nullable=True)
3408 error = Column(Text, nullable=True)
3409 #: Asked to stop: the runner stops the turn running and starts no more.
3410 cancel_requested = Column(Boolean, nullable=False, default=False)
3411 created_at = Column(DateTime, nullable=False, default=aware_utcnow)
3412 #: When it last moved; a run silent too long reads as failed.
3413 updated_at = Column(DateTime, nullable=False, default=aware_utcnow)
3414 finished_at = Column(DateTime, nullable=True)
3417# -- Swarms --
3420class Swarm(
3421 OwnableMixin.Resource,
3422 GenerationMixin.Tagged,
3423 DateMixin.Updated,
3424 Base,
3425):
3426 """A team of agents in a shape (``app/services/swarms``), saved so it can
3427 be sent on a task as often as it is wanted.
3429 ``topology`` names the shape — a class in ``swarms.topologies`` — and
3430 ``params`` its settings, validated by that class. ``roster`` is which of
3431 the workspace's agents play which part: ``[{handle, role, agent_id}]``.
3432 ``defaults`` are what a dispatch starts from (budget, time cap,
3433 parallelism, whether the plan is approved first, whether workers may
3434 ask).
3436 Versioned like every user-created resource; a run stores the version it
3437 ran (``SwarmRun.swarm_version``) and a copy of what it ran, so editing a
3438 swarm never changes a run's record.
3439 """
3441 __tablename__ = "swarms"
3443 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
3444 name = Column(String(255), nullable=False)
3445 description = Column(Text, nullable=True)
3446 topology = Column(String(32), nullable=False)
3447 params = Column(JSON, nullable=False, default=dict)
3448 roster = Column(JSON, nullable=False, default=list)
3449 defaults = Column(JSON, nullable=False, default=dict)
3451 __table_args__ = (
3452 # One name per owner: three partial indexes, as dashboards have,
3453 # since NULLs make a composite UNIQUE enforce nothing for a user row.
3454 Index(
3455 "uq_swarm_name_user",
3456 "owner_user_id",
3457 "name",
3458 unique=True,
3459 postgresql_where=text("owner_user_id IS NOT NULL"),
3460 ),
3461 Index(
3462 "uq_swarm_name_organisation",
3463 "owner_organisation_id",
3464 "name",
3465 unique=True,
3466 postgresql_where=text("owner_organisation_id IS NOT NULL"),
3467 ),
3468 Index(
3469 "uq_swarm_name_project",
3470 "owner_project_id",
3471 "name",
3472 unique=True,
3473 postgresql_where=text("owner_project_id IS NOT NULL"),
3474 ),
3475 ownership_constraint("swarms"),
3476 )
3479class SwarmRun(Base):
3480 """One dispatch of a swarm on a task, under a budget and a time cap.
3482 Written before the work is handed to a coordinator and finished in
3483 place; a record of something that happened, so it has no version trail
3484 of its own. The swarm is ``SET NULL`` and its name and configuration are
3485 copied (``config``): a run is most worth reading when someone asks what
3486 a since-changed or deleted swarm did.
3488 Its tasks (``swarm_tasks``) are the tree the team worked through. The
3489 rows are the truth: a finished task is committed before anything is
3490 decided from it, so a coordinator lost to a restart is resumed from the
3491 last finished task (``swarms.engine.watchdog``).
3492 """
3494 __tablename__ = "swarm_runs"
3496 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
3497 swarm_id = Column(
3498 UUID(as_uuid=True), ForeignKey("swarms.id", ondelete="SET NULL"), nullable=True
3499 )
3500 swarm_name = Column(String(255), nullable=False)
3501 swarm_version = Column(Integer, nullable=True)
3502 #: The run this one follows up (``swarms.thread``): the latest run of
3503 #: its thread when it was sent.
3504 parent_run_id = Column(
3505 UUID(as_uuid=True),
3506 ForeignKey("swarm_runs.id", ondelete="SET NULL"),
3507 nullable=True,
3508 )
3509 #: The thread's first run (its own id for a first request), and this
3510 #: run's place in the thread, from 1: one place per thread.
3511 thread_id = Column(UUID(as_uuid=True), nullable=False)
3512 thread_seq = Column(Integer, nullable=False, default=1, server_default="1")
3513 #: The swarm as it ran: ``{topology, params, roster, defaults}``.
3514 config = Column(JSON, nullable=False, default=dict)
3515 user_id = Column(
3516 UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False
3517 )
3518 #: The workspace it was dispatched in, as a skill run's.
3519 workspace_organisation_id = Column(UUID(as_uuid=True), nullable=True)
3520 workspace_project_id = Column(UUID(as_uuid=True), nullable=True)
3522 #: ``SwarmEnum.RunStatus``, stored as a string.
3523 status = Column(String(24), nullable=False)
3524 #: What the person asked the swarm to do.
3525 task = Column(Text, nullable=False)
3526 #: Documents from the workspace's library, given to every agent.
3527 file_ids = Column(JSON, nullable=False, default=list)
3529 budget_usd = Column(Numeric(precision=14, scale=6), nullable=False)
3530 time_cap_s = Column(Integer, nullable=False)
3531 deadline_at = Column(DateTime, nullable=False)
3532 #: Kept back for the answer: work stops being started once what is left
3533 #: of the budget or the time is this much (``swarms.budget``).
3534 reserve_usd = Column(Numeric(precision=14, scale=6), nullable=False)
3535 reserve_s = Column(Integer, nullable=False)
3536 #: ``SwarmEnum.WrapUpReason`` once the run began writing its answer early.
3537 wrap_up_reason = Column(String(16), nullable=True)
3539 #: What the lead proposed, as approved: ``{approach, tasks, estimate_usd}``.
3540 plan = Column(JSON(none_as_null=True), nullable=True)
3541 #: What the team has established, shared with every agent: facts,
3542 #: assumptions and gaps (``swarms.ledger``).
3543 ledger = Column(JSON, nullable=False, default=dict)
3544 #: ``{done, total, running}``: tasks finished, tasks in all, running now.
3545 progress = Column(JSON, nullable=False, default=dict)
3547 output = Column(Text, nullable=True)
3548 #: The sources its answer cites, each with the ``marker`` the answer
3549 #: cites it by (svc-ai's ``cited_citations``): handed on with the answer
3550 #: to a follow-up (``swarms.thread``), so it cites the sources themselves.
3551 citations = Column(JSON(none_as_null=True), nullable=True)
3552 warnings = Column(JSON(none_as_null=True), nullable=True)
3553 error = Column(Text, nullable=True)
3555 #: What the run's calls cost as svc-ai measured them, and what a budget
3556 #: counts them as (unpriced calls at the dearest rate).
3557 cost_usd = Column(
3558 Numeric(precision=14, scale=8), nullable=False, default=0, server_default="0"
3559 )
3560 spent_usd = Column(
3561 Numeric(precision=14, scale=8), nullable=False, default=0, server_default="0"
3562 )
3563 llm_calls = Column(Integer, nullable=False, default=0, server_default="0")
3564 unpriced_calls = Column(Integer, nullable=False, default=0, server_default="0")
3565 input_tokens = Column(Integer, nullable=False, default=0, server_default="0")
3566 output_tokens = Column(Integer, nullable=False, default=0, server_default="0")
3568 #: Asked to stop: no new work starts and the answer is written.
3569 cancel_requested = Column(Boolean, nullable=False, default=False)
3570 #: When its coordinator last looked at it; silent too long, the watchdog
3571 #: resumes it.
3572 heartbeat_at = Column(DateTime, nullable=True)
3573 #: When it began waiting on a person — the plan's approval, or answers
3574 #: nothing else can go on without. Its clock is stopped meanwhile: the
3575 #: deadline moves on by the wait when it resumes (``engine._resume``).
3576 paused_at = Column(DateTime, nullable=True)
3578 created_at = Column(DateTime, nullable=False, default=aware_utcnow)
3579 finished_at = Column(DateTime, nullable=True)
3581 # The database deletes a run's tasks (``run_id`` cascades), so deleting a
3582 # run never loads them first.
3583 tasks = relationship(
3584 "SwarmTask",
3585 back_populates="run",
3586 cascade="all, delete-orphan",
3587 passive_deletes=True,
3588 order_by="SwarmTask.seq",
3589 )
3591 __table_args__ = (
3592 Index("ix_swarm_runs_swarm_user_created", "swarm_id", "user_id", "created_at"),
3593 Index("ix_swarm_runs_status", "status"),
3594 Index("ix_swarm_runs_parent_run_id", "parent_run_id"),
3595 Index("uq_swarm_runs_thread_seq", "thread_id", "thread_seq", unique=True),
3596 )
3599class SwarmTask(Base):
3600 """One piece of a swarm run: an agent's turn planning, working,
3601 reviewing or writing the answer.
3603 Its own governed turn: ``invocation_id`` joins it to its ledger rows,
3604 rule activity and svc-ai's traces, as a skill run's does. ``agent_id``
3605 is ``SET NULL`` with its name copied, as everywhere a record outlives
3606 what it names.
3607 """
3609 __tablename__ = "swarm_tasks"
3611 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
3612 run_id = Column(
3613 UUID(as_uuid=True),
3614 ForeignKey("swarm_runs.id", ondelete="CASCADE"),
3615 nullable=False,
3616 index=True,
3617 )
3618 #: The task this one's work belongs under. ``SET NULL``, not a cascade:
3619 #: a run's tasks go with the run, and a cascade here raced the run's.
3620 parent_id = Column(
3621 UUID(as_uuid=True),
3622 ForeignKey("swarm_tasks.id", ondelete="SET NULL"),
3623 nullable=True,
3624 )
3625 #: Order of creation within the run.
3626 seq = Column(Integer, nullable=False)
3627 depth = Column(Integer, nullable=False, default=0)
3628 #: ``SwarmEnum.TaskKind``.
3629 kind = Column(String(16), nullable=False)
3630 #: How the plan names it to the team (``T1``…), or the step's name.
3631 handle = Column(String(16), nullable=False)
3632 title = Column(String(255), nullable=False)
3633 #: The roster role that does it (``lead``, ``worker``).
3634 role = Column(String(32), nullable=False)
3635 agent_id = Column(
3636 UUID(as_uuid=True), ForeignKey("agents.id", ondelete="SET NULL"), nullable=True
3637 )
3638 agent_name = Column(String(255), nullable=False)
3639 #: ``SwarmEnum.Tier`` and the cost profile it ran under.
3640 tier = Column(String(16), nullable=False)
3641 cost_profile = Column(String(16), nullable=True)
3642 #: What it is asked to do: objective, output format, sources,
3643 #: boundaries, when it is done (``swarms.schemas.TaskBrief``).
3644 brief = Column(JSON, nullable=False, default=dict)
3645 #: Ids of the tasks it waits for.
3646 depends_on = Column(JSON, nullable=False, default=list)
3648 #: ``SwarmEnum.TaskStatus``.
3649 status = Column(String(16), nullable=False)
3650 attempts = Column(Integer, nullable=False, default=0, server_default="0")
3652 #: Its share of the budget, what its agent's turn was estimated to cost,
3653 #: and the most its current call may spend (the share left, or less).
3654 budget_usd = Column(Numeric(precision=14, scale=6), nullable=True)
3655 estimate_usd = Column(Numeric(precision=14, scale=6), nullable=True)
3656 limit_usd = Column(Numeric(precision=14, scale=6), nullable=True)
3657 cost_usd = Column(
3658 Numeric(precision=14, scale=8), nullable=False, default=0, server_default="0"
3659 )
3660 spent_usd = Column(
3661 Numeric(precision=14, scale=8), nullable=False, default=0, server_default="0"
3662 )
3663 llm_calls = Column(Integer, nullable=False, default=0, server_default="0")
3664 unpriced_calls = Column(Integer, nullable=False, default=0, server_default="0")
3665 input_tokens = Column(Integer, nullable=False, default=0, server_default="0")
3666 output_tokens = Column(Integer, nullable=False, default=0, server_default="0")
3667 latency_ms = Column(Integer, nullable=True)
3668 invocation_id = Column(UUID(as_uuid=True), nullable=True, index=True)
3670 #: What it wrote (after the Output rules).
3671 output = Column(Text, nullable=True)
3672 #: A structured step's reply, as validated (a plan, a review).
3673 result = Column(JSON(none_as_null=True), nullable=True)
3674 #: The sources its answer cites, each with the ``marker`` its text cites
3675 #: it by: handed on with its text to the steps that read it.
3676 citations = Column(JSON(none_as_null=True), nullable=True)
3677 #: The questions its agent asked, while it waits, and every answer given.
3678 questions = Column(JSON(none_as_null=True), nullable=True)
3679 responses = Column(JSON(none_as_null=True), nullable=True)
3680 rule_events = Column(JSON(none_as_null=True), nullable=True)
3681 error = Column(Text, nullable=True)
3683 created_at = Column(DateTime, nullable=False, default=aware_utcnow)
3684 started_at = Column(DateTime, nullable=True)
3685 finished_at = Column(DateTime, nullable=True)
3687 run = relationship("SwarmRun", back_populates="tasks")