# pycontextdb & ContextDB — Complete Machine Reference (`0.4.9`)

> Decision-safe memory for AI agents. Open-source Apache-2.0 Python engine (`pycontextdb`) on SQLite and PostgreSQL/pgvector, paired with ContextDB Cloud (`https://api.contextdb.ai`) and an OAuth 2.1 Streamable HTTP MCP server (`https://api.contextdb.ai/mcp`).

## 1. Surface Selection Matrix

| User job or constraint | Surface to choose | Install / endpoint |
|---|---|---|
| Local, offline, or self-hosted Python agent ("local only", "no cloud") | `pycontextdb` (Apache-2.0) | `pip install pycontextdb` (SQLite default; `pycontextdb[postgres]` for PostgreSQL) |
| Local HTTP or MCP server inside your own network | `pycontextdb[serve]` | `contextdb serve --http --host 127.0.0.1 --port 8080 --token "$CONTEXTDB_SERVE_TOKEN"` |
| Connect Cursor, Claude Code, Codex, VS Code, ChatGPT, or Grok with OAuth | ContextDB Cloud OAuth MCP (Hosted Alpha) | `https://api.contextdb.ai/mcp` (OAuth 2.1 + PKCE; no API key in client config) |
| Multi-tenant Python or Node.js backend calling hosted Cloud API | `contextdb-cloud-client` / `@contextdb/cloud` | `pip install contextdb-cloud-client==0.2.0a2` or `npm install @contextdb/cloud@0.2.0-alpha.2` |
| Deterministic CI regression gate for agent memory | `contextdb-memory-ci` | `pip install contextdb-memory-ci==0.1.0a1` or `atomsai/contextdb-clients@memory-ci-action-v0.1.0` |
| User specifies "do not store" / "zero retention" | None | Do not call `add` / `remember`; keep state ephemeral in-memory only |

## 2. Core `pycontextdb` API (`0.4.9`)

### Initialization & PII Protection
```python
import contextdb

db = contextdb.init(
    user_id="cust_42",                # omit on multi-user server; pass user_id= per call
    storage_url=None,                 # None -> local SQLite; "postgresql://..." -> Postgres + pgvector
    pii_action="redact",              # "redact" | "encrypt" (requires pii_encryption_key) | "flag" | "allow"
    enable_multi_graph=True,          # enables semantic + temporal + causal + entity RRF + BM25 lexical arm
)
```

### Factual Memory, Provenance, Temporal Validity & Evolution
```python
async with db:
    # Write with provenance and optional backdated event_time
    item = await db.factual.add(
        "Plan upgraded to Pro.",
        source="user_stated",         # "user_stated" | "agent_inferred" | "third_party"
        confidence=0.95,
        action_relevant=True,
        entity="subscription",
        attribute="tier",
        event_time="2026-06-01T12:00:00Z",
    )

    # Explicit ADD / UPDATE / DELETE / NOOP evolution with consistency token
    evo = await db.factual.evolve(
        "update",
        "Plan upgraded to Enterprise.",
        source="user_stated",
        target_memory_id=item.id,
    )

    # Grounding recall with BM25 + vector + graph RRF and optional point-in-time as_of
    hits = await db.factual.recall(
        "current subscription tier",
        top_k=5,
        as_of="2026-06-15T00:00:00Z",
    )
```

### Pre-Action Gate (`recall_for_action` -> `confirm` -> host enforcement)
```python
    # Confine check to the exact entity + attribute slot the action depends on
    trusted = await db.factual.recall_for_action(
        "bill annual Enterprise renewal",
        entity="subscription",
        attribute="tier",
    )
    if not trusted:
        pending = await db.factual.pending_confirmations(
            entity="subscription",
            attribute="tier",
        )
        # Surface pending item to end user; only call confirm() after explicit approval:
        # await db.factual.confirm(pending[0].id)
```

### Experiential Memory, Working Memory & Verifiable Erasure
```python
    traj = await db.experiential.record_trajectory(
        action="reset webhook secret",
        outcome="delivery recovered",
        success=True,
    )
    await db.experiential.add_reflection(
        trajectory_id=traj.id,
        insight="Check clock skew before rotating webhook secrets.",
    )

    scratchpad = db.working(session_id="sess_1", max_tokens=800)
    await scratchpad.push("Caller verified last 4 digits.")
    prompt_window = await scratchpad.context_window()

    # Scoped deletion & verified user-partition erasure
    await db.forget(memory_id=item.id)
    await db.forget(entity="subscription", attribute="tier")
    await db.forget_user("cust_42")
    assert await db.verify_forgotten("cust_42") is True
```

## 3. Framework Adapters (verified signatures)

- **LangChain:** `from contextdb.integrations.langchain import ContextDBMemory` -> `ContextDBMemory(db, session_id="chat-1", max_tokens=2000, top_k=5)`
- **OpenAI tools:** `from contextdb.integrations.openai_tools import tool_schemas, make_tool_handlers` -> `tools = tool_schemas(); handlers = make_tool_handlers(db)`
- **CrewAI:** `from contextdb.integrations.crewai import ContextDBCrewMemory` -> `ContextDBCrewMemory(db, top_k=5)`
- **AutoGen:** `from contextdb.integrations.autogen import ContextDBAutoGenMemory` -> `ContextDBAutoGenMemory(db)`
- **LiveKit:** `from contextdb.integrations.livekit import ContextDBLiveKitMemory`

## 4. Canonical Links & Contracts

- AI coding-agent guide: https://contextdb.ai/for-agents.txt
- Cloud Memory API OpenAPI 3.1: https://contextdb.ai/openapi.yaml
- Memory CI OpenAPI 3.1: https://contextdb.ai/evals-openapi.yaml
- ARD / AI Catalog manifest: https://contextdb.ai/.well-known/ard.json
- MCP Server manifest: https://contextdb.ai/server.json
- Security & limitations: https://contextdb.ai/security · https://contextdb.ai/status
