Coverage for app / db / postgres / models.py: 100%
185 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1from uuid import uuid4
3from sqlalchemy import (
4 Boolean,
5 Column,
6 Date,
7 DateTime,
8 Enum,
9 ForeignKey,
10 Integer,
11 JSON,
12 Numeric,
13 SmallInteger,
14 String,
15 Text,
16 UniqueConstraint,
17 Float,
18 Index,
19)
20from sqlalchemy.dialects.postgresql import ARRAY, REAL, UUID
21from sqlalchemy.orm import declarative_base, relationship
23from .enums import (
24 InvocationEnum,
25 MessageEnum,
26 ModelEnum,
27 ToolInvocationEnum,
28)
29from .mixin import DateMixin, FKMixin
30from app.util.time import aware_utcnow
31from app.agents.enums import AgentRole
33Base = declarative_base()
36# ---------------------------------------------------------------------------
37# Providers
38# ---------------------------------------------------------------------------
41class Provider(DateMixin.Updated, Base):
42 """
43 A registered LLM provider (e.g. OpenAI, Anthropic).
44 Stores connectivity config and enabled/disabled state.
45 """
47 __tablename__ = "providers"
49 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
51 name = Column(
52 Enum(ModelEnum.Provider, name="provider_name_enum"),
53 unique=True,
54 nullable=False,
55 )
56 display_name = Column(String(255), nullable=False)
58 is_default = Column(
59 Boolean, default=False, nullable=False
60 ) # Whether this is the default provider for new models
62 # Override the default provider API endpoint (e.g. self-hosted proxies)
63 base_url = Column(String(1024), nullable=True)
65 is_enabled = Column(Boolean, default=True, nullable=False)
67 # Extra provider-level settings (e.g. org_id, api_version)
68 config = Column(JSON, nullable=True)
70 models = relationship(
71 "LLMModel",
72 back_populates="provider",
73 cascade="all, delete-orphan",
74 )
77# ---------------------------------------------------------------------------
78# LLM Models
79# ---------------------------------------------------------------------------
82class LLMModel(FKMixin.Provider.Child, DateMixin.Updated, Base):
83 """
84 A specific model offered by a provider.
85 Stores capability flags, token limits, pricing, and default config.
86 """
88 __tablename__ = "llm_models"
90 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
92 # Exact identifier used in API calls (e.g. "gpt-4o-mini", "claude-3-5-sonnet-20241022")
93 model_name = Column(String(255), nullable=False)
95 display_name = Column(String(255), nullable=True)
96 description = Column(Text, nullable=True)
98 is_default = Column(
99 Boolean, default=False, nullable=False
100 ) # Whether this is the default model for its provider
101 is_recommended = Column(
102 Boolean, default=False, nullable=False
103 ) # Whether this model is recommended for new agents/conversations
105 # Capability flags
106 is_chat = Column(Boolean, default=True, nullable=False)
107 is_embedding = Column(Boolean, default=False, nullable=False)
108 is_vision = Column(Boolean, default=False, nullable=False)
110 # Last known availability (updated on validate calls)
111 is_available = Column(Boolean, default=True, nullable=False)
113 # Token limits
114 context_window = Column(Integer, nullable=True) # max input tokens
115 max_output_tokens = Column(Integer, nullable=True)
117 # Per-token cost in USD (high-precision decimal for small values)
118 input_cost_per_token = Column(Numeric(precision=14, scale=10), nullable=True)
119 output_cost_per_token = Column(Numeric(precision=14, scale=10), nullable=True)
120 # The rest of the price card, USD per token (services/provider_usage.py):
121 # cache reads, cache writes (OpenAI's, Anthropic's 5-minute) and
122 # Anthropic's 1-hour writes — each a per-model rate, not a multiplier —
123 # and the prompt size past which the whole request is repriced by the
124 # two multipliers (input classes, output). Null where the model has no
125 # such rate; a call needing one is then priced from LiteLLM or unpriced.
126 cache_read_cost_per_token = Column(Numeric(precision=14, scale=10), nullable=True)
127 cache_write_cost_per_token = Column(Numeric(precision=14, scale=10), nullable=True)
128 cache_write_1h_cost_per_token = Column(
129 Numeric(precision=14, scale=10), nullable=True
130 )
131 long_context_threshold = Column(Integer, nullable=True)
132 long_context_input_multiplier = Column(Numeric(precision=6, scale=3), nullable=True)
133 long_context_output_multiplier = Column(
134 Numeric(precision=6, scale=3), nullable=True
135 )
137 # Data residency region — where requests are processed (for compliance/governance)
138 data_region = Column(
139 # By value: the database's labels are the values (migration 7), and
140 # ``global`` is a keyword, so its member is ``global_`` — persisted
141 # by name it would be refused, and no seed had used it until the
142 # Bedrock catalogue (``inference_routes``).
143 Enum(
144 ModelEnum.DataRegion,
145 name="data_region_enum",
146 values_callable=lambda members: [m.value for m in members],
147 ),
148 nullable=True,
149 )
151 # Provider-independent reasoning tier — what a user picking between
152 # "Claude Sonnet 5" and "GPT-5.6 Terra" is actually choosing between.
153 effort = Column(
154 Enum(ModelEnum.Effort, name="model_effort_enum"),
155 nullable=True,
156 )
158 # Comparative response speed within the catalogue, not a measured figure.
159 latency = Column(
160 Enum(ModelEnum.Latency, name="model_latency_enum"),
161 nullable=True,
162 )
164 # Reliable knowledge cutoff — the date through which the model's knowledge
165 # is most extensive, as published by the provider. Stored as a date because
166 # providers publish it to the month; the day is the first of that month.
167 knowledge_cutoff = Column(Date, nullable=True)
169 # Default inference config (temperature, max_tokens, top_p, etc.)
170 config = Column(JSON, nullable=True)
172 # When the model was taken out of the catalogue. A model is archived, never
173 # deleted: the row stays so every trace, call and conversation that used
174 # it keeps naming its provider and model. Archived models are left out of
175 # every catalogue read unless one asks for them, so nothing can select or
176 # run one — exactly as if it had been deleted.
177 archived_at = Column(DateTime, nullable=True)
179 provider = relationship("Provider", back_populates="models")
181 # None of these cascade: a model's conversations and traces outlive it.
182 # An ORM delete cascade here once deleted svc-ai's record of every
183 # conversation on a model when the model was deleted.
184 conversations = relationship(
185 "Conversation",
186 back_populates="model",
187 passive_deletes=True,
188 )
189 invocations = relationship(
190 "LLMInvocation",
191 back_populates="model",
192 passive_deletes=True,
193 )
195 __table_args__ = (
196 UniqueConstraint("provider_id", "model_name", name="uq_provider_model_name"),
197 )
200# ---------------------------------------------------------------------------
201# Conversations
202# ---------------------------------------------------------------------------
205class Conversation(FKMixin.LLMModel.NullableChild, DateMixin.Updated, Base):
206 """
207 A multi-turn LLM conversation session.
209 user_id is the requesting user from svc-core — stored as plain text, no FK constraint.
210 external_agent_id optionally links to a svc-core Agent; again no FK constraint.
211 """
213 __tablename__ = "conversations"
215 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
217 # Requesting user from svc-core (no cross-DB FK)
218 user_id = Column(Text, nullable=False, index=True)
220 # Soft-reference to a svc-core Agent (no cross-DB FK)
221 external_agent_id = Column(UUID(as_uuid=True), nullable=True, index=True)
223 # Optional human-readable title (auto-generated or user-set)
224 title = Column(String(512), nullable=True)
226 total_input_tokens = Column(Integer, nullable=False, default=0)
227 total_output_tokens = Column(Integer, nullable=False, default=0)
228 total_tokens = Column(Integer, nullable=False, default=0)
230 model = relationship("LLMModel", back_populates="conversations")
232 messages = relationship(
233 "ChatMessage",
234 back_populates="conversation",
235 order_by="ChatMessage.sent_at",
236 cascade="all, delete-orphan",
237 lazy="selectin",
238 )
241# ---------------------------------------------------------------------------
242# Chat Messages
243# ---------------------------------------------------------------------------
246class ChatMessage(FKMixin.Conversation.Child, DateMixin.Sent, Base):
247 """
248 A single message within a Conversation.
249 token_count is stored per-message for accurate billing and context management.
250 """
252 __tablename__ = "chat_messages"
254 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
256 role = Column(
257 Enum(MessageEnum.Role, name="message_role_enum"),
258 nullable=False,
259 index=True,
260 )
261 content = Column(Text, nullable=False)
262 token_count = Column(Integer, nullable=False)
264 conversation = relationship("Conversation", back_populates="messages")
267# ---------------------------------------------------------------------------
268# LLM Invocations
269# ---------------------------------------------------------------------------
272class LLMInvocation(FKMixin.LLMModel.NullableChild, DateMixin.Created, Base):
273 """
274 One traced invocation — an execution, a resumed segment of one, or a
275 platform flow — and the model calls it made.
276 Tracks token usage, latency, cost, and outcome for observability and billing.
277 conversation_id is a soft cross-service reference to svc-core's conversations.id (no FK constraint).
279 ``provider`` / ``model_name`` name the model the request asked for (an
280 agent's or a prompt's configured model, a generation flow's model), or
281 the one model every call used when the request named none. They are
282 stored as text so the row says which model it was even when the
283 catalogue does not list it, or no longer does; ``model_id`` is the
284 catalogue link when there is one. Null only when the calls used several
285 models and the request named none — ``calls`` says exactly which did
286 what, one row per model call.
287 """
289 __tablename__ = "llm_invocations"
291 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
293 # Soft reference to svc-core's conversations.id — no FK constraint
294 conversation_id = Column(UUID(as_uuid=True), nullable=True)
296 # Soft reference to svc-core's users.id — set for user-attributable calls
297 user_id = Column(UUID(as_uuid=True), nullable=True, index=True)
299 # The svc-core workspace the call was made in (``user:<id>``,
300 # ``organisation:<id>``, ``project:<id>``; app/common/workspace.py), so a
301 # workspace's usage figures are its own. None: before rows named one.
302 workspace = Column(String(80), nullable=True)
304 # svc-core's id for the turn this was part of — an answer, a skill run,
305 # an evaluation cell (``X-Invocation-Id``; app/common/invocation.py) —
306 # which its usage ledger, review queue and messages carry too, so the
307 # decision record for one answer can read the calls behind it. None: no
308 # turn named, or before rows carried one.
309 core_invocation_id = Column(UUID(as_uuid=True), nullable=True, index=True)
311 # What produced this call: an execution type (model | agent | skill |
312 # worker | graph | pipeline) or a platform flow (agent_generation)
313 purpose = Column(String(50), nullable=True, index=True)
315 # Truncated snapshot of the produced output, for the activity trace view
316 output_preview = Column(Text, nullable=True)
318 prompt_tokens = Column(Integer, nullable=False, default=0)
319 completion_tokens = Column(Integer, nullable=False, default=0)
320 total_tokens = Column(Integer, nullable=False, default=0)
322 latency_ms = Column(Integer, nullable=True)
324 status = Column(
325 Enum(InvocationEnum.Status, name="invocation_status_enum"),
326 nullable=False,
327 )
328 error_detail = Column(Text, nullable=True)
330 # Snapshot of the config used for this specific call
331 request_config = Column(JSON, nullable=True)
333 # Computed cost based on model pricing at time of call
334 estimated_cost_usd = Column(Numeric(precision=14, scale=8), nullable=True)
336 provider = Column(String(100), nullable=True, index=True)
337 model_name = Column(String(255), nullable=True, index=True)
339 model = relationship("LLMModel", back_populates="invocations")
340 calls = relationship(
341 "LLMInvocationCall",
342 back_populates="invocation",
343 cascade="all, delete-orphan",
344 passive_deletes=True,
345 order_by="LLMInvocationCall.sequence",
346 )
348 __table_args__ = (
349 # What /stats reads: one person's rows in one workspace.
350 Index("ix_llm_invocations_user_workspace", "user_id", "workspace"),
351 )
354class LLMInvocationCall(FKMixin.LLMModel.NullableChild, DateMixin.Created, Base):
355 """
356 One model call within a traced invocation, as the usage meter saw it.
358 Recorded where the call happened, against the model that was actually
359 built for it — so a graph run whose system nodes run on one model and
360 whose skill nodes pin others says which node called which model, and a
361 retry or a runtime fallback shows the attempt that failed as well as the
362 one that answered. ``provider`` / ``model_name`` are required — every
363 call site names the model it built, and the meter logs one that does
364 not; ``model_id`` is the catalogue link when the model is listed.
366 ``estimated_cost_usd`` is None when the call could not be priced (or
367 failed), never zero for "unknown".
368 """
370 __tablename__ = "llm_invocation_calls"
372 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
374 invocation_id = Column(
375 UUID(as_uuid=True),
376 ForeignKey("llm_invocations.id", ondelete="CASCADE"),
377 nullable=False,
378 index=True,
379 )
380 # Order of the call within its invocation, from 0.
381 sequence = Column(Integer, nullable=False)
383 provider = Column(String(100), nullable=False)
384 model_name = Column(String(255), nullable=False)
385 # ``chat`` or ``embedding``.
386 kind = Column(String(20), nullable=False, default="chat")
387 # The graph node that made the call; null outside a graph.
388 node = Column(String(255), nullable=True)
389 # What the code in that node was doing (``metering.step``): a structured
390 # call's purpose (``retrieval.reranker``) or a ``metering.Step``
391 # (``respond``, ``continuation`` …). A node makes several kinds of call,
392 # and the node alone cannot say which one the tokens went on. Null for an
393 # unlabelled call and every row before migration 27.
394 step = Column(String(64), nullable=True)
395 # Which pass of a graph run made it: 0 the first, 1 the first revision
396 # after the quality check, … Null outside a graph.
397 pass_index = Column(SmallInteger, nullable=True)
399 # Every prompt token (cached or not) and every generated token
400 # (reasoning included); the three below are parts of them, as the
401 # provider reported them, not additions.
402 prompt_tokens = Column(Integer, nullable=False, default=0)
403 completion_tokens = Column(Integer, nullable=False, default=0)
404 cache_read_tokens = Column(Integer, nullable=False, default=0)
405 # All cache writes; ``pricing`` splits out Anthropic's 1-hour ones.
406 cache_write_tokens = Column(Integer, nullable=False, default=0)
407 reasoning_tokens = Column(Integer, nullable=False, default=0)
408 latency_ms = Column(Integer, nullable=True)
410 status = Column(
411 Enum(InvocationEnum.Status, name="invocation_status_enum"),
412 nullable=False,
413 )
414 error_detail = Column(Text, nullable=True)
416 estimated_cost_usd = Column(Numeric(precision=14, scale=8), nullable=True)
417 # How ``estimated_cost_usd`` was reached: the per-token rates applied and
418 # their source, whether the long-context tier repriced the call — or why
419 # it is unpriced. Kept with the call so the figure can be audited after
420 # the catalogue's prices change.
421 pricing = Column(JSON, nullable=True)
423 invocation = relationship("LLMInvocation", back_populates="calls")
425 __table_args__ = (
426 Index("ix_llm_invocation_calls_provider_model", "provider", "model_name"),
427 )
430# ---------------------------------------------------------------------------
431# Tool Invocations
432# ---------------------------------------------------------------------------
435class ToolInvocation(DateMixin.Created, Base):
436 """
437 A single tool call made during an agent execution.
439 Records the tool name, input arguments, raw output, execution outcome,
440 and latency — the primary data source for tool observability and debugging.
442 conversation_id is a soft cross-service reference to svc-core's conversations.id (no FK constraint).
444 execution_context captures free-form metadata about the execution that
445 produced this call (e.g. skill_id, graph node name, agent name) so
446 invocations can be grouped or filtered by workflow.
447 """
449 __tablename__ = "tool_invocations"
451 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
453 # Soft reference to svc-core's conversations.id — no FK constraint
454 conversation_id = Column(UUID(as_uuid=True), nullable=True)
456 # Soft reference to svc-core's users.id — set for user-attributable calls
457 user_id = Column(UUID(as_uuid=True), nullable=True, index=True)
459 # The svc-core workspace the call was made in — see LLMInvocation.
460 workspace = Column(String(80), nullable=True)
462 # svc-core's id for the turn this was part of — see LLMInvocation.
463 core_invocation_id = Column(UUID(as_uuid=True), nullable=True, index=True)
465 # Canonical tool identifier matching ToolDefinition.name in the registry
466 tool_name = Column(String(255), nullable=False, index=True)
468 # Input arguments passed to the tool (serialised as JSON)
469 input_args = Column(JSON, nullable=True)
471 # Raw string output returned by the tool (may be very large)
472 raw_output = Column(Text, nullable=True)
474 # Wall-clock execution time in milliseconds
475 latency_ms = Column(Integer, nullable=True)
477 status = Column(
478 Enum(ToolInvocationEnum.Status, name="tool_invocation_status_enum"),
479 nullable=False,
480 index=True,
481 )
482 error_detail = Column(Text, nullable=True)
484 # Free-form context from the surrounding execution (skill_id, node name, etc.)
485 execution_context = Column(JSON, nullable=True)
487 # What the tool kept beside its output: a web search's report — what
488 # each engine said and what each check removed
489 # (``app/util/web_search_report.py``). Never a result's text.
490 report = Column(JSON, nullable=True)
492 citations = relationship(
493 "ToolCitation",
494 back_populates="invocation",
495 cascade="all, delete-orphan",
496 lazy="selectin",
497 order_by="ToolCitation.index",
498 )
500 __table_args__ = (
501 # Primary query pattern: all tool calls for a conversation
502 Index("ix_tool_invocations_conversation_tool", "conversation_id", "tool_name"),
503 Index("ix_tool_invocations_user_workspace", "user_id", "workspace"),
504 )
507class ToolCitation(FKMixin.ToolInvocation.Child, Base):
508 """
509 A single source citation extracted from a ToolInvocation's output.
511 Each citation captures the tool that produced it, the raw source reference
512 (URL or document name), a human-readable title, and an ordinal index that
513 preserves the order in which sources appeared in the tool response.
515 source_type distinguishes URLs (clickable links) from knowledge-base
516 documents (filename references) and other custom citation kinds, allowing
517 the frontend to render each type appropriately.
519 collection is only populated for query_knowledge_base invocations and
520 records which RAG collection the document was retrieved from.
521 """
523 __tablename__ = "tool_citations"
525 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
527 # Ordinal position within this invocation's result set (1-based)
528 index = Column(Integer, nullable=False)
530 source_type = Column(
531 Enum(ToolInvocationEnum.SourceType, name="tool_citation_source_type_enum"),
532 nullable=False,
533 index=True,
534 )
536 # URL or filename — the canonical reference for this source
537 source = Column(Text, nullable=False)
539 # Human-readable label: page title for web results, filename for documents
540 title = Column(Text, nullable=False)
542 # RAG collection name — only set for query_knowledge_base citations
543 collection = Column(String(255), nullable=True)
545 # Relevance score from the retrieval step (0.0–1.0), when available
546 relevance_score = Column(Float, nullable=True)
548 invocation = relationship("ToolInvocation", back_populates="citations")
550 __table_args__ = (
551 Index("ix_tool_citations_invocation_index", "tool_invocation_id", "index"),
552 )
555# ---------------------------------------------------------------------------
556# Worker Agent Definitions
557# ---------------------------------------------------------------------------
560class WorkerAgentDefinition(DateMixin.Created, Base):
561 """
562 A reusable worker agent definition — the building block for skill graphs.
564 Definitions describe an agent's role, system prompt, default model, and
565 default tools. They are referenced by name in skill graph_definitions so
566 that graphs stay lightweight (no embedded configs) while remaining fully
567 customisable via config_overrides at the node level.
569 is_builtin=True entries are seeded on startup and should not be deleted
570 by regular users.
571 """
573 __tablename__ = "worker_agent_definitions"
575 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
577 name = Column(String(255), unique=True, nullable=False, index=True)
578 display_name = Column(String(255), nullable=False)
579 description = Column(Text, nullable=False)
581 role = Column(
582 Enum(AgentRole, name="agent_role_enum"),
583 nullable=False,
584 index=True,
585 )
587 system_prompt = Column(Text, nullable=False)
589 # Default ModelConfig dict: {provider, model, temperature, max_tokens}
590 default_model_config = Column(JSON, nullable=False)
592 # Single user-facing tool toggle: True → the full general toolset is
593 # bound (web search, url fetch, calculate, geocode, render tools, …);
594 # False → a pure reasoning unit with no tools (routers, loop
595 # controllers, judges). Per-tool selection is deliberately NOT part
596 # of the worker contract — simplicity over configuration surface.
597 tools_enabled = Column(Boolean, nullable=False, default=True)
599 # MCP server descriptors whose tools are loaded into the worker at
600 # execution time: [{"name", "transport", "url" | "command", ...}].
601 # This is the extension point for capabilities beyond the builtin set.
602 mcp_servers = Column(JSON, nullable=False, default=list)
604 # Specialist ToolConfig extras [{name, type, config}] — kept for
605 # webhooks and KB tools; general tools come via tools_enabled.
606 default_tools = Column(JSON, nullable=False, default=list)
608 # Typed interface (see app.agents.interfaces.FieldSpec). input_schema
609 # lists the values a skill node binds into the worker; output_schema —
610 # when non-empty — makes the worker return a schema-validated dict so
611 # downstream nodes and conditional edges can address single fields.
612 input_schema = Column(JSON, nullable=False, default=list)
613 output_schema = Column(JSON, nullable=False, default=list)
615 # Free-form categorisation tags (e.g. ["coding", "analysis"])
616 tags = Column(JSON, nullable=False, default=list)
618 is_builtin = Column(Boolean, nullable=False, default=True)
620 __table_args__ = (UniqueConstraint("name", name="uq_worker_agent_definition_name"),)
623# ---------------------------------------------------------------------------
624# Agent Memories
625# ---------------------------------------------------------------------------
628class AgentMemory(DateMixin.Created, Base):
629 """
630 What an agent keeps of one person between conversations — written by
631 __memory_write__, recalled by __memory_read__ (``app/memory``).
633 external_agent_id and user_id are soft cross-service references to
634 svc-core — no FK constraints so svc-ai remains independently deployable.
635 conversation_id links the memory to the conversation that produced it.
637 ``kind`` is an episode (one turn) or a curated memory (fact, preference,
638 goal) written only from the person's quoted words, kept in ``evidence``.
639 A corrected memory is superseded rather than deleted, so its history
640 stays readable; recall leaves out superseded and expired rows.
641 """
643 __tablename__ = "agent_memories"
645 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
647 # Soft reference to svc-core Agent (no cross-DB FK)
648 external_agent_id = Column(UUID(as_uuid=True), nullable=True, index=True)
650 # Requesting user from svc-core (no FK)
651 user_id = Column(Text, nullable=False, index=True)
653 # Soft reference to the conversation that produced this memory (no FK)
654 conversation_id = Column(UUID(as_uuid=True), nullable=True)
656 # The LangGraph store key used for this entry (uuid4)
657 memory_key = Column(String(255), nullable=False)
659 # An episode: "Task: ...\nResponse: ..."; a curated memory: the statement.
660 content = Column(Text, nullable=False)
662 # Migration 10 made this NOT NULL, unlike the mixin's other tables.
663 created_at = Column(DateTime, nullable=False, default=aware_utcnow)
665 # app.memory.kinds.MemoryKind — every row before migration 28 an episode.
666 kind = Column(
667 String(16), nullable=False, default="episode", server_default="episode"
668 )
669 # A curated memory's grounds: the person's own words it was kept from.
670 evidence = Column(Text, nullable=True)
671 # The svc-core workspace the work was done in (app/common/workspace.py);
672 # null on rows from before migration 28.
673 workspace = Column(String(80), nullable=True)
674 # Its embedding, and the embedder that made it (Embedder.key()): only a
675 # request embedded by the same model is compared with it.
676 embedding = Column(ARRAY(REAL), nullable=True)
677 embedding_key = Column(String(255), nullable=True)
678 # A temporary memory's end: recall leaves it out afterwards.
679 expires_at = Column(DateTime, nullable=True)
680 # Replaced by a correction — the replacing row — and when.
681 superseded_at = Column(DateTime, nullable=True)
682 superseded_by = Column(UUID(as_uuid=True), nullable=True)
683 # When the person last restated it.
684 confirmed_at = Column(DateTime, nullable=True)
685 # How often, and when last, recall sent it to a model.
686 recall_count = Column(Integer, nullable=False, default=0, server_default="0")
687 last_recalled_at = Column(DateTime, nullable=True)
689 __table_args__ = (
690 Index("ix_agent_memories_agent_user", "external_agent_id", "user_id"),
691 )
694class SpendCounter(Base):
695 """Model spend in one period — a UTC day or calendar month — kept for the
696 deployment's spending ceiling (``app.services.spend_guard``).
698 One row per period, ``day:2026-10-08`` or ``month:2026-10``, incremented
699 by every metered call. The guard keeps the running total in memory and
700 writes here so that a restart does not forget what the day has spent.
701 """
703 __tablename__ = "spend_counters"
705 period = Column(String(16), primary_key=True)
706 cost_usd = Column(Numeric(14, 6), nullable=False, server_default="0")
707 updated_at = Column(DateTime, nullable=False, default=aware_utcnow)