# API Documentation

Records provide a transactional, schema-backed data API with full CRUD, structured filtering, and semantic search. Unlike memories, records let you define typed schemas and store structured objects that your AI can query and reason over.

**Use cases:** CRM contacts, product catalogs, knowledge bases, task lists, inventory, support tickets — any structured data your AI needs to read, write, and search.

**AI Integration:** Records can be automatically recalled and learned during chat via the `mnx.records` config — the LLM can read and write structured data as part of the conversation flow.

### 1. Define a Schema

Schemas define the structure of your records. Each schema has a `type_name` and a set of typed fields.

`type_name` required

- **string**: Unique identifier for the record type (e.g., "account", "deal", "ticket").

`fields` required

- **object**: Field definitions — keys are field names, values describe the type and constraints.
  - `display_name`: **string**: Human-readable name for the schema.
  - `description`: **string**: Description of what this record type represents.

```bash
curl -X POST "https://www.mnexium.com/api/v1/records/schemas" \
  -H "x-mnexium-key: $MNX_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type_name": "account",
    "display_name": "Customer Account",
    "description": "CRM customer accounts",
    "fields": {
      "name": { "type": "text", "required": true },
      "industry": { "type": "text" },
      "revenue": { "type": "number" },
      "is_active": { "type": "boolean" }
    }
  }'
```

### 2. Insert Records

Create a record of a given type. The data is validated against the schema and automatically embedded for semantic search.

`data` required

- **object**: Record data matching the schema fields.
- `owner_id`: **string**: Owner subject ID for access control.
- `visibility`: **string**: Access level: "public" (default) or "private".
- `collaborators`: **string[]**: Subject IDs that can read/write this record.

```bash
curl -X POST "https://www.mnexium.com/api/v1/records/account" \
  -H "x-mnexium-key: $MNX_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "data": {
      "name": "TechCorp",
      "industry": "Technology",
      "revenue": 5000000,
      "is_active": true
    },
    "owner_id": "user_123",
    "visibility": "private",
    "collaborators": ["user_456"]
  }'
```

### 3. Get, Update & Delete

Standard CRUD operations on individual records.

```bash
# Get a record
curl "https://www.mnexium.com/api/v1/records/account/rec_abc123" \
  -H "x-mnexium-key: $MNX_KEY"

# Update (partial merge)
curl -X PUT "https://www.mnexium.com/api/v1/records/account/rec_abc123" \
  -H "x-mnexium-key: $MNX_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "data": { "revenue": 7500000 } }'

# Delete (soft)
curl -X DELETE "https://www.mnexium.com/api/v1/records/account/rec_abc123" \
  -H "x-mnexium-key: $MNX_KEY"
```

### 4. Query with Filters

Filter records with field-value matching and server-side sorting.

`where` required
- **object**: Exact-match filter object (all provided fields must match).

`order_by`
- **string**: Field to sort by (prefix with - for descending).

`limit`
- **number**: Max records to return.

`offset`
- **number**: Pagination offset.

```bash
curl -X POST "https://www.mnexium.com/api/v1/records/account/query" \
  -H "x-mnexium-key: $MNX_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "where": {
      "industry": "Technology",
      "is_active": true
    },
    "order_by": "-revenue",
    "limit": 10
  }'
```

```json
// Response
{
  "records": [
    {
      "record_id": "rec_abc123",
      "type_name": "account",
      "data": { "name": "TechCorp", "industry": "Technology", "revenue": 7500000, "is_active": true },
      "owner_id": "user_123",
      "visibility": "private",
      "created_at": "2025-01-15T10:00:00Z"
    }
  ]
}
```

### 5. Semantic Search

Search records by natural language query using pgvector embeddings. Records are automatically embedded on insert/update.

`query` required
- **string**: Natural language search query.

`limit`
- **number**: Max results to return.

```bash
curl -X POST "https://www.mnexium.com/api/v1/records/account/search" \
  -H "x-mnexium-key: $MNX_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "query": "enterprise technology companies", "limit": 5 }'
```

### 6. Access Control

Records support fine-grained access control via `owner_id`, `visibility`, and `collaborators`.

- **Read access**: `public` records are visible to all. `private` records are visible only to the owner and collaborators.
- **Write access**: Only the owner or collaborators can update or delete a record. System actors (no subject_id) bypass ownership checks.

### AI-Powered Records in Chat

Enable automatic record recall and learning during conversations via the `mnx.records` config:

```bash
curl -X POST "https://www.mnexium.com/api/v1/chat/completions" \
  -H "x-mnexium-key: $MNX_KEY" \
  -H "x-openai-key: $OPENAI_KEY" \
  -d '{
    "model": "gpt-4o-mini",
    "messages": [{ "role": "user", "content": "What deals do we have with TechCorp?" }],
    "mnx": {
      "subject_id": "user_123",
      "records": {
        "recall": true,
        "learn": "auto",
        "tables": ["account", "deal"]
      }
    }
  }'
```

When `records.recall: true`, relevant records are injected into the LLM context. Set `records.learn` to "auto", "force", or false. When using "force", `records.tables` is required. Set `records.sync` to true to block the response until writes complete. For dependency graphs (for example, fields typed as `ref:<type>`), partial writes fail the request.

### How `mnx.records` Expands

In chat requests, `mnx.records` controls two independent runtime steps: record recall before generation, and structured extraction after generation.

```json
{
  "mnx": {
    "subject_id": "user_123",
    "records": {
      "recall": true,
      "learn": "force",
      "sync": true,
      "tables": ["account", "deal"]
    }
  }
}
```

- `recall: true` → injects relevant records from selected schemas into model context.
- `learn: "auto"` → runs async selective extraction by default; for streaming requests with explicit write intent and scoped tables, Mnexium attempts a pre-stream write first.
- `learn: "force"` → higher-intent extraction with required table allowlist.
- `sync: true` → response waits for writes; if a dependency graph write is partial, the request fails.
- `tables` → scopes recall/extraction to specific schemas.
- `ref:<type>` fields → extraction plans can link operations using `{ "$ref":"op_id" }` (or `@ref:op_id`) and Mnexium resolves DB-generated record IDs in dependency order.

### Extraction Classifier Timeout

Classification timeout is configurable via `MNX_EXTRACT_CLASSIFY_TIMEOUT_MS`. Values are clamped to `250..15000 ms`. Invalid values fall back to `2000 ms`. 
On timeout/failure, Mnexium keeps existing fallback behavior and routes extraction as `both_unclassified`.
