# `ai.db` — Module Overview

> This document is partially auto-generated. Sections tagged `<!-- AUTO:id -->` are refreshed by the generator.
> Everything else is yours to edit freely and will never be overwritten.

<!-- AUTO:meta -->
## About This Document

This file is **partially auto-generated**. Sections wrapped in `<!-- AUTO:id -->` tags
are overwritten each time the generator runs. Everything else is yours to edit freely.

| Field | Value |
|-------|-------|
| Module | `matrx_ai/db` |
| Last generated | 2026-04-07 11:38 |
| Output file | `matrx_ai/db/MODULE_README.md` |
| Signature mode | `signatures` |


**Child READMEs detected** (signatures collapsed — see links for detail):

| README | |
|--------|---|
| [`matrx_ai/db/ai_models/MODULE_README.md`](matrx_ai/db/ai_models/MODULE_README.md) | last generated 2026-04-07 11:38 |
| [`matrx_ai/db/content_types/MODULE_README.md`](matrx_ai/db/content_types/MODULE_README.md) | last generated 2026-04-07 11:38 |
**To refresh auto-sections:**
```bash
python utils/code_context/generate_module_readme.py matrx_ai/db --mode signatures
```

**To add permanent notes:** Write anywhere outside the `<!-- AUTO:... -->` blocks.
<!-- /AUTO:meta -->

<!-- HUMAN-EDITABLE: This section is yours. Agents & Humans can edit this section freely — it will not be overwritten. -->

## Architecture

> **Fill this in.** Describe the execution flow and layer map for this module.
> See `utils/code_context/MODULE_README_SPEC.md` for the recommended format.
>
> Suggested structure:
>
> ### Layers
> | File | Role |
> |------|------|
> | `entry.py` | Public entry point — receives requests, returns results |
> | `engine.py` | Core dispatch logic |
> | `models.py` | Shared data types |
>
> ### Call Flow (happy path)
> ```
> entry_function() → engine.dispatch() → implementation()
> ```


<!-- AUTO:tree -->
## Directory Tree

> Auto-generated. 28 files across 4 directories.

```
matrx_ai/db/
├── MODULE_README.md
├── __init__.py
├── _registry.py
├── agx_manager.py
├── ai_models/
│   ├── MODULE_README.md
│   ├── __init__.py
│   ├── ai_model_base.py
│   ├── ai_model_dto.py
│   ├── ai_model_manager.py
│   ├── ai_model_validator.py
│   ├── duplicate_models.py
│   ├── tests.py
├── content_types/
│   ├── MODULE_README.md
│   ├── data_ref.py
│   ├── data_ref_utils.ts
│   ├── notes.py
│   ├── patch_utils.py
│   ├── tasks.py
│   ├── tests.py
│   ├── picklists.py
│   ├── datasets.py
├── conversation_gate.py
├── conversation_rebuild.py
├── cx_managers.py
├── guest_registry.py
├── persistence.py
├── tests/
│   ├── agx_tests.py
│   ├── db_tests.py
# excluded: 4 .md, 2 .json
```
<!-- /AUTO:tree -->

<!-- AUTO:signatures -->
## API Signatures

> Auto-generated via `output_mode="{mode}"`. ~5-10% token cost vs full source.
> For full source, open the individual files directly.
> Submodules with their own `MODULE_README.md` are collapsed to a single stub line.

```
---
Filepath: matrx_ai/db/conversation_gate.py  [python]

  class ConversationGateError(Exception):
  def _is_valid_uuid(value: str | None) -> bool
  def _require_valid_user_id(user_id: str | None, context: str = '') -> str
  async def create_new_conversation(conversation_id: str, user_id: str, metadata: dict[str, Any] | None = None) -> None
  async def ensure_conversation_exists(conversation_id: str, user_id: str, parent_conversation_id: str | None = None) -> None
  async def _log_guest_execution(fingerprint: str, conversation_id: str, ip_address: str | None, user_agent: str | None) -> None
  async def verify_existing_conversation(conversation_id: str) -> dict[str, Any]
  async def update_conversation_status(conversation_id: str, status: str) -> None
  async def create_pending_user_request(request_id: str, user_id: str) -> None
  async def ensure_user_request_exists(request_id: str, user_id: str) -> None
  async def update_user_request_status(request_id: str, status: str, error: str | None = None) -> None
  def launch_conversation_gate(conversation_id: str, is_new_conversation: bool, execution_task: asyncio.Task[Any]) -> asyncio.Task[Any] | None
  async def _gate_task() -> None
  def _on_gate_done(t: asyncio.Task[Any]) -> None
  async def _send_fatal() -> None



---
Filepath: matrx_ai/db/agx_manager.py  [python]

  AgxAgentBase = get_base('AgxAgentBase')
  AgxVersionBase = get_base('AgxVersionBase')
  AgxShortcutBase = get_base('AgxShortcutBase')
  AgxAgent = get_model('AgxAgent')
  AgxVersion = get_model('AgxVersion')
  AgxShortcut = get_model('AgxShortcut')
  class AgxAgentManager(AgxAgentBase):
      def __new__(cls, *args: Any, **kwargs: Any) -> AgxAgentManager
      def __init__(self) -> None
      async def _initialize_runtime_data(self, item: AgxAgent) -> None
      async def to_config(self, agent_id: str) -> AgentConfig
  class AgxVersionManager(AgxVersionBase):
      def __new__(cls, *args: Any, **kwargs: Any) -> AgxVersionManager
      def __init__(self) -> None
      async def _initialize_runtime_data(self, item: AgxVersion) -> None
      async def to_config(self, version_id: str) -> AgentConfig
  class AgxShortcutManager(AgxShortcutBase):
      def __new__(cls, *args: Any, **kwargs: Any) -> AgxShortcutManager
      def __init__(self) -> None
      async def _initialize_runtime_data(self, item: AgxShortcut) -> None
  class AgxManagers:
      def __new__(cls, *args: Any, **kwargs: Any) -> AgxManagers
      def __init__(self) -> None
      async def load_for_execution(self, resolved_id: str, is_version: bool = False) -> AgentConfig
  def _row_to_config(row: Any) -> AgentConfig



---
Filepath: matrx_ai/db/persistence.py  [python]

  def _is_valid_uuid(value: str | None) -> bool
  async def _backfill_tool_call_message_id(msg: dict[str, Any], message_id: str, conversation_id: str) -> None
  async def persist_completed_request(completed: CompletedRequest, conversation_id: str | None = None, debug: bool = False) -> dict[str, Any]



---
Filepath: matrx_ai/db/__init__.py  [python]




---
Filepath: matrx_ai/db/guest_registry.py  [python]

  async def _create_anon_auth_user() -> str
  async def resolve_guest_uuid(fingerprint: str, ip_address: str | None = None, user_agent: str | None = None) -> str
  async def log_guest_execution(fingerprint: str, resource_type: str, resource_id: str | None = None, resource_name: str | None = None, ip_address: str | None = None, user_agent: str | None = None) -> None
  async def link_guest_to_user(fingerprint: str, real_user_id: str) -> bool



---
Filepath: matrx_ai/db/_registry.py  [python]

  class DBNotConfiguredError(RuntimeError):
  def _not_configured_msg(kind: str, name: str) -> str
  def configure_db(*, models: dict[str, Any] | None = None, bases: dict[str, Any] | None = None, instances: dict[str, Any] | None = None, extras: dict[str, Any] | None = None) -> None
  def is_configured() -> bool
  def get_model(name: str) -> Any
  def get_base(name: str) -> Any
  def get_instance(name: str) -> Any
  def get_extra(name: str) -> Any



---
Filepath: matrx_ai/db/conversation_rebuild.py  [python]

  CxMessage = get_model('CxMessage')
  CxToolCall = get_model('CxToolCall')
  CxMedia = get_model('CxMedia')
  def _rebuild_tool_result_content(tool_calls: list[CxToolCall]) -> list[dict[str, Any]]
  async def _map_tool_calls_to_messages(messages: list[CxMessage], tool_calls: list[CxToolCall]) -> dict[str, list[CxToolCall]]
  async def rebuild_conversation_messages(raw_messages: list[CxMessage], tool_calls: list[CxToolCall], media: list[CxMedia]) -> list[CxMessage]



---
Filepath: matrx_ai/db/cx_managers.py  [python]

  CxAgentMemoryBase = get_base('CxAgentMemoryBase')
  CxRequestBase = get_base('CxRequestBase')
  CxToolCallBase = get_base('CxToolCallBase')
  CxUserRequestBase = get_base('CxUserRequestBase')
  CxMessageBase = get_base('CxMessageBase')
  CxMediaBase = get_base('CxMediaBase')
  CxConversationBase = get_base('CxConversationBase')
  CxMessage = get_model('CxMessage')
  CxToolCall = get_model('CxToolCall')
  CxMedia = get_model('CxMedia')
  CxUserRequest = get_model('CxUserRequest')
  CxRequest = get_model('CxRequest')
  CxAgentMemory = get_model('CxAgentMemory')
  CxConversation = get_model('CxConversation')
  class CxToolCallManager(CxToolCallBase):
      def __new__(cls, *args: Any, **kwargs: Any) -> CxToolCallManager
      def __init__(self) -> None
      async def _initialize_runtime_data(self, item: CxToolCall) -> None
  class CxConversationManager(CxConversationBase):
      def __new__(cls, *args: Any, **kwargs: Any) -> CxConversationManager
      def __init__(self) -> None
      async def _initialize_runtime_data(self, item: CxConversation) -> None
  class CxMediaManager(CxMediaBase):
      def __new__(cls, *args: Any, **kwargs: Any) -> CxMediaManager
      def __init__(self) -> None
      async def _initialize_runtime_data(self, item: CxMedia) -> None
  class CxMessageManager(CxMessageBase):
      def __new__(cls, *args: Any, **kwargs: Any) -> CxMessageManager
      def __init__(self) -> None
      async def _initialize_runtime_data(self, item: CxMessage) -> None
  class CxUserRequestManager(CxUserRequestBase):
      def __new__(cls, *args: Any, **kwargs: Any) -> CxUserRequestManager
      def __init__(self) -> None
      async def _initialize_runtime_data(self, item: CxUserRequest) -> None
  class CxRequestManager(CxRequestBase):
      def __new__(cls, *args: Any, **kwargs: Any) -> CxRequestManager
      def __init__(self) -> None
      async def _initialize_runtime_data(self, item: CxRequest) -> None
      async def get_conversation_cost_summary(self, conversation_id: str) -> ConversationCostSummary
  class CxAgentMemoryManager(CxAgentMemoryBase):
      def __new__(cls, *args: Any, **kwargs: Any) -> CxAgentMemoryManager
      def __init__(self) -> None
      async def _initialize_runtime_data(self, item: CxAgentMemory) -> None
  class CxManagers:
      def __new__(cls, *args: Any, **kwargs: Any) -> CxManagers
      def __init__(self) -> None
      async def get_conversation_data(self, conversation_id: str) -> dict[str, Any]
      async def get_unified_config(self, flat_data: dict[str, Any]) -> UnifiedConfig
      async def get_conversation_unified_config(self, conversation_id: str) -> UnifiedConfig
      async def get_full_conversation(self, conversation_id: str) -> dict[str, Any]
      async def get_conversation_cost_summary(self, conversation_id: str) -> ConversationCostSummary



---
Submodule: matrx_ai/db/content_types/  [8 files — full detail in matrx_ai/db/content_types/MODULE_README.md]

---
Submodule: matrx_ai/db/ai_models/  [7 files — full detail in matrx_ai/db/ai_models/MODULE_README.md]

```
<!-- /AUTO:signatures -->

<!-- AUTO:dependencies -->
## Dependencies

**External packages:** initialize_systems, matrx_connect, matrx_orm, matrx_utils, supabase_auth
**Internal modules:** matrx_ai._ext, matrx_ai.agents, matrx_ai.config, matrx_ai.context, matrx_ai.orchestrator, matrx_ai.reports, matrx_ai.tools
<!-- /AUTO:dependencies -->

<!-- AUTO:config -->
## Generation Config

> Auto-managed. Contains the exact parameters used to generate this README.
> Used by parent modules to auto-refresh this file when it is stale.
> Do not edit manually — changes will be overwritten on the next run.

```json
{
  "subdirectory": "matrx_ai/db",
  "mode": "signatures",
  "scope": null,
  "project_noise": null,
  "include_call_graph": false,
  "entry_points": null,
  "call_graph_exclude": [
    "tests"
  ],
  "signatures_exclude": [
    "tests",
    "db",
    "local_data",
    "docs"
  ]
}
```
<!-- /AUTO:config -->

<!-- AUTO:callers -->
## Upstream Callers

> Auto-discovered by scanning all project files that import from this module.
> Set `ENTRY_POINTS` in `generate_readme.py` to pin specific functions.

| Caller | Calls |
|--------|-------|
| `matrx_ai/agents/services/batch_categorize.py` | `ensure_conversation_exists()` |
| `matrx_ai/orchestrator/executor.py` | `ensure_conversation_exists()` |
| `matrx_ai/tests/execution_test.py` | `ensure_conversation_exists()` |
| `matrx_ai/agents/services/batch_categorize.py` | `ensure_user_request_exists()` |
| `matrx_ai/orchestrator/executor.py` | `ensure_user_request_exists()` |
| `matrx_ai/tests/execution_test.py` | `ensure_user_request_exists()` |
| `matrx_ai/agents/DEPRECATED_prompts_manager.py` | `get_base()` |
| `matrx_ai/tools/tools_db.py` | `get_base()` |
| `matrx_ai/instructions/content_blocks_manager.py` | `get_extra()` |
| `matrx_ai/agents/DEPRECATED_prompts_manager.py` | `get_model()` |
| `matrx_ai/config/message_config.py` | `get_model()` |
| `matrx_ai/instructions/content_blocks_manager.py` | `get_model()` |
| `matrx_ai/instructions/matrx_fetcher.py` | `get_model()` |
| `matrx_ai/instructions/tests/direct_fetch_test.py` | `get_model()` |
| `matrx_ai/instructions/tests/user_table_data_test.py` | `get_model()` |
| `matrx_ai/tests/prompts/prompt_to_config.py` | `get_model()` |
| `matrx_ai/orchestrator/executor.py` | `persist_completed_request()` |
| `matrx_ai/config/structured_input_config.py` | `resolve_data_refs()` |
| `matrx_ai/orchestrator/executor.py` | `update_conversation_status()` |
| `matrx_ai/orchestrator/executor.py` | `update_user_request_status()` |
<!-- /AUTO:callers -->
