# TrustMem Quickstart Guide

> Zero Trust Memory for AI Agents — 5 minutes to get started.

## Install

```bash
# Embedded SDK (OpenAI included as required dependency)
pip install trustmem

# Embedded SDK + FastAPI server
pip install "trustmem[server]"

# HTTP client only (separate package, no trustmem dependency)
pip install trustmem-client
```

## Getting Your API Key

TrustMem requires an OpenAI API key (or compatible provider) for embeddings and LLM operations.

1. Go to [platform.openai.com/api-keys](https://platform.openai.com/api-keys)
2. Create a new API key
3. Create a `.env` file in your project root:

```
OPENAI_API_KEY=sk-...
```

TrustMem loads `.env` automatically via `python-dotenv`.

> **Azure / Compatible Providers**: Set `EMBED_PROVIDER=azure` (or `openai_compat`) and provide the appropriate API key / endpoint. See the environment variables table below.

## Configuration

### All Environment Variables

See [README.md](../../README.md#environment-variables) for the full list. Key variables:

| Variable | Default | Description |
|---|---|---|
| `OPENAI_API_KEY` | — | OpenAI API key (required for `openai` provider) |
| `DATABASE_URL` | `~/.trustmem/trustmem.db` | SQLite database path |
| `EMBED_PROVIDER` | `openai` | `openai` \| `azure` \| `openai_compat` |
| `LLM_PROVIDER` | `openai` | `openai` \| `azure` \| `openai_compat` |
| `EMBED_MODEL` | `text-embedding-3-small` | Embedding model name |
| `LLM_MODEL` | `gpt-4o-mini` | LLM model for extraction |
| `EMBED_DIM` | `1536` | Embedding vector dimension |
| `HOST` | `0.0.0.0` | Server bind address |
| `PORT` | `8080` | Server port |
| `TRUSTMEM_API_KEY` | — | API key for Bearer auth (unset = no auth) |
| `CORS_ORIGINS` | `localhost` | Comma-separated allowed CORS origins |
| `TRUSTMEM_MAX_BODY_SIZE` | `10485760` | Max request body size in bytes (10 MB) |
| `TRUSTMEM_BASE_URL` | `http://localhost:8080` | Server URL for TrustMemClient |
| `VECTOR_STORE` | `sqlite` | `sqlite` \| `qdrant` |
| `GRAPH_STORE` | `sqlite` | `sqlite` \| `neo4j` |

## Embedded SDK (TrustMem)

The primary way to use TrustMem. All operations are local, no HTTP server needed.

```python
from trustmem import TrustMem

m = TrustMem()

# Add memories from conversation messages (LLM auto-extraction)
messages = [
    {"role": "user", "content": "I like sushi and live in Tokyo"},
    {"role": "assistant", "content": "Nice! Tokyo is great."},
]
m.add(messages, user_id="user-123")

# Search (hybrid: vector + keyword + RRF fusion)
result = m.search("food preferences", user_id="user-123")
print(result)  # {"results": [...], "relations": [...]}

# Shared knowledge (user_id=NULL)
m.add(messages, visibility="organization")
result = m.search("food preferences", visibility="organization")

# List all memories (scope-aware)
all_memories = m.get_all(user_id="user-123")

# Admin: list all memories (ignores scope)
all_memories = m.list_all()

# Delete a memory
m.delete(memory_id)
```

### Conversation Extraction

All data goes through the LLM extraction pipeline. Pass conversation messages and TrustMem automatically extracts atomic facts:

```python
messages = [
    {"role": "user", "content": "I just moved to Tokyo"},
    {"role": "assistant", "content": "Welcome! How do you like it?"},
    {"role": "user", "content": "I love the food, especially sushi"},
]
m.add(messages, user_id="user-123")
```

The pipeline extracts facts like:
- "User moved to Tokyo" (confidence: high)
- "User loves sushi" (confidence: high)

Key behaviors:
- **User/Assistant separation**: Only facts from user messages are extracted by default
- **Fact verification**: LLM checks factual claims against its knowledge (e.g., outdated political leaders → low confidence)
- **Coexistence**: Multiple preferences coexist without false contradictions (e.g., "likes pizza" + "likes sushi" → both kept)
- **Contradiction detection**: Conflicting facts are automatically detected (e.g., "lives in Tokyo" → "lives in Osaka" → CONTRADICT with winner/loser)

### Management Operations

TrustMem provides 29 methods in total. Scoped methods require either `user_id` or `visibility="organization"` (mutually exclusive). Management operations are available only via the embedded SDK (not exposed through the HTTP server):

```python
# Get a single memory
mem = m.get(memory_id)

# Raw operations (bypass LLM pipeline)
m.add_raw(content="Budget is 5M", confidence="high", source_trust="verified", user_id="user-123")
m.search_raw("budget", user_id="user-123")
m.update_raw(memory_id, content="Budget is 8M", reason="FY2026 revision")

# Investigation (memory trust context)
trail = m.audit_trail(memory_id)
m.contradictions(memory_id)  # What contradicts this memory?
m.provenance(memory_id)      # Where did this memory come from?

# ZTM integrity verification
m.verify(memory_id)
m.verify_all()

# Knowledge graph
m.add_relation("Alex", "likes", "sushi", user_id="user-123")
relations = m.search_relations("Alex", user_id="user-123")
graph = m.get_graph("Alex", user_id="user-123")

# GDPR erasure
m.forget("Alex", dry_run=True)   # Preview impact
m.forget("Alex", reason="gdpr_erasure")  # Execute

# Statistics
m.stats()
m.entity_stats()

# Maintenance
m.backfill_hashes()
m.cleanup_expired()
m.reset()  # Clear all data (development only)
```

## HTTP Server

For remote access, TrustMem includes a FastAPI server that exposes the 4 core CRUD endpoints.

### Start the Server

```bash
pip install "trustmem[server]"
python -m trustmem
# or: trustmem-server
```

The server starts at `http://localhost:8080`.

- Swagger UI: `http://localhost:8080/docs`
- Playground: `http://localhost:8080/playground`

### Authentication

```bash
# No auth (default, for development)
python -m trustmem

# With API key authentication
TRUSTMEM_API_KEY=tm-xxx python -m trustmem
```

When `TRUSTMEM_API_KEY` is set, all `/v1/*` endpoints require a `Bearer` token. The `/health` and `/playground` endpoints are always public.

### Rate Limiting & Security

TrustMem includes basic security features out of the box:

- **Request body size limit**: 10 MB default (configurable via `TRUSTMEM_MAX_BODY_SIZE` env var)
- **CORS**: Restricted to localhost by default (configurable via `CORS_ORIGINS` env var)
- **Startup warning**: Logged when binding to `0.0.0.0` without `TRUSTMEM_API_KEY`

For production deployments, we recommend:

- Always set `TRUSTMEM_API_KEY` for Bearer authentication
- Use a reverse proxy (nginx, Caddy) for rate limiting, TLS, and additional security
- Set `CORS_ORIGINS` to your specific frontend domain(s)

```bash
# Example: production configuration
TRUSTMEM_API_KEY=tm-your-secret-key
CORS_ORIGINS=https://app.example.com,https://admin.example.com
TRUSTMEM_MAX_BODY_SIZE=5242880  # 5 MB
```

### REST API

```bash
# Health check (no auth required)
curl http://localhost:8080/health

# Add memory (conversation messages)
curl -X POST http://localhost:8080/v1/memories \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer tm-xxx" \
  -d '{"data": [{"role": "user", "content": "Hello world"}], "user_id": "user-123"}'

# Search memories
curl -X POST http://localhost:8080/v1/memories/search \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer tm-xxx" \
  -d '{"query": "Hello", "user_id": "user-123"}'

# List memories
curl -H "Authorization: Bearer tm-xxx" \
  "http://localhost:8080/v1/memories?user_id=user-123"

# Delete a memory
curl -X DELETE -H "Authorization: Bearer tm-xxx" \
  "http://localhost:8080/v1/memories/{memory_id}"
```

### Server Endpoints

| HTTP | Path | Auth | Description |
|---|---|---|---|
| POST | `/v1/memories` | Yes (if configured) | Add memory |
| POST | `/v1/memories/search` | Yes (if configured) | Search memories |
| GET | `/v1/memories` | Yes (if configured) | List all memories |
| DELETE | `/v1/memories/{memory_id}` | Yes (if configured) | Delete a memory |
| GET | `/v1/memories/{memory_id}` | Yes (if configured) | Get a single memory |
| GET | `/health` | No | Health check |
| GET | `/v1/version` | Yes (if configured) | Server version |
| GET | `/playground` | No | Interactive playground UI |

## HTTP Client (TrustMemClient)

A lightweight HTTP client for connecting to a remote TrustMem server. Install separately — no `trustmem` dependency needed.

```bash
pip install trustmem-client
```

```python
from trustmem_client import TrustMemClient

# Development (no auth)
client = TrustMemClient(base_url="http://localhost:8080")

# Production (with auth)
client = TrustMemClient(base_url="https://example.com", api_key="tm-xxx")

# Or use environment variables (TRUSTMEM_BASE_URL, TRUSTMEM_API_KEY)
client = TrustMemClient()

# Core CRUD — same interface as TrustMem SDK
client.add([{"role": "user", "content": "Hello world"}], user_id="user-123")
result = client.search("Hello", user_id="user-123")
all_memories = client.get_all(user_id="user-123")
client.delete(memory_id)

client.close()
```

## Zero Trust Memory (ZTM) v2

TrustMem uses a **confidence-based trust model**. Confidence is assigned at write time by LLM screening and updated only when contradictions are detected.

### Confidence Levels

| Confidence | Criteria |
|---|---|
| `high` | Specific, plausible, clearly stated, AND factually correct |
| `medium` | Vague, uncertain, hearsay, or cannot verify (default) |
| `low` | Factually wrong, outdated, or self-contradictory |

### Contradiction Detection (CONTRADICT)

When a new fact conflicts with an existing memory:

1. Both memories are kept
2. A `contradicts` provenance edge is recorded
3. LLM determines the **winner** (`new` / `existing` / `unknown`)
4. Winner's confidence → `high`, Loser's confidence → demoted (LLM-judged)

```
Existing: "Works at Microsoft" (high)
New:      "Works at Google"

→ CONTRADICT, winner: "new"
→ "Works at Google": confidence="high"
→ "Works at Microsoft": confidence="low"
```

### Freshness

Search results include `freshness` (negative integer: days since `last_evaluated_at`) as informational context. No penalty is applied — applications can use this for their own logic.

## Next Steps

- [Full Design Specification](../design/TrustMem_Design.md)
- [README](../../README.md)
